TypeScript
fix(server): idle orphaned follow-ups can be cancelled without a running parent (#22581)
Theo Browne849b3f894803
diff --git a/apps/server/src/mcp/OrchestratorMcpService.test.ts b/apps/server/src/mcp/OrchestratorMcpService.test.tsindex a3f43ef892f..c037370d451 100644--- a/apps/server/src/mcp/OrchestratorMcpService.test.ts+++ b/apps/server/src/mcp/OrchestratorMcpService.test.ts@@ -14,6 +14,7 @@ import {ProviderInstanceId,RunId,ThreadId,+ type OrchestrationV2ServerCommand,type OrchestrationV2ThreadProjection,type ServerProvider,} from "@t3tools/contracts";@@ -366,6 +367,109 @@ describe("OrchestratorMcpService", () => {}),);+ it.effect.each(["no runs", "a finished run"] as const)(+ "cancels an orphaned follow-up through its parent when the child has %s",+ (childState) =>+ Effect.gen(function* () {+ const parentThreadId = ThreadId.make("thread:mcp-orphan-parent");+ const childThreadId = ThreadId.make("thread:mcp-orphan-child");+ const taskId = NodeId.make("node:mcp-orphan-task");+ const parentRunId = RunId.make("run:mcp-orphan-parent");+ const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationV2ServerCommand>>([]);+ const status = yield* Ref.make("running");+ const parentProjection = (taskStatus: string) =>+ ({+ thread: { id: parentThreadId },+ runs: [],+ contextTransfers: [],+ subagents: [+ {+ id: taskId,+ threadId: parentThreadId,+ runId: parentRunId,+ origin: "app_owned",+ childThreadId,+ driver: "codex",+ model: "gpt-5.6-terra",+ status: taskStatus,+ result: null,+ completionDelivery: { state: "pending" },+ },+ ],+ }) as unknown as OrchestrationV2ThreadProjection;+ // A finished run whose binding to the follow-up was lost (#19002).+ const childProjection = {+ thread: { id: childThreadId },+ runs:+ childState === "no runs"+ ? []+ : [{ id: RunId.make("run:mcp-orphan-child"), ordinal: 1, status: "completed" }],+ contextTransfers: [],+ messages: [],+ subagents: [],+ providerThreads: [],+ runtimeRequests: [],+ turnItems: [],+ } as unknown as OrchestrationV2ThreadProjection;+ const layerDependencies = Layer.mergeAll(+ NodeServices.layer,+ Layer.mock(ThreadManagementService.ThreadManagementService)({+ getThreadRecords: (threadId) =>+ threadId === parentThreadId+ ? Effect.map(Ref.get(status), parentProjection)+ : Effect.succeed(childProjection),+ getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)),+ delegatedTaskResultPending: () => Effect.succeed(false),+ // The orchestrator's subagent.stop repair is covered in ThreadStop.test.ts.+ dispatch: (command) =>+ Ref.update(dispatched, (commands) => [...commands, command]).pipe(+ Effect.andThen(+ command.type === "subagent.stop" ? Ref.set(status, "cancelled") : Effect.void,+ ),+ Effect.as({} as never),+ ),+ }),+ ServerSettings.layerTest(),+ Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),+ Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({+ list: () => Effect.succeed([]),+ }),+ Layer.mock(ProjectService.ProjectService)({}),+ Layer.mock(SecretRequests.SecretRequests)({}),+ Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),+ );+ const scope: McpInvocationScope = {+ environmentId: EnvironmentId.make("environment:mcp-orphan"),+ requestNamespace: "provider-session:mcp-orphan",+ thread: {+ threadId: parentThreadId,+ providerSessionId: "provider-session:mcp-orphan",+ providerInstanceId: ProviderInstanceId.make("codex"),+ },+ client: undefined,+ capabilities: new Set(["orchestration"]),+ issuedAt: 1,+ };++ yield* Effect.gen(function* () {+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;+ const result = yield* service.cancelTask(scope, {+ taskId,+ 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");+ if (stop?.type !== "subagent.stop") return;+ assert.deepEqual(+ { threadId: stop.threadId, runId: stop.runId, subagentId: stop.subagentId },+ { threadId: parentThreadId, runId: parentRunId, subagentId: taskId },+ );+ }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies))));+ }),+ );+it.effect("does not dispose delivery when the child stop fails", () =>Effect.gen(function* () {const parentThreadId = ThreadId.make("thread:mcp-cancel-failed-parent");diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.tsindex 186a8c895ed..7d88e4d5f75 100644--- a/apps/server/src/mcp/OrchestratorMcpService.ts+++ b/apps/server/src/mcp/OrchestratorMcpService.ts@@ -60,6 +60,7 @@ import {type ScheduledTaskUpsertInput,type ServerProvider,ThreadId,+ isOrchestrationV2WorkActive,} from "@t3tools/contracts";import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";import {@@ -2357,7 +2358,32 @@ 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.+ const cancelOrphan = Effect.gen(function* () {+ if (parentTask?.runId == null || !isOrchestrationV2WorkActive(parentTask.status))+ return false;+ yield* threadManagement+ .dispatch({+ type: "subagent.stop",+ commandId: stableCommandId({+ scope,+ requestKey: key,+ operation: "cancel-task-orphan",+ }),+ threadId: scope.thread.threadId,+ runId: parentTask.runId,+ subagentId: parentTask.id,+ })+ .pipe(Effect.mapError(threadManagementFailure));+ const { subagents } = yield* threadManagement+ .getThreadRecords(scope.thread.threadId, ["subagents"])+ .pipe(Effect.mapError(threadManagementFailure));+ return subagents.some((task) => task.id === input.taskId && task.status === "cancelled");+ });if (isTerminalTaskStatus(current.status)) {+ if (yield* cancelOrphan) return { taskId: input.taskId, status: "cancelled" };yield* stopWithinLimit;yield* disposeCompletionDelivery;return {@@ -2375,6 +2401,7 @@ const make = Effect.gen(function* () {(run.delegatedTaskId === input.taskId || run.id === current.childRunId),)) {+ if (yield* cancelOrphan) return { taskId: input.taskId, status: "cancelled" };return yield* failure("task_not_cancellable",`Delegated task ${input.taskId} has no interruptible child run.`,diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.tsindex 78b6557d17c..7094be95897 100644--- a/apps/server/src/orchestration-v2/Orchestrator.ts+++ b/apps/server/src/orchestration-v2/Orchestrator.ts@@ -190,6 +190,8 @@ export class OrchestratorProjectionError extends Schema.TaggedError<Orchestrator}}+const isOrchestratorProjectionError = Schema.is(OrchestratorProjectionError);+export class OrchestratorDomainEventStreamError extends Schema.TaggedError<OrchestratorDomainEventStreamError>()("OrchestratorDomainEventStreamError",{@@ -9395,6 +9397,24 @@ 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).+ if (+ subagent?.origin === "app_owned" &&+ subagent.childThreadId !== null &&+ subagent.runId === command.runId+ ) {+ const records = yield* loadProjectionForCommand(command, ["subagents", "turnItems"], {+ turnItemTypes: ["subagent"],+ turnItemStatuses: ["pending", "running", "waiting"],+ });+ return yield* cancelIdleOrphans({+ command,+ events,+ projection: records,+ childThreadId: subagent.childThreadId,+ });+ }if (subagent === undefined ||subagent.runId !== command.runId ||@@ -9837,23 +9857,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioreturn undefined;});- const dispatchThreadStop = Effect.fn("Orchestrator.dispatchThreadStop")(function* (- command: Extract<OrchestrationV2ServerCommand, { readonly type: "thread.stop" }>,- events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,- effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,- ) {- const projection = yield* projectionStore- .getThreadRecords(command.threadId, ["runs", "providerThreads", "turnItems", "subagents"], {- turnItemTypes: ["command_execution", "dynamic_tool", "subagent"],- turnItemStatuses: ["pending", "running", "waiting"],- })- .pipe(- Effect.mapError(- (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),- ),- );- if (projection.thread.deletedAt !== null) return undefined;- const cancelIdleOrphans = Effect.gen(function* () {+ const cancelIdleOrphans = Effect.fn("Orchestrator.cancelIdleOrphans")(+ function* (input: {+ readonly command: Extract<+ OrchestrationV2ServerCommand,+ { readonly type: "run.interrupt" | "thread.stop" | "subagent.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);const children = new Map<ThreadId,@@ -9869,7 +9884,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioif (task.origin !== "app_owned" ||task.childThreadId === null ||- !isOrchestrationV2WorkActive(task.status)+ !isOrchestrationV2WorkActive(task.status) ||+ (input.childThreadId !== undefined && task.childThreadId !== input.childThreadId))continue;const childThreadId = task.childThreadId;@@ -9951,13 +9967,33 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio});}}- }).pipe(- Effect.mapError((cause) =>- Schema.is(OrchestratorProjectionError)(cause)- ? cause- : new OrchestratorProjectionError({ threadId: command.threadId, cause }),+ },+ (effect, input) =>+ effect.pipe(+ Effect.mapError((cause) =>+ isOrchestratorProjectionError(cause)+ ? cause+ : new OrchestratorProjectionError({ threadId: input.command.threadId, cause }),+ ),),- );+ );++ const dispatchThreadStop = Effect.fn("Orchestrator.dispatchThreadStop")(function* (+ command: Extract<OrchestrationV2ServerCommand, { readonly type: "thread.stop" }>,+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,+ effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,+ ) {+ const projection = yield* projectionStore+ .getThreadRecords(command.threadId, ["runs", "providerThreads", "turnItems", "subagents"], {+ turnItemTypes: ["command_execution", "dynamic_tool", "subagent"],+ turnItemStatuses: ["pending", "running", "waiting"],+ })+ .pipe(+ Effect.mapError(+ (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),+ ),+ );+ if (projection.thread.deletedAt !== null) return undefined;const latestRun = projection.runs.findLast((run) => run.status !== "queued");const target =projection.runs.findLast(@@ -9996,7 +10032,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioconst enqueued = yield* Ref.get(interruptEffects);yield* Ref.update(events, (existing) => [...existing, ...written]);yield* Ref.update(effects, (existing) => [...existing, ...enqueued]);- yield* cancelIdleOrphans;+ yield* cancelIdleOrphans({ command, events, projection });return interrupted.value;}yield* Effect.logWarning("thread.stop could not interrupt the running turn", {@@ -10016,7 +10052,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functioyield* markStoppedRun({ command, events, thread: projection.thread, run, now });}yield* holdStoppedThread({ command, events, projection, cohortRunIds: [], now });- yield* cancelIdleOrphans;+ yield* cancelIdleOrphans({ command, events, projection });return undefined;});@@ -11296,6 +11332,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functiocase "run.interrupt":cancelUnsettledEffects = yield* dispatchRunInterrupt(command, events, effects);if (command.holdQueue === true) {+ // Stop must still commit when a child can't be read, so a failed repair's+ // partial events are dropped.+ const repairEvents = yield* Ref.make(yield* Ref.get(events));+ const repaired = yield* Effect.exit(+ loadProjectionForCommand(command, ["subagents", "turnItems"], {+ turnItemTypes: ["subagent"],+ turnItemStatuses: ["pending", "running", "waiting"],+ }).pipe(+ Effect.flatMap((projection) =>+ cancelIdleOrphans({ command, events: repairEvents, projection }),+ ),+ ),+ );+ if (Exit.isSuccess(repaired)) yield* Ref.set(events, yield* Ref.get(repairEvents));+ else+ yield* Effect.logWarning("Stop could not cancel orphaned delegated follow-ups", {+ threadId: command.threadId,+ cause: repaired.cause,+ });yield* Ref.update(effects, (existing) => [...existing,{diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.tsindex 92837a6ceef..74da4d674d7 100644--- a/apps/server/src/orchestration-v2/ThreadStop.test.ts+++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts@@ -161,21 +161,24 @@ const threadState = (threadId: ThreadId) =>});it.effect.each([- "idle",- "archived",- "missing",- "running",- "queued",- "waiting",- "correlated",- "provider-active",- "roster",- "background",- "question",- "restart",+ ["idle", "thread.stop"],+ ["idle", "run.interrupt"],+ ["idle", "subagent.stop"],+ ["running", "subagent.stop"],+ ["archived", "thread.stop"],+ ["missing", "thread.stop"],+ ["running", "thread.stop"],+ ["queued", "thread.stop"],+ ["waiting", "thread.stop"],+ ["correlated", "thread.stop"],+ ["provider-active", "thread.stop"],+ ["roster", "thread.stop"],+ ["background", "thread.stop"],+ ["question", "thread.stop"],+ ["restart", "thread.stop"],] as const)(- "Stop clears an orphaned follow-up only when its child is finished (%s)",- (childState) =>+ "Stop clears an orphaned follow-up only when its child is finished (%s via %s)",+ ([childState, type]) =>Effect.gen(function* () {const orchestrator = yield* Orchestrator.OrchestratorV2;const projections = yield* ProjectionStore.ProjectionStoreV2;@@ -367,6 +370,41 @@ it.effect.each([occurredAt: now,payload: { ...parent.runs[0]!, status: "completed", completedAt: now },});+ if (type === "run.interrupt") {+ const run = parent.runs[0]!;+ yield* apply({+ type: "provider-turn.updated",+ threadId: parentThreadId,+ occurredAt: now,+ payload: {+ id: ProviderTurnId.make("provider-turn:orphan-parent"),+ providerThreadId: run.providerThreadId!,+ nodeId: run.rootNodeId!,+ runAttemptId: run.activeAttemptId!,+ nativeTurnRef: null,+ ordinal: 1,+ status: "completed",+ startedAt: now,+ completedAt: now,+ },+ });+ yield* apply({+ type: "run-attempt.updated",+ threadId: parentThreadId,+ occurredAt: now,+ payload: { ...parent.attempts[0]!, status: "completed", completedAt: now },+ });+ yield* apply({+ type: "node.updated",+ threadId: parentThreadId,+ occurredAt: now,+ payload: {+ ...parent.nodes.find((node) => node.id === run.rootNodeId)!,+ status: "completed",+ completedAt: now,+ },+ });+ }if (childState === "archived") {yield* apply({type: "thread.archived",@@ -382,20 +420,30 @@ it.effect.each([),1,);- yield* orchestrator.dispatch({- type: "thread.stop",+ const stop = {commandId: CommandId.make(`stop-orphan:${childState}`),threadId: parentThreadId,- });+ };+ yield* orchestrator.dispatch(+ type === "run.interrupt"+ ? { ...stop, type, runId: parent.runs.at(-1)!.id, holdQueue: true }+ : type === "subagent.stop"+ ? { ...stop, type, runId: original.runId!, subagentId: taskId }+ : { ...stop, type },+ );const after = yield* orchestrator.getThreadProjection(parentThreadId);- assert.isEmpty((after.thread.pullRequests ?? []).filter((link) => link.watch !== undefined));+ // The Lineage stop of one subagent leaves the parent's watches alone.+ assert.lengthOf(+ (after.thread.pullRequests ?? []).filter((link) => link.watch !== undefined),+ type === "subagent.stop" ? 1 : 0,+ );const expected = 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);assert.equal(after.subagents.find((task) => task.id === taskId)?.completionDelivery?.state,- "disposed",+ type === "subagent.stop" && expected === "running" ? undefined : "disposed",);assert.equal(after.subagents.find((task) => task.id === original.id)?.result,@@ -404,7 +452,9 @@ it.effect.each([assert.deepEqual(yield* orchestrator.getThreadProjection(childThreadId), childBeforeStop);if (expected === "cancelled") {assert.lengthOf(- (yield* orchestrator.getThreadShell(parentThreadId))?.pendingBackgroundTasks ?? [],+ (+ (yield* orchestrator.getThreadShell(parentThreadId))?.pendingBackgroundTasks ?? []+ ).filter((task) => task.kind === "subagent"),0,);yield* orchestrator.recoverDelegatedTasks;@@ -421,6 +471,30 @@ it.effect.each([}).pipe(Effect.provide(layerTest)),);+it.effect("Stop still stops the thread when a delegated child cannot be read", () =>+ Effect.gen(function* () {+ const orchestrator = yield* Orchestrator.OrchestratorV2;+ const sql = yield* SqlClient.SqlClient;+ const parentThreadId = ThreadId.make("thread:unreadable-child-parent");+ yield* createWatchingThread(parentThreadId, 1);+ yield* send(parentThreadId, "parent", "start_immediately");+ const childThreadId = yield* delegate(parentThreadId, "unreadable child");+ yield* sql`+ UPDATE orchestration_v2_projection_runs+ SET payload_json = '{"obsolete":true}'+ WHERE thread_id = ${childThreadId}+ `;+ yield* orchestrator.dispatch({+ type: "run.interrupt",+ commandId: CommandId.make("stop:unreadable-child"),+ threadId: parentThreadId,+ runId: (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!.id,+ holdQueue: true,+ });+ assert.deepEqual(yield* threadState(parentThreadId), { runs: ["interrupted"], watched: [] });+ }).pipe(Effect.provide(layerTest)),+);+it.effect("Stop ends watches, holds queues, and stops the delegated tasks under the thread", () =>Effect.gen(function* () {const orchestrator = yield* Orchestrator.OrchestratorV2;diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsxindex 499d014417d..5262b559169 100644--- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx+++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx@@ -366,16 +366,13 @@ export function ThreadRelationshipsPanel(props: {const stopSubagent = async (childThreadId: ThreadId,- agent: Pick<OrchestrationV2Subagent, "id" | "origin" | "threadId">,+ agent: Pick<OrchestrationV2Subagent, "id" | "threadId">,) => {if (stoppingId !== null) return;setStoppingId(childThreadId);const result = await interruptTurn({environmentId: props.environmentId,- input:- agent.origin === "provider_native"- ? { threadId: agent.threadId, subagentId: agent.id }- : { threadId: childThreadId },+ input: { threadId: agent.threadId, subagentId: agent.id },});setStoppingId(null);if (result._tag === "Failure") {diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.tsindex d4e2db6ae3f..41fbb2b7699 100644--- a/packages/client-runtime/src/operations/commands.test.ts+++ b/packages/client-runtime/src/operations/commands.test.ts@@ -588,6 +588,65 @@ describe("V2 environment commands", () => {}).pipe(Effect.provide(layerTestCrypto)),);+ it.effect(+ "an app-owned subagent stop asks the parent to clear an orphan, then stops the child",+ () =>+ Effect.gen(function* () {+ const subagentId = NodeId.make("app-owned-subagent");+ const runId = RunId.make("parent-run");+ const childThreadId = ThreadId.make("app-owned-child-thread");+ const commands: OrchestrationV2Command[] = [];+ const supervisor = yield* makeSupervisor({+ commands,+ projects: [],+ advertiseThreadStop: true,+ projection: {+ ...v2Projection,+ subagents: [+ {+ id: subagentId,+ threadId: v2ThreadId,+ runId,+ parentNodeId: NodeId.make("owner-node"),+ origin: "app_owned",+ createdBy: "agent",+ driver: ProviderDriverKind.make("codex"),+ providerInstanceId: ProviderInstanceId.make("codex"),+ providerThreadId: null,+ childThreadId,+ nativeTaskRef: null,+ prompt: "Work",+ title: null,+ model: null,+ result: null,+ status: "running",+ startedAt: v2Now,+ completedAt: null,+ updatedAt: v2Now,+ },+ ],+ },+ });+ yield* interruptThreadTurn({+ commandId: CommandId.make("lineage-stop"),+ threadId: v2ThreadId,+ subagentId,+ // A parent run must not be interrupted on the child thread.+ runId,+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));+ expect(commands).toEqual([+ {+ type: "subagent.stop",+ commandId: expect.any(String),+ threadId: v2ThreadId,+ runId,+ subagentId,+ },+ { type: "thread.stop", commandId: "lineage-stop", threadId: childThreadId },+ ]);+ }).pipe(Effect.provide(layerTestCrypto)),+ );+it.effect("stops a thread without relying on background work in the history window", () =>Effect.gen(function* () {const commands: OrchestrationV2Command[] = [];diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.tsindex e839231e389..edb9d70ef6f 100644--- a/packages/client-runtime/src/operations/commands.ts+++ b/packages/client-runtime/src/operations/commands.ts@@ -769,19 +769,37 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreadTurn")(function* (input: InterruptThreadTurnInput,) {+ let threadId = input.threadId;if (input.subagentId !== undefined) {const projection = yield* getProjection(input.threadId);const subagent = projection.subagents.find((agent) => agent.id === input.subagentId);- if (subagent?.runId == null) return { sequence: 0 };- return yield* dispatch({- type: "subagent.stop",- commandId: yield* allocateCommandId(input),- threadId: input.threadId,- runId: subagent.runId,- subagentId: subagent.id,- });+ if (subagent?.origin === "app_owned" && subagent.childThreadId !== null) {+ // The parent cancels the task if it is an orphan with an idle child (#19002). Older+ // servers reject this for app-owned tasks, so the child stop below still runs.+ if (subagent.runId !== null) {+ yield* dispatch({+ type: "subagent.stop",+ commandId: yield* allocateCommandId({}),+ threadId: input.threadId,+ runId: subagent.runId,+ subagentId: subagent.id,+ }).pipe(Effect.ignore);+ }+ threadId = subagent.childThreadId;+ } else {+ if (subagent?.runId == null) return { sequence: 0 };+ return yield* dispatch({+ type: "subagent.stop",+ commandId: yield* allocateCommandId(input),+ threadId: input.threadId,+ runId: subagent.runId,+ subagentId: subagent.id,+ });+ }}- let runId = input.runId ?? (input.turnId as RunId | undefined);+ // A run named by the caller belongs to the parent, not the rerouted child.+ let runId =+ threadId === input.threadId ? (input.runId ?? (input.turnId as RunId | undefined)) : undefined;if (runId === undefined) {const config = yield* getInitialServerConfig();if (config.environment.capabilities.threadStop === true) {@@ -789,12 +807,12 @@ export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreareturn yield* dispatch({type: "thread.stop",commandId: yield* allocateCommandId(input),- threadId: input.threadId,+ threadId,});}}if (runId === undefined) {- const projection = yield* getProjection(input.threadId);+ const projection = yield* getProjection(threadId);runId = projection.runs.findLast((run) =>run.status === "preparing" ||@@ -823,7 +841,7 @@ export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThrearesult = yield* dispatch({type: "thread.pull-request.watch",commandId: yield* allocateCommandId(result.sequence === 0 ? input : {}),- threadId: input.threadId,+ threadId,host: link.host,repository: link.repository,number: link.number,@@ -837,7 +855,7 @@ export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreareturn yield* dispatch({type: "run.interrupt",commandId: yield* allocateCommandId(input),- threadId: input.threadId,+ threadId,runId,holdQueue: true,});