TypeScript
fix(server): Stop on a delegate always clears it, even when it is stuck (#22653)
Theo Browne6a6c84f9906c
diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.tsindex c037370d451..015cf1f5769 100644--- a/apps/server/src/mcp/OrchestratorMcpService.test.ts+++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts@@ -420,6 +420,7 @@ describe("OrchestratorMcpService", () => {: Effect.succeed(childProjection),getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)),delegatedTaskResultPending: () => Effect.succeed(false),+ stopDelegatedTasks: () => Effect.void,// The orchestrator's subagent.stop repair is covered in ThreadStop.test.ts.dispatch: (command) =>Ref.update(dispatched, (commands) => [...commands, command]).pipe(@@ -458,9 +459,15 @@ describe("OrchestratorMcpService", () => {clientRequestId: "cancel-orphan-task",});assert.deepEqual(result, { taskId, status: "cancelled" });- const [stop, ...rest] = yield* Ref.get(dispatched);- assert.isEmpty(rest);- assert.equal(stop?.type, "subagent.stop");+ const commands = yield* Ref.get(dispatched);+ // A child whose run finished can still run another turn's work, so it is stopped too.+ assert.deepEqual(+ commands.flatMap((command) =>+ command.type === "thread.stop" ? [command.threadId] : [],+ ),+ childState === "a finished run" ? [childThreadId] : [],+ );+ const stop = commands.find((command) => command.type === "subagent.stop");if (stop?.type !== "subagent.stop") return;assert.deepEqual({ threadId: stop.threadId, runId: stop.runId, subagentId: stop.subagentId },diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.tsindex 7d88e4d5f75..f1ac8c57038 100644--- a/apps/server/src/mcp/OrchestratorMcpService.ts+++ b/apps/server/src/mcp/OrchestratorMcpService.ts@@ -2359,8 +2359,7 @@ const make = Effect.gen(function* () {),);// A follow-up that lost its child run (#19002) stays running on the parent, while its- // status here comes from the child's last run. The parent cancels it, and any other- // orphan of the same child, when that child is idle.+ // status here comes from the child's last run. Stop on the parent cancels that task.const cancelOrphan = Effect.gen(function* () {if (parentTask?.runId == null || !isOrchestrationV2WorkActive(parentTask.status))return false;@@ -2383,12 +2382,13 @@ const make = Effect.gen(function* () {return subagents.some((task) => task.id === input.taskId && task.status === "cancelled");});if (isTerminalTaskStatus(current.status)) {- if (yield* cancelOrphan) return { taskId: input.taskId, status: "cancelled" };+ // The child can still run work for another turn, so it is stopped either way.yield* stopWithinLimit;+ const cancelled = yield* cancelOrphan;yield* disposeCompletionDelivery;return {taskId: input.taskId,- status: current.status,+ status: cancelled ? "cancelled" : current.status,} satisfies OrchestratorMcpTaskCancelResult;}const child = yield* loadProjection(current.childThreadId);diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.tsindex 7094be95897..22d3de23a69 100644--- a/apps/server/src/orchestration-v2/Orchestrator.ts+++ b/apps/server/src/orchestration-v2/Orchestrator.ts@@ -539,6 +539,20 @@ function withoutPreparationResult(return rest;}+/** Stop ended this task, so its result is not delivered to the parent agent. */+function cancelledAppOwnedTask(+ task: OrchestrationV2Subagent,+ now: DateTime.Utc,+): OrchestrationV2Subagent {+ return {+ ...task,+ status: "cancelled",+ completedAt: now,+ updatedAt: now,+ completionDelivery: { state: "disposed", observedByRunId: null },+ };+}+function isBlockingRun(run: OrchestrationV2Run): boolean {return (run.status === "preparing" ||@@ -9397,22 +9411,46 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio]);const run = projection.runs.find((candidate) => candidate.id === command.runId);const subagent = projection.subagents.find((candidate) => candidate.id === command.subagentId);- // An app-owned task stops through its child thread. Here the parent only cancels the child's- // orphaned tasks: the child is idle and no child run is bound to them (#19002).+ // A user Stop cancels an app-owned task here when nothing else can settle it: no child run was+ // ever bound to it and it is not the child's original task (#19002). This holds whatever else+ // the child is doing. A task with a bound run, live or ended, keeps its settlement path, since+ // its result may still be on the way, and the child stop the client sends next interrupts the+ // run. A task that already ended is written again, so a client holding a stale copy, such as+ // one cached before a repair, shows it ended.if (subagent?.origin === "app_owned" &&subagent.childThreadId !== null &&subagent.runId === command.runId) {- const records = yield* loadProjectionForCommand(command, ["subagents", "turnItems"], {+ const childThreadId = subagent.childThreadId;+ const child = yield* projectionStore.getThreadRecords(childThreadId, ["runs"]).pipe(+ Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }),+ Effect.mapError(+ (cause) => new OrchestratorProjectionError({ threadId: childThreadId, cause }),+ ),+ );+ const active = isOrchestrationV2WorkActive(subagent.status);+ if (+ active &&+ child !== null &&+ ((child.thread.forkedFrom?.type === "node" &&+ child.thread.forkedFrom.nodeId === subagent.id) ||+ child.runs.some((run) => run.delegatedTaskId === subagent.id))+ )+ return;+ const records = yield* loadProjectionForCommand(command, ["nodes", "turnItems"], {turnItemTypes: ["subagent"],- turnItemStatuses: ["pending", "running", "waiting"],+ turnItemRunIds: [subagent.runId],+ omitSettledLeafNodes: true,});- return yield* cancelIdleOrphans({+ const now = yield* DateTime.now;+ return yield* writeAppOwnedTask({command,events,- projection: records,- childThreadId: subagent.childThreadId,+ task: active ? cancelledAppOwnedTask(subagent, now) : subagent,+ nodes: records.nodes,+ turnItems: records.turnItems,+ now,});}if (@@ -9857,16 +9895,56 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioreturn undefined;});+ /** Writes a parent's app-owned task, and sets its node and turn items to the task's status. */+ const writeAppOwnedTask = Effect.fn("Orchestrator.writeAppOwnedTask")(function* (input: {+ readonly command: Extract<+ OrchestrationV2ServerCommand,+ { readonly type: "run.interrupt" | "thread.stop" | "subagent.stop" }+ >;+ readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;+ readonly task: OrchestrationV2Subagent;+ readonly nodes: ReadonlyArray<OrchestrationV2ExecutionNode>;+ readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;+ readonly now: DateTime.Utc;+ }) {+ const { command, task, now } = input;+ const emitEvent = emit(input.events, command);+ yield* emitEvent({+ type: "subagent.updated",+ threadId: command.threadId,+ nodeId: task.id,+ occurredAt: now,+ payload: task,+ });+ const node = input.nodes.find((candidate) => candidate.id === task.id);+ if (node !== undefined)+ yield* emitEvent({+ type: "node.updated",+ threadId: command.threadId,+ nodeId: node.id,+ occurredAt: now,+ payload: { ...node, status: task.status, completedAt: task.completedAt },+ });+ for (const item of input.turnItems) {+ if (item.type !== "subagent" || item.subagentId !== task.id) continue;+ yield* emitEvent({+ type: "turn-item.updated",+ threadId: command.threadId,+ nodeId: task.id,+ occurredAt: now,+ payload: { ...item, status: task.status, completedAt: task.completedAt, updatedAt: now },+ });+ }+ });+const cancelIdleOrphans = Effect.fn("Orchestrator.cancelIdleOrphans")(function* (input: {readonly command: Extract<OrchestrationV2ServerCommand,- { readonly type: "run.interrupt" | "thread.stop" | "subagent.stop" }+ { readonly type: "run.interrupt" | "thread.stop" }>;readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;readonly projection: Pick<OrchestrationV2ThreadProjection, "subagents" | "turnItems">;- /** Limits the repair to tasks delegated to this child thread. */- readonly childThreadId?: ThreadId;}) {const { command, events, projection } = input;const pending = yield* Ref.get(events);@@ -9884,8 +9962,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioif (task.origin !== "app_owned" ||task.childThreadId === null ||- !isOrchestrationV2WorkActive(task.status) ||- (input.childThreadId !== undefined && task.childThreadId !== input.childThreadId)+ !isOrchestrationV2WorkActive(task.status))continue;const childThreadId = task.childThreadId;@@ -9932,40 +10009,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioif (!idle) continue;// Stop can cancel an idle orphan without guessing which completed run owned its result.const now = yield* DateTime.now;- const emitEvent = emit(events, command);- yield* emitEvent({- type: "subagent.updated",- threadId: command.threadId,- nodeId: task.id,- occurredAt: now,- payload: {- ...task,- status: "cancelled",- completedAt: now,- updatedAt: now,- completionDelivery: { state: "disposed", observedByRunId: null },- },- });nodes ??= (yield* projectionStore.getThreadRecords(command.threadId, ["nodes"])).nodes;- const node = nodes.find((candidate) => candidate.id === task.id);- if (node !== undefined)- yield* emitEvent({- type: "node.updated",- threadId: command.threadId,- nodeId: node.id,- occurredAt: now,- payload: { ...node, status: "cancelled", completedAt: now },- });- for (const item of projection.turnItems) {- if (item.type !== "subagent" || item.subagentId !== task.id) continue;- yield* emitEvent({- type: "turn-item.updated",- threadId: command.threadId,- nodeId: task.id,- occurredAt: now,- payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },- });- }+ yield* writeAppOwnedTask({+ command,+ events,+ task: cancelledAppOwnedTask(task, now),+ nodes,+ turnItems: projection.turnItems,+ now,+ });}},(effect, input) =>diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.tsindex e041b5628bb..c8b49000876 100644--- a/apps/server/src/orchestration-v2/ThreadStop.test.ts+++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts@@ -166,6 +166,8 @@ it.effect.each([["idle", "run.interrupt"],["idle", "subagent.stop"],["running", "subagent.stop"],+ ["bound", "subagent.stop"],+ ["correlated", "subagent.stop"],["archived", "thread.stop"],["missing", "thread.stop"],["running", "thread.stop"],@@ -178,7 +180,7 @@ it.effect.each([["question", "thread.stop"],["restart", "thread.stop"],] as const)(- "Stop clears an orphaned follow-up only when its child is finished (%s via %s)",+ "Stop clears an orphaned follow-up when its child is finished; its own Stop does unless a run is bound (%s via %s)",([childState, type]) =>Effect.gen(function* () {const orchestrator = yield* Orchestrator.OrchestratorV2;@@ -279,7 +281,9 @@ it.effect.each([const childRunStatus =childState === "running" || childState === "queued" || childState === "waiting"? childState- : "completed";+ : childState === "bound"+ ? "running"+ : "completed";yield* apply({type: "run.updated",threadId: childThreadId,@@ -299,12 +303,14 @@ it.effect.each([...runAtStart,status: childRunStatus,completedAt: childRunStatus === "completed" ? now : null,- ...(childState === "correlated" ? { delegatedTaskId: taskId } : {}),+ ...(childState === "correlated" || childState === "bound"+ ? { delegatedTaskId: taskId }+ : {}),},});assert.equal((yield* orchestrator.getThreadProjection(childThreadId)).runs[0]?.delegatedTaskId,- childState === "correlated" ? taskId : undefined,+ childState === "correlated" || childState === "bound" ? taskId : undefined,);if (childState === "provider-active" || childState === "roster") {yield* apply({@@ -438,7 +444,13 @@ it.effect.each([(after.thread.pullRequests ?? []).filter((link) => link.watch !== undefined),type === "subagent.stop" ? 1 : 0,);- const expected = childState === "idle" || childState === "archived" ? "cancelled" : "running";+ // A task with a bound run, live or ended, keeps its settlement path.+ const expected =+ childState === "bound" || childState === "correlated"+ ? "running"+ : type === "subagent.stop" || childState === "idle" || childState === "archived"+ ? "cancelled"+ : "running";assert.equal(after.subagents.find((task) => task.id === taskId)?.status, expected);assert.equal(after.nodes.find((node) => node.id === taskId)?.status, expected);assert.equal(after.turnItems.find((item) => item.id === itemId)?.status, expected);@@ -468,6 +480,28 @@ it.effect.each([assert.equal(repeated.subagents.find((task) => task.id === taskId)?.status, "cancelled");assert.deepEqual(repeated.messages, after.messages);assert.deepEqual(repeated.contextTransfers, after.contextTransfers);+ if (type === "subagent.stop") {+ // A client that missed the cancel, such as one resumed from an older cache, still+ // shows the task as running. Its Stop gets the ended task back.+ const eventStore = yield* EventStore.EventStoreV2;+ const afterSequence = yield* eventStore.latestSequence({ threadId: parentThreadId });+ yield* orchestrator.dispatch({+ ...stop,+ commandId: CommandId.make(`stop-orphan-stale-client:${childState}`),+ type,+ runId: original.runId!,+ subagentId: taskId,+ });+ const resent = yield* eventStore+ .read({ threadId: parentThreadId, afterSequence })+ .pipe(Stream.runCollect);+ assert.deepEqual(+ resent.flatMap(({ event }) =>+ event.type === "subagent.updated" ? [event.payload.status] : [],+ ),+ ["cancelled"],+ );+ }}}).pipe(Effect.provide(layerTest)),);diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.tsindex edb9d70ef6f..e28df43e6a2 100644--- a/packages/client-runtime/src/operations/commands.ts+++ b/packages/client-runtime/src/operations/commands.ts@@ -774,7 +774,7 @@ export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreaconst projection = yield* getProjection(input.threadId);const subagent = projection.subagents.find((agent) => agent.id === input.subagentId);if (subagent?.origin === "app_owned" && subagent.childThreadId !== null) {- // The parent cancels the task if it is an orphan with an idle child (#19002). Older+ // The parent ends the task even when its child lost track of it (#19002). Older// servers reject this for app-owned tasks, so the child stop below still runs.if (subagent.runId !== null) {yield* dispatch({