@devries-cameron20 / t3code-1 / commits / 7792cd5445
Fork 0

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

fix(server): parent Stop clears orphaned delegated follow-ups (#20310)

kuna committed Oct 18, 2026 at 15:54 UTC 7792cd544515892382acbd3174b323e294277fce
2 files changed +371
apps/server/src/orchestration-v2/Orchestrator.ts
+108
@@ -20,6 +20,7 @@ import {
20 ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE,
21 type ChatAttachment,
22 CommandId,
23 + isOrchestrationV2WorkActive,
24 isProviderNativeSubagentThread,
25 MessageId,
26 type NodeId,
@@ -9514,6 +9515,111 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
9515 ),
9516 );
9517 if (projection.thread.deletedAt !== null) return undefined;
9518 + const cancelIdleOrphans = Effect.gen(function* () {
9519 + const pending = yield* Ref.get(events);
9520 + const children = new Map<
9521 + ThreadId,
9522 + ProjectionRecords<"runs" | "providerThreads" | "runtimeRequests" | "turnItems"> | null
9523 + >();
9524 + const idleChildren = new Map<ThreadId, boolean>();
9525 + let nodes: ReadonlyArray<OrchestrationV2ExecutionNode> | undefined;
9526 + for (const recorded of projection.subagents) {
9527 + const updated = pending.findLast(
9528 + (event) => event.type === "subagent.updated" && event.payload.id === recorded.id,
9529 + );
9530 + const task = updated?.type === "subagent.updated" ? updated.payload : recorded;
9531 + if (
9532 + task.origin !== "app_owned" ||
9533 + task.childThreadId === null ||
9534 + !isOrchestrationV2WorkActive(task.status)
9535 + )
9536 + continue;
9537 + const childThreadId = task.childThreadId;
9538 + const child = children.has(childThreadId)
9539 + ? (children.get(childThreadId) ?? null)
9540 + : yield* projectionStore
9541 + .getThreadRecords(
9542 + childThreadId,
9543 + ["runs", "providerThreads", "runtimeRequests", "turnItems"],
9544 + {
9545 + turnItemTypes: ["command_execution", "dynamic_tool", "subagent"],
9546 + turnItemStatuses: ["pending", "running", "waiting"],
9547 + },
9548 + )
9549 + .pipe(
9550 + Effect.catchTags({
9551 + ProjectionStoreThreadNotFoundError: () => Effect.succeed(null),
9552 + }),
9553 + Effect.mapError(
9554 + (cause) => new OrchestratorProjectionError({ threadId: childThreadId, cause }),
9555 + ),
9556 + );
9557 + children.set(childThreadId, child);
9558 + if (child === null) continue;
9559 + if (
9560 + child.thread.lineage.parentThreadId !== command.threadId ||
9561 + child.thread.lineage.relationshipToParent !== "subagent" ||
9562 + (child.thread.forkedFrom?.type === "node" &&
9563 + child.thread.forkedFrom.nodeId === task.id) ||
9564 + child.runs.some((run) => run.delegatedTaskId === task.id)
9565 + )
9566 + continue;
9567 + const idle =
9568 + idleChildren.get(task.childThreadId) ??
9569 + (!child.runs.some((run) => run.status === "queued" || isBlockingRun(run)) &&
9570 + !child.providerThreads.some(
9571 + (thread) =>
9572 + thread.status === "active" || (thread.pendingBackgroundTasks?.length ?? 0) > 0,
9573 + ) &&
9574 + !child.runtimeRequests.some((request) => request.status === "pending") &&
9575 + child.turnItems.length === 0 &&
9576 + Option.isNone(yield* Effect.findFirst(child.runs, awaitsRestartContinuation)));
9577 + idleChildren.set(task.childThreadId, idle);
9578 + if (!idle) continue;
9579 + // Stop can cancel an idle orphan without guessing which completed run owned its result.
9580 + const now = yield* DateTime.now;
9581 + const emitEvent = emit(events, command);
9582 + yield* emitEvent({
9583 + type: "subagent.updated",
9584 + threadId: command.threadId,
9585 + nodeId: task.id,
9586 + occurredAt: now,
9587 + payload: {
9588 + ...task,
9589 + status: "cancelled",
9590 + completedAt: now,
9591 + updatedAt: now,
9592 + completionDelivery: { state: "disposed", observedByRunId: null },
9593 + },
9594 + });
9595 + nodes ??= (yield* projectionStore.getThreadRecords(command.threadId, ["nodes"])).nodes;
9596 + const node = nodes.find((candidate) => candidate.id === task.id);
9597 + if (node !== undefined)
9598 + yield* emitEvent({
9599 + type: "node.updated",
9600 + threadId: command.threadId,
9601 + nodeId: node.id,
9602 + occurredAt: now,
9603 + payload: { ...node, status: "cancelled", completedAt: now },
9604 + });
9605 + for (const item of projection.turnItems) {
9606 + if (item.type !== "subagent" || item.subagentId !== task.id) continue;
9607 + yield* emitEvent({
9608 + type: "turn-item.updated",
9609 + threadId: command.threadId,
9610 + nodeId: task.id,
9611 + occurredAt: now,
9612 + payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
9613 + });
9614 + }
9615 + }
9616 + }).pipe(
9617 + Effect.mapError((cause) =>
9618 + Schema.is(OrchestratorProjectionError)(cause)
9619 + ? cause
9620 + : new OrchestratorProjectionError({ threadId: command.threadId, cause }),
9621 + ),
9622 + );
9623 const latestRun = projection.runs.findLast((run) => run.status !== "queued");
9624 const target =
9625 projection.runs.findLast(
@@ -9552,6 +9658,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
9658 const enqueued = yield* Ref.get(interruptEffects);
9659 yield* Ref.update(events, (existing) => [...existing, ...written]);
9660 yield* Ref.update(effects, (existing) => [...existing, ...enqueued]);
9661 + yield* cancelIdleOrphans;
9662 return interrupted.value;
9663 }
9664 yield* Effect.logWarning("thread.stop could not interrupt the running turn", {
@@ -9572,6 +9679,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
9679 yield* markStoppedRun({ command, events, thread: projection.thread, run, now });
9680 }
9681 yield* holdStoppedThread({ command, events, projection, cohortRunIds: [], now });
9682 + yield* cancelIdleOrphans;
9683 return undefined;
9684 });
9685
apps/server/src/orchestration-v2/ThreadStop.test.ts
+263
@@ -1,9 +1,11 @@
1 import { assert, it } from "@effect/vitest";
2 import {
3 CommandId,
4 + ContextTransferId,
5 EventId,
6 MessageId,
7 NodeId,
8 + type OrchestrationV2DomainEvent,
9 ProjectId,
10 ProviderDriverKind,
11 ProviderInstanceId,
@@ -157,6 +159,267 @@ const threadState = (threadId: ThreadId) =>
159 };
160 });
161
162 +it.effect.each([
163 + "idle",
164 + "archived",
165 + "missing",
166 + "running",
167 + "queued",
168 + "waiting",
169 + "correlated",
170 + "provider-active",
171 + "roster",
172 + "background",
173 + "question",
174 + "restart",
175 +] as const)(
176 + "Stop clears an orphaned follow-up only when its child is finished (%s)",
177 + (childState) =>
178 + Effect.gen(function* () {
179 + const orchestrator = yield* Orchestrator.OrchestratorV2;
180 + const projections = yield* ProjectionStore.ProjectionStoreV2;
181 + const parentThreadId = ThreadId.make(`thread:orphan-parent:${childState}`);
182 + yield* createWatchingThread(parentThreadId, 1);
183 + yield* send(parentThreadId, "parent", "start_immediately");
184 + const childThreadId = yield* delegate(parentThreadId, "original task");
185 + const parent = yield* orchestrator.getThreadProjection(parentThreadId);
186 + const child = yield* orchestrator.getThreadProjection(childThreadId);
187 + const original = parent.subagents[0]!;
188 + const originalItem = parent.turnItems.find((item) => item.type === "subagent")!;
189 + const originalNode = parent.nodes.find((node) => node.id === original.id)!;
190 + const taskId = NodeId.make(`node:orphan-followup:${childState}`);
191 + const itemId = TurnItemId.make(`item:orphan-followup:${childState}`);
192 + const followupChildThreadId =
193 + childState === "missing" ? ThreadId.make("thread:missing-child") : childThreadId;
194 + const now = yield* DateTime.now;
195 + let sequence = 0;
196 + const apply = (event: Omit<OrchestrationV2DomainEvent, "id">) =>
197 + projections.apply({
198 + ...event,
199 + id: EventId.make(`event:orphan:${childState}:${sequence++}`),
200 + } as OrchestrationV2DomainEvent);
201 + yield* apply({
202 + type: "subagent.updated",
203 + threadId: parentThreadId,
204 + occurredAt: now,
205 + payload: {
206 + ...original,
207 + status: "completed",
208 + result: "Original result",
209 + completedAt: now,
210 + completionDelivery: { state: "acknowledged", observedByRunId: null },
211 + },
212 + });
213 + yield* apply({
214 + type: "context-transfer.created",
215 + threadId: parentThreadId,
216 + occurredAt: now,
217 + payload: {
218 + ...child.contextTransfers[0]!,
219 + id: ContextTransferId.make(`transfer:original-result:${childState}`),
220 + type: "subagent_result",
221 + sourceThreadId: childThreadId,
222 + targetThreadId: parentThreadId,
223 + sourcePoint: { threadId: childThreadId, runId: child.runs[0]!.id },
224 + targetRunId: parent.runs[0]!.id,
225 + },
226 + });
227 + yield* apply({
228 + type: "node.updated",
229 + threadId: parentThreadId,
230 + occurredAt: now,
231 + payload: { ...originalNode, status: "completed", completedAt: now },
232 + });
233 + yield* apply({
234 + type: "turn-item.updated",
235 + threadId: parentThreadId,
236 + occurredAt: now,
237 + payload: { ...originalItem, status: "completed", completedAt: now },
238 + });
239 + yield* apply({
240 + type: "subagent.updated",
241 + threadId: parentThreadId,
242 + occurredAt: now,
243 + payload: {
244 + ...original,
245 + id: taskId,
246 + childThreadId: followupChildThreadId,
247 + status: "running",
248 + result: null,
249 + completedAt: null,
250 + },
251 + });
252 + yield* apply({
253 + type: "node.updated",
254 + threadId: parentThreadId,
255 + occurredAt: now,
256 + payload: { ...originalNode, id: taskId, status: "running" },
257 + });
258 + assert.equal(originalItem.type, "subagent");
259 + if (originalItem.type !== "subagent") return;
260 + yield* apply({
261 + type: "turn-item.updated",
262 + threadId: parentThreadId,
263 + occurredAt: now,
264 + payload: {
265 + ...originalItem,
266 + id: itemId,
267 + nodeId: taskId,
268 + subagentId: taskId,
269 + childThreadId: followupChildThreadId,
270 + status: "running",
271 + },
272 + });
273 + const runAtStart = child.runs[0]!;
274 + const childRunStatus =
275 + childState === "running" || childState === "queued" || childState === "waiting"
276 + ? childState
277 + : "completed";
278 + yield* apply({
279 + type: "run.updated",
280 + threadId: childThreadId,
281 + occurredAt: now,
282 + payload: { ...runAtStart, status: "running", delegatedTaskId: taskId },
283 + });
284 + assert.equal(
285 + (yield* orchestrator.getThreadProjection(childThreadId)).runs[0]?.delegatedTaskId,
286 + taskId,
287 + );
288 + // A terminal write based on the attempt's start snapshot loses a later steer binding.
289 + yield* apply({
290 + type: "run.updated",
291 + threadId: childThreadId,
292 + occurredAt: now,
293 + payload: {
294 + ...runAtStart,
295 + status: childRunStatus,
296 + completedAt: childRunStatus === "completed" ? now : null,
297 + ...(childState === "correlated" ? { delegatedTaskId: taskId } : {}),
298 + },
299 + });
300 + assert.equal(
301 + (yield* orchestrator.getThreadProjection(childThreadId)).runs[0]?.delegatedTaskId,
302 + childState === "correlated" ? taskId : undefined,
303 + );
304 + if (childState === "provider-active" || childState === "roster") {
305 + yield* apply({
306 + type: "provider-thread.updated",
307 + threadId: childThreadId,
308 + occurredAt: now,
309 + payload: {
310 + ...child.providerThreads[0]!,
311 + status: childState === "provider-active" ? "active" : "idle",
312 + pendingBackgroundTasks:
313 + childState === "roster" ? [{ taskId: "background-task", kind: "command" }] : [],
314 + },
315 + });
316 + }
317 + if (childState === "background") {
318 + yield* apply({
319 + type: "turn-item.updated",
320 + threadId: childThreadId,
321 + occurredAt: now,
322 + payload: {
323 + ...originalItem,
324 + id: TurnItemId.make("item:child-background"),
325 + threadId: childThreadId,
326 + runId: runAtStart.id,
327 + nodeId: runAtStart.rootNodeId,
328 + type: "command_execution",
329 + status: "running",
330 + input: "test background work",
331 + },
332 + });
333 + }
334 + if (childState === "question") {
335 + yield* apply({
336 + type: "runtime-request.updated",
337 + threadId: childThreadId,
338 + occurredAt: now,
339 + payload: {
340 + id: RuntimeRequestId.make("request:child-question"),
341 + nodeId: runAtStart.rootNodeId!,
342 + providerTurnId: null,
343 + nativeRequestRef: null,
344 + kind: "user_input",
345 + status: "pending",
346 + responseCapability: { type: "message" },
347 + createdAt: now,
348 + resolvedAt: null,
349 + },
350 + });
351 + }
352 + if (childState === "restart") {
353 + const outbox = yield* EffectOutbox.EffectOutboxV2;
354 + yield* outbox.enqueue([
355 + {
356 + id: `effect:restart-continuation:${runAtStart.id}`,
357 + commandId: CommandId.make("command:child-restart"),
358 + threadId: childThreadId,
359 + request: { type: "provider-runtime.continue", sourceRunId: runAtStart.id },
360 + },
361 + ]);
362 + }
363 + yield* apply({
364 + type: "run.updated",
365 + threadId: parentThreadId,
366 + occurredAt: now,
367 + payload: { ...parent.runs[0]!, status: "completed", completedAt: now },
368 + });
369 + if (childState === "archived") {
370 + yield* apply({
371 + type: "thread.archived",
372 + threadId: childThreadId,
373 + occurredAt: now,
374 + payload: { ...child.thread, archivedAt: now },
375 + });
376 + }
377 + const childBeforeStop = yield* orchestrator.getThreadProjection(childThreadId);
378 + assert.lengthOf(
379 + ((yield* orchestrator.getThreadShell(parentThreadId))?.pendingBackgroundTasks ?? []).filter(
380 + (task) => task.kind === "subagent",
381 + ),
382 + 1,
383 + );
384 + yield* orchestrator.dispatch({
385 + type: "thread.stop",
386 + commandId: CommandId.make(`stop-orphan:${childState}`),
387 + threadId: parentThreadId,
388 + });
389 + const after = yield* orchestrator.getThreadProjection(parentThreadId);
390 + assert.isEmpty((after.thread.pullRequests ?? []).filter((link) => link.watch !== undefined));
391 + const expected = childState === "idle" || childState === "archived" ? "cancelled" : "running";
392 + assert.equal(after.subagents.find((task) => task.id === taskId)?.status, expected);
393 + assert.equal(after.nodes.find((node) => node.id === taskId)?.status, expected);
394 + assert.equal(after.turnItems.find((item) => item.id === itemId)?.status, expected);
395 + assert.equal(
396 + after.subagents.find((task) => task.id === taskId)?.completionDelivery?.state,
397 + "disposed",
398 + );
399 + assert.equal(
400 + after.subagents.find((task) => task.id === original.id)?.result,
401 + "Original result",
402 + );
403 + assert.deepEqual(yield* orchestrator.getThreadProjection(childThreadId), childBeforeStop);
404 + if (expected === "cancelled") {
405 + assert.lengthOf(
406 + (yield* orchestrator.getThreadShell(parentThreadId))?.pendingBackgroundTasks ?? [],
407 + 0,
408 + );
409 + yield* orchestrator.recoverDelegatedTasks;
410 + yield* orchestrator.dispatch({
411 + type: "thread.stop",
412 + commandId: CommandId.make(`stop-orphan-again:${childState}`),
413 + threadId: parentThreadId,
414 + });
415 + const repeated = yield* orchestrator.getThreadProjection(parentThreadId);
416 + assert.equal(repeated.subagents.find((task) => task.id === taskId)?.status, "cancelled");
417 + assert.deepEqual(repeated.messages, after.messages);
418 + assert.deepEqual(repeated.contextTransfers, after.contextTransfers);
419 + }
420 + }).pipe(Effect.provide(layerTest)),
421 +);
422 +
423 it.effect("Stop ends watches, holds queues, and stops the delegated tasks under the thread", () =>
424 Effect.gen(function* () {
425 const orchestrator = yield* Orchestrator.OrchestratorV2;