@devries-cameron20 / t3code Mirror · read-only / commits / 849b3f8948
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 20:45 UTC

fix(server): idle orphaned follow-ups can be cancelled without a running parent (#22581)

Co-authored-by: syberia <n.kuhtin@gmail.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 20, 2026 at 18:26 UTC 849b3f894803a4f04672fa7e9881aa140106d261
7 files changed +398 -64
apps/server/src/mcp/OrchestratorMcpService.test.ts
+104
@@ -14,6 +14,7 @@ import {
14 ProviderInstanceId,
15 RunId,
16 ThreadId,
17 + type OrchestrationV2ServerCommand,
18 type OrchestrationV2ThreadProjection,
19 type ServerProvider,
20 } from "@t3tools/contracts";
@@ -366,6 +367,109 @@ describe("OrchestratorMcpService", () => {
367 }),
368 );
369
370 + it.effect.each(["no runs", "a finished run"] as const)(
371 + "cancels an orphaned follow-up through its parent when the child has %s",
372 + (childState) =>
373 + Effect.gen(function* () {
374 + const parentThreadId = ThreadId.make("thread:mcp-orphan-parent");
375 + const childThreadId = ThreadId.make("thread:mcp-orphan-child");
376 + const taskId = NodeId.make("node:mcp-orphan-task");
377 + const parentRunId = RunId.make("run:mcp-orphan-parent");
378 + const dispatched = yield* Ref.make<ReadonlyArray<OrchestrationV2ServerCommand>>([]);
379 + const status = yield* Ref.make("running");
380 + const parentProjection = (taskStatus: string) =>
381 + ({
382 + thread: { id: parentThreadId },
383 + runs: [],
384 + contextTransfers: [],
385 + subagents: [
386 + {
387 + id: taskId,
388 + threadId: parentThreadId,
389 + runId: parentRunId,
390 + origin: "app_owned",
391 + childThreadId,
392 + driver: "codex",
393 + model: "gpt-5.6-terra",
394 + status: taskStatus,
395 + result: null,
396 + completionDelivery: { state: "pending" },
397 + },
398 + ],
399 + }) as unknown as OrchestrationV2ThreadProjection;
400 + // A finished run whose binding to the follow-up was lost (#19002).
401 + const childProjection = {
402 + thread: { id: childThreadId },
403 + runs:
404 + childState === "no runs"
405 + ? []
406 + : [{ id: RunId.make("run:mcp-orphan-child"), ordinal: 1, status: "completed" }],
407 + contextTransfers: [],
408 + messages: [],
409 + subagents: [],
410 + providerThreads: [],
411 + runtimeRequests: [],
412 + turnItems: [],
413 + } as unknown as OrchestrationV2ThreadProjection;
414 + const layerDependencies = Layer.mergeAll(
415 + NodeServices.layer,
416 + Layer.mock(ThreadManagementService.ThreadManagementService)({
417 + getThreadRecords: (threadId) =>
418 + threadId === parentThreadId
419 + ? Effect.map(Ref.get(status), parentProjection)
420 + : Effect.succeed(childProjection),
421 + getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)),
422 + delegatedTaskResultPending: () => Effect.succeed(false),
423 + // The orchestrator's subagent.stop repair is covered in ThreadStop.test.ts.
424 + dispatch: (command) =>
425 + Ref.update(dispatched, (commands) => [...commands, command]).pipe(
426 + Effect.andThen(
427 + command.type === "subagent.stop" ? Ref.set(status, "cancelled") : Effect.void,
428 + ),
429 + Effect.as({} as never),
430 + ),
431 + }),
432 + ServerSettings.layerTest(),
433 + Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
434 + Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({
435 + list: () => Effect.succeed([]),
436 + }),
437 + Layer.mock(ProjectService.ProjectService)({}),
438 + Layer.mock(SecretRequests.SecretRequests)({}),
439 + Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
440 + );
441 + const scope: McpInvocationScope = {
442 + environmentId: EnvironmentId.make("environment:mcp-orphan"),
443 + requestNamespace: "provider-session:mcp-orphan",
444 + thread: {
445 + threadId: parentThreadId,
446 + providerSessionId: "provider-session:mcp-orphan",
447 + providerInstanceId: ProviderInstanceId.make("codex"),
448 + },
449 + client: undefined,
450 + capabilities: new Set(["orchestration"]),
451 + issuedAt: 1,
452 + };
453 +
454 + yield* Effect.gen(function* () {
455 + const service = yield* OrchestratorMcpService.OrchestratorMcpService;
456 + const result = yield* service.cancelTask(scope, {
457 + taskId,
458 + clientRequestId: "cancel-orphan-task",
459 + });
460 + assert.deepEqual(result, { taskId, status: "cancelled" });
461 + const [stop, ...rest] = yield* Ref.get(dispatched);
462 + assert.isEmpty(rest);
463 + assert.equal(stop?.type, "subagent.stop");
464 + if (stop?.type !== "subagent.stop") return;
465 + assert.deepEqual(
466 + { threadId: stop.threadId, runId: stop.runId, subagentId: stop.subagentId },
467 + { threadId: parentThreadId, runId: parentRunId, subagentId: taskId },
468 + );
469 + }).pipe(Effect.provide(layerOrchestratorService.pipe(Layer.provide(layerDependencies))));
470 + }),
471 + );
472 +
473 it.effect("does not dispose delivery when the child stop fails", () =>
474 Effect.gen(function* () {
475 const parentThreadId = ThreadId.make("thread:mcp-cancel-failed-parent");
apps/server/src/mcp/OrchestratorMcpService.ts
+27
@@ -60,6 +60,7 @@ import {
60 type ScheduledTaskUpsertInput,
61 type ServerProvider,
62 ThreadId,
63 + isOrchestrationV2WorkActive,
64 } from "@t3tools/contracts";
65 import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
66 import {
@@ -2357,7 +2358,32 @@ const make = Effect.gen(function* () {
2358 ),
2359 ),
2360 );
2361 + // A follow-up that lost its child run (#19002) stays running on the parent, while its
2362 + // status here comes from the child's last run. The parent cancels it, and any other
2363 + // orphan of the same child, when that child is idle.
2364 + const cancelOrphan = Effect.gen(function* () {
2365 + if (parentTask?.runId == null || !isOrchestrationV2WorkActive(parentTask.status))
2366 + return false;
2367 + yield* threadManagement
2368 + .dispatch({
2369 + type: "subagent.stop",
2370 + commandId: stableCommandId({
2371 + scope,
2372 + requestKey: key,
2373 + operation: "cancel-task-orphan",
2374 + }),
2375 + threadId: scope.thread.threadId,
2376 + runId: parentTask.runId,
2377 + subagentId: parentTask.id,
2378 + })
2379 + .pipe(Effect.mapError(threadManagementFailure));
2380 + const { subagents } = yield* threadManagement
2381 + .getThreadRecords(scope.thread.threadId, ["subagents"])
2382 + .pipe(Effect.mapError(threadManagementFailure));
2383 + return subagents.some((task) => task.id === input.taskId && task.status === "cancelled");
2384 + });
2385 if (isTerminalTaskStatus(current.status)) {
2386 + if (yield* cancelOrphan) return { taskId: input.taskId, status: "cancelled" };
2387 yield* stopWithinLimit;
2388 yield* disposeCompletionDelivery;
2389 return {
@@ -2375,6 +2401,7 @@ const make = Effect.gen(function* () {
2401 (run.delegatedTaskId === input.taskId || run.id === current.childRunId),
2402 )
2403 ) {
2404 + if (yield* cancelOrphan) return { taskId: input.taskId, status: "cancelled" };
2405 return yield* failure(
2406 "task_not_cancellable",
2407 `Delegated task ${input.taskId} has no interruptible child run.`,
apps/server/src/orchestration-v2/Orchestrator.ts
+81 -26
@@ -190,6 +190,8 @@ export class OrchestratorProjectionError extends Schema.TaggedError<Orchestrator
190 }
191 }
192
193 +const isOrchestratorProjectionError = Schema.is(OrchestratorProjectionError);
194 +
195 export class OrchestratorDomainEventStreamError extends Schema.TaggedError<OrchestratorDomainEventStreamError>()(
196 "OrchestratorDomainEventStreamError",
197 {
@@ -9395,6 +9397,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
9397 ]);
9398 const run = projection.runs.find((candidate) => candidate.id === command.runId);
9399 const subagent = projection.subagents.find((candidate) => candidate.id === command.subagentId);
9400 + // An app-owned task stops through its child thread. Here the parent only cancels the child's
9401 + // orphaned tasks: the child is idle and no child run is bound to them (#19002).
9402 + if (
9403 + subagent?.origin === "app_owned" &&
9404 + subagent.childThreadId !== null &&
9405 + subagent.runId === command.runId
9406 + ) {
9407 + const records = yield* loadProjectionForCommand(command, ["subagents", "turnItems"], {
9408 + turnItemTypes: ["subagent"],
9409 + turnItemStatuses: ["pending", "running", "waiting"],
9410 + });
9411 + return yield* cancelIdleOrphans({
9412 + command,
9413 + events,
9414 + projection: records,
9415 + childThreadId: subagent.childThreadId,
9416 + });
9417 + }
9418 if (
9419 subagent === undefined ||
9420 subagent.runId !== command.runId ||
@@ -9837,23 +9857,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
9857 return undefined;
9858 });
9859
9840 - const dispatchThreadStop = Effect.fn("Orchestrator.dispatchThreadStop")(function* (
9841 - command: Extract<OrchestrationV2ServerCommand, { readonly type: "thread.stop" }>,
9842 - events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
9843 - effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
9844 - ) {
9845 - const projection = yield* projectionStore
9846 - .getThreadRecords(command.threadId, ["runs", "providerThreads", "turnItems", "subagents"], {
9847 - turnItemTypes: ["command_execution", "dynamic_tool", "subagent"],
9848 - turnItemStatuses: ["pending", "running", "waiting"],
9849 - })
9850 - .pipe(
9851 - Effect.mapError(
9852 - (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
9853 - ),
9854 - );
9855 - if (projection.thread.deletedAt !== null) return undefined;
9856 - const cancelIdleOrphans = Effect.gen(function* () {
9860 + const cancelIdleOrphans = Effect.fn("Orchestrator.cancelIdleOrphans")(
9861 + function* (input: {
9862 + readonly command: Extract<
9863 + OrchestrationV2ServerCommand,
9864 + { readonly type: "run.interrupt" | "thread.stop" | "subagent.stop" }
9865 + >;
9866 + readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;
9867 + readonly projection: Pick<OrchestrationV2ThreadProjection, "subagents" | "turnItems">;
9868 + /** Limits the repair to tasks delegated to this child thread. */
9869 + readonly childThreadId?: ThreadId;
9870 + }) {
9871 + const { command, events, projection } = input;
9872 const pending = yield* Ref.get(events);
9873 const children = new Map<
9874 ThreadId,
@@ -9869,7 +9884,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
9884 if (
9885 task.origin !== "app_owned" ||
9886 task.childThreadId === null ||
9872 - !isOrchestrationV2WorkActive(task.status)
9887 + !isOrchestrationV2WorkActive(task.status) ||
9888 + (input.childThreadId !== undefined && task.childThreadId !== input.childThreadId)
9889 )
9890 continue;
9891 const childThreadId = task.childThreadId;
@@ -9951,13 +9967,33 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
9967 });
9968 }
9969 }
9954 - }).pipe(
9955 - Effect.mapError((cause) =>
9956 - Schema.is(OrchestratorProjectionError)(cause)
9957 - ? cause
9958 - : new OrchestratorProjectionError({ threadId: command.threadId, cause }),
9970 + },
9971 + (effect, input) =>
9972 + effect.pipe(
9973 + Effect.mapError((cause) =>
9974 + isOrchestratorProjectionError(cause)
9975 + ? cause
9976 + : new OrchestratorProjectionError({ threadId: input.command.threadId, cause }),
9977 + ),
9978 ),
9960 - );
9979 + );
9980 +
9981 + const dispatchThreadStop = Effect.fn("Orchestrator.dispatchThreadStop")(function* (
9982 + command: Extract<OrchestrationV2ServerCommand, { readonly type: "thread.stop" }>,
9983 + events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
9984 + effects: Ref.Ref<Array<PendingOrchestrationEffectV2>>,
9985 + ) {
9986 + const projection = yield* projectionStore
9987 + .getThreadRecords(command.threadId, ["runs", "providerThreads", "turnItems", "subagents"], {
9988 + turnItemTypes: ["command_execution", "dynamic_tool", "subagent"],
9989 + turnItemStatuses: ["pending", "running", "waiting"],
9990 + })
9991 + .pipe(
9992 + Effect.mapError(
9993 + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
9994 + ),
9995 + );
9996 + if (projection.thread.deletedAt !== null) return undefined;
9997 const latestRun = projection.runs.findLast((run) => run.status !== "queued");
9998 const target =
9999 projection.runs.findLast(
@@ -9996,7 +10032,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10032 const enqueued = yield* Ref.get(interruptEffects);
10033 yield* Ref.update(events, (existing) => [...existing, ...written]);
10034 yield* Ref.update(effects, (existing) => [...existing, ...enqueued]);
9999 - yield* cancelIdleOrphans;
10035 + yield* cancelIdleOrphans({ command, events, projection });
10036 return interrupted.value;
10037 }
10038 yield* Effect.logWarning("thread.stop could not interrupt the running turn", {
@@ -10016,7 +10052,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10052 yield* markStoppedRun({ command, events, thread: projection.thread, run, now });
10053 }
10054 yield* holdStoppedThread({ command, events, projection, cohortRunIds: [], now });
10019 - yield* cancelIdleOrphans;
10055 + yield* cancelIdleOrphans({ command, events, projection });
10056 return undefined;
10057 });
10058
@@ -11296,6 +11332,25 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11332 case "run.interrupt":
11333 cancelUnsettledEffects = yield* dispatchRunInterrupt(command, events, effects);
11334 if (command.holdQueue === true) {
11335 + // Stop must still commit when a child can't be read, so a failed repair's
11336 + // partial events are dropped.
11337 + const repairEvents = yield* Ref.make(yield* Ref.get(events));
11338 + const repaired = yield* Effect.exit(
11339 + loadProjectionForCommand(command, ["subagents", "turnItems"], {
11340 + turnItemTypes: ["subagent"],
11341 + turnItemStatuses: ["pending", "running", "waiting"],
11342 + }).pipe(
11343 + Effect.flatMap((projection) =>
11344 + cancelIdleOrphans({ command, events: repairEvents, projection }),
11345 + ),
11346 + ),
11347 + );
11348 + if (Exit.isSuccess(repaired)) yield* Ref.set(events, yield* Ref.get(repairEvents));
11349 + else
11350 + yield* Effect.logWarning("Stop could not cancel orphaned delegated follow-ups", {
11351 + threadId: command.threadId,
11352 + cause: repaired.cause,
11353 + });
11354 yield* Ref.update(effects, (existing) => [
11355 ...existing,
11356 {
apps/server/src/orchestration-v2/ThreadStop.test.ts
+94 -20
@@ -161,21 +161,24 @@ const threadState = (threadId: ThreadId) =>
161 });
162
163 it.effect.each([
164 - "idle",
165 - "archived",
166 - "missing",
167 - "running",
168 - "queued",
169 - "waiting",
170 - "correlated",
171 - "provider-active",
172 - "roster",
173 - "background",
174 - "question",
175 - "restart",
164 + ["idle", "thread.stop"],
165 + ["idle", "run.interrupt"],
166 + ["idle", "subagent.stop"],
167 + ["running", "subagent.stop"],
168 + ["archived", "thread.stop"],
169 + ["missing", "thread.stop"],
170 + ["running", "thread.stop"],
171 + ["queued", "thread.stop"],
172 + ["waiting", "thread.stop"],
173 + ["correlated", "thread.stop"],
174 + ["provider-active", "thread.stop"],
175 + ["roster", "thread.stop"],
176 + ["background", "thread.stop"],
177 + ["question", "thread.stop"],
178 + ["restart", "thread.stop"],
179 ] as const)(
177 - "Stop clears an orphaned follow-up only when its child is finished (%s)",
178 - (childState) =>
180 + "Stop clears an orphaned follow-up only when its child is finished (%s via %s)",
181 + ([childState, type]) =>
182 Effect.gen(function* () {
183 const orchestrator = yield* Orchestrator.OrchestratorV2;
184 const projections = yield* ProjectionStore.ProjectionStoreV2;
@@ -367,6 +370,41 @@ it.effect.each([
370 occurredAt: now,
371 payload: { ...parent.runs[0]!, status: "completed", completedAt: now },
372 });
373 + if (type === "run.interrupt") {
374 + const run = parent.runs[0]!;
375 + yield* apply({
376 + type: "provider-turn.updated",
377 + threadId: parentThreadId,
378 + occurredAt: now,
379 + payload: {
380 + id: ProviderTurnId.make("provider-turn:orphan-parent"),
381 + providerThreadId: run.providerThreadId!,
382 + nodeId: run.rootNodeId!,
383 + runAttemptId: run.activeAttemptId!,
384 + nativeTurnRef: null,
385 + ordinal: 1,
386 + status: "completed",
387 + startedAt: now,
388 + completedAt: now,
389 + },
390 + });
391 + yield* apply({
392 + type: "run-attempt.updated",
393 + threadId: parentThreadId,
394 + occurredAt: now,
395 + payload: { ...parent.attempts[0]!, status: "completed", completedAt: now },
396 + });
397 + yield* apply({
398 + type: "node.updated",
399 + threadId: parentThreadId,
400 + occurredAt: now,
401 + payload: {
402 + ...parent.nodes.find((node) => node.id === run.rootNodeId)!,
403 + status: "completed",
404 + completedAt: now,
405 + },
406 + });
407 + }
408 if (childState === "archived") {
409 yield* apply({
410 type: "thread.archived",
@@ -382,20 +420,30 @@ it.effect.each([
420 ),
421 1,
422 );
385 - yield* orchestrator.dispatch({
386 - type: "thread.stop",
423 + const stop = {
424 commandId: CommandId.make(`stop-orphan:${childState}`),
425 threadId: parentThreadId,
389 - });
426 + };
427 + yield* orchestrator.dispatch(
428 + type === "run.interrupt"
429 + ? { ...stop, type, runId: parent.runs.at(-1)!.id, holdQueue: true }
430 + : type === "subagent.stop"
431 + ? { ...stop, type, runId: original.runId!, subagentId: taskId }
432 + : { ...stop, type },
433 + );
434 const after = yield* orchestrator.getThreadProjection(parentThreadId);
391 - assert.isEmpty((after.thread.pullRequests ?? []).filter((link) => link.watch !== undefined));
435 + // The Lineage stop of one subagent leaves the parent's watches alone.
436 + assert.lengthOf(
437 + (after.thread.pullRequests ?? []).filter((link) => link.watch !== undefined),
438 + type === "subagent.stop" ? 1 : 0,
439 + );
440 const expected = childState === "idle" || childState === "archived" ? "cancelled" : "running";
441 assert.equal(after.subagents.find((task) => task.id === taskId)?.status, expected);
442 assert.equal(after.nodes.find((node) => node.id === taskId)?.status, expected);
443 assert.equal(after.turnItems.find((item) => item.id === itemId)?.status, expected);
444 assert.equal(
445 after.subagents.find((task) => task.id === taskId)?.completionDelivery?.state,
398 - "disposed",
446 + type === "subagent.stop" && expected === "running" ? undefined : "disposed",
447 );
448 assert.equal(
449 after.subagents.find((task) => task.id === original.id)?.result,
@@ -404,7 +452,9 @@ it.effect.each([
452 assert.deepEqual(yield* orchestrator.getThreadProjection(childThreadId), childBeforeStop);
453 if (expected === "cancelled") {
454 assert.lengthOf(
407 - (yield* orchestrator.getThreadShell(parentThreadId))?.pendingBackgroundTasks ?? [],
455 + (
456 + (yield* orchestrator.getThreadShell(parentThreadId))?.pendingBackgroundTasks ?? []
457 + ).filter((task) => task.kind === "subagent"),
458 0,
459 );
460 yield* orchestrator.recoverDelegatedTasks;
@@ -421,6 +471,30 @@ it.effect.each([
471 }).pipe(Effect.provide(layerTest)),
472 );
473
474 +it.effect("Stop still stops the thread when a delegated child cannot be read", () =>
475 + Effect.gen(function* () {
476 + const orchestrator = yield* Orchestrator.OrchestratorV2;
477 + const sql = yield* SqlClient.SqlClient;
478 + const parentThreadId = ThreadId.make("thread:unreadable-child-parent");
479 + yield* createWatchingThread(parentThreadId, 1);
480 + yield* send(parentThreadId, "parent", "start_immediately");
481 + const childThreadId = yield* delegate(parentThreadId, "unreadable child");
482 + yield* sql`
483 + UPDATE orchestration_v2_projection_runs
484 + SET payload_json = '{"obsolete":true}'
485 + WHERE thread_id = ${childThreadId}
486 + `;
487 + yield* orchestrator.dispatch({
488 + type: "run.interrupt",
489 + commandId: CommandId.make("stop:unreadable-child"),
490 + threadId: parentThreadId,
491 + runId: (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!.id,
492 + holdQueue: true,
493 + });
494 + assert.deepEqual(yield* threadState(parentThreadId), { runs: ["interrupted"], watched: [] });
495 + }).pipe(Effect.provide(layerTest)),
496 +);
497 +
498 it.effect("Stop ends watches, holds queues, and stops the delegated tasks under the thread", () =>
499 Effect.gen(function* () {
500 const orchestrator = yield* Orchestrator.OrchestratorV2;
apps/web/src/components/chat/ThreadRelationshipsControl.tsx
+2 -5
@@ -366,16 +366,13 @@ export function ThreadRelationshipsPanel(props: {
366
367 const stopSubagent = async (
368 childThreadId: ThreadId,
369 - agent: Pick<OrchestrationV2Subagent, "id" | "origin" | "threadId">,
369 + agent: Pick<OrchestrationV2Subagent, "id" | "threadId">,
370 ) => {
371 if (stoppingId !== null) return;
372 setStoppingId(childThreadId);
373 const result = await interruptTurn({
374 environmentId: props.environmentId,
375 - input:
376 - agent.origin === "provider_native"
377 - ? { threadId: agent.threadId, subagentId: agent.id }
378 - : { threadId: childThreadId },
375 + input: { threadId: agent.threadId, subagentId: agent.id },
376 });
377 setStoppingId(null);
378 if (result._tag === "Failure") {
packages/client-runtime/src/operations/commands.test.ts
+59
@@ -588,6 +588,65 @@ describe("V2 environment commands", () => {
588 }).pipe(Effect.provide(layerTestCrypto)),
589 );
590
591 + it.effect(
592 + "an app-owned subagent stop asks the parent to clear an orphan, then stops the child",
593 + () =>
594 + Effect.gen(function* () {
595 + const subagentId = NodeId.make("app-owned-subagent");
596 + const runId = RunId.make("parent-run");
597 + const childThreadId = ThreadId.make("app-owned-child-thread");
598 + const commands: OrchestrationV2Command[] = [];
599 + const supervisor = yield* makeSupervisor({
600 + commands,
601 + projects: [],
602 + advertiseThreadStop: true,
603 + projection: {
604 + ...v2Projection,
605 + subagents: [
606 + {
607 + id: subagentId,
608 + threadId: v2ThreadId,
609 + runId,
610 + parentNodeId: NodeId.make("owner-node"),
611 + origin: "app_owned",
612 + createdBy: "agent",
613 + driver: ProviderDriverKind.make("codex"),
614 + providerInstanceId: ProviderInstanceId.make("codex"),
615 + providerThreadId: null,
616 + childThreadId,
617 + nativeTaskRef: null,
618 + prompt: "Work",
619 + title: null,
620 + model: null,
621 + result: null,
622 + status: "running",
623 + startedAt: v2Now,
624 + completedAt: null,
625 + updatedAt: v2Now,
626 + },
627 + ],
628 + },
629 + });
630 + yield* interruptThreadTurn({
631 + commandId: CommandId.make("lineage-stop"),
632 + threadId: v2ThreadId,
633 + subagentId,
634 + // A parent run must not be interrupted on the child thread.
635 + runId,
636 + }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
637 + expect(commands).toEqual([
638 + {
639 + type: "subagent.stop",
640 + commandId: expect.any(String),
641 + threadId: v2ThreadId,
642 + runId,
643 + subagentId,
644 + },
645 + { type: "thread.stop", commandId: "lineage-stop", threadId: childThreadId },
646 + ]);
647 + }).pipe(Effect.provide(layerTestCrypto)),
648 + );
649 +
650 it.effect("stops a thread without relying on background work in the history window", () =>
651 Effect.gen(function* () {
652 const commands: OrchestrationV2Command[] = [];
packages/client-runtime/src/operations/commands.ts
+31 -13
@@ -769,19 +769,37 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")(
769 export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThreadTurn")(function* (
770 input: InterruptThreadTurnInput,
771 ) {
772 + let threadId = input.threadId;
773 if (input.subagentId !== undefined) {
774 const projection = yield* getProjection(input.threadId);
775 const subagent = projection.subagents.find((agent) => agent.id === input.subagentId);
775 - if (subagent?.runId == null) return { sequence: 0 };
776 - return yield* dispatch({
777 - type: "subagent.stop",
778 - commandId: yield* allocateCommandId(input),
779 - threadId: input.threadId,
780 - runId: subagent.runId,
781 - subagentId: subagent.id,
782 - });
776 + if (subagent?.origin === "app_owned" && subagent.childThreadId !== null) {
777 + // The parent cancels the task if it is an orphan with an idle child (#19002). Older
778 + // servers reject this for app-owned tasks, so the child stop below still runs.
779 + if (subagent.runId !== null) {
780 + yield* dispatch({
781 + type: "subagent.stop",
782 + commandId: yield* allocateCommandId({}),
783 + threadId: input.threadId,
784 + runId: subagent.runId,
785 + subagentId: subagent.id,
786 + }).pipe(Effect.ignore);
787 + }
788 + threadId = subagent.childThreadId;
789 + } else {
790 + if (subagent?.runId == null) return { sequence: 0 };
791 + return yield* dispatch({
792 + type: "subagent.stop",
793 + commandId: yield* allocateCommandId(input),
794 + threadId: input.threadId,
795 + runId: subagent.runId,
796 + subagentId: subagent.id,
797 + });
798 + }
799 }
784 - let runId = input.runId ?? (input.turnId as RunId | undefined);
800 + // A run named by the caller belongs to the parent, not the rerouted child.
801 + let runId =
802 + threadId === input.threadId ? (input.runId ?? (input.turnId as RunId | undefined)) : undefined;
803 if (runId === undefined) {
804 const config = yield* getInitialServerConfig();
805 if (config.environment.capabilities.threadStop === true) {
@@ -789,12 +807,12 @@ export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThrea
807 return yield* dispatch({
808 type: "thread.stop",
809 commandId: yield* allocateCommandId(input),
792 - threadId: input.threadId,
810 + threadId,
811 });
812 }
813 }
814 if (runId === undefined) {
797 - const projection = yield* getProjection(input.threadId);
815 + const projection = yield* getProjection(threadId);
816 runId = projection.runs.findLast(
817 (run) =>
818 run.status === "preparing" ||
@@ -823,7 +841,7 @@ export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThrea
841 result = yield* dispatch({
842 type: "thread.pull-request.watch",
843 commandId: yield* allocateCommandId(result.sequence === 0 ? input : {}),
826 - threadId: input.threadId,
844 + threadId,
845 host: link.host,
846 repository: link.repository,
847 number: link.number,
@@ -837,7 +855,7 @@ export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThrea
855 return yield* dispatch({
856 type: "run.interrupt",
857 commandId: yield* allocateCommandId(input),
840 - threadId: input.threadId,
858 + threadId,
859 runId,
860 holdQueue: true,
861 });