The best way to control Claude Code, Codex and more from any computer or phone
fix(server): transfer native child routing between runs (#21615)
Julius Marminge committed
Oct 19, 2026 at 20:26 UTC
6a049d0ea10ee8b75b43ea0e5f2851dee36c31c8
2 files changed
+313
-14
apps/server/src/orchestration-v2/RunExecutionService.test.ts
+200
-1
@@ -327,6 +327,141 @@ it("routes only enrolled workflow members after the root turn ends", () => {
327
);
328
});
329
330
+it("moves a child thread to the run that shows its subagent now", () => {
331
+ const threadId = ThreadId.make("thread:handoff");
332
+ const rootProviderTurnId = ProviderTurnId.make("provider-turn:handoff");
333
+ const identity: RunExecutionService.ProviderEventRouteIdentity = {
334
+ threadId,
335
+ runId: RunId.make("run:handoff:1"),
336
+ attemptId: RunAttemptId.make("attempt:handoff:1"),
337
+ providerThreadId: ProviderThreadId.make("provider-thread:handoff"),
338
+ };
339
+ const resumedChild = ThreadId.make("thread:handoff:resumed");
340
+ const siblingChild = ThreadId.make("thread:handoff:sibling");
341
+ const providerThreadOf = (childThreadId: ThreadId) =>
342
+ ProviderThreadId.make(`provider-thread:${childThreadId}`);
343
+ const subagent = (childThreadId: ThreadId, runId: RunId): OrchestrationV2Subagent => ({
344
+ id: NodeId.make(`node:${childThreadId}`),
345
+ threadId,
346
+ runId,
347
+ parentNodeId: NodeId.make("node:handoff"),
348
+ origin: "provider_native",
349
+ createdBy: "agent",
350
+ driver,
351
+ providerInstanceId: ProviderInstanceId.make("codex"),
352
+ providerThreadId: providerThreadOf(childThreadId),
353
+ childThreadId,
354
+ nativeTaskRef: null,
355
+ prompt: "Work",
356
+ title: "Work",
357
+ model: null,
358
+ status: "running",
359
+ result: null,
360
+ startedAt: null,
361
+ completedAt: null,
362
+ updatedAt: DateTime.makeUnsafe(0),
363
+ });
364
+ const childMessage = (childThreadId: ThreadId) =>
365
+ ({
366
+ type: "message.updated",
367
+ driver,
368
+ message: {
369
+ id: MessageId.make(`message:${childThreadId}`),
370
+ threadId: childThreadId,
371
+ runId: null,
372
+ },
373
+ }) as ProviderAdapter.ProviderAdapterV2Event;
374
+ const childTurn = (childThreadId: ThreadId, ordinal: number) =>
375
+ ({
376
+ type: "provider_turn.updated",
377
+ driver,
378
+ providerTurn: {
379
+ id: ProviderTurnId.make(`provider-turn:${childThreadId}:${ordinal}`),
380
+ providerThreadId: providerThreadOf(childThreadId),
381
+ runAttemptId: null,
382
+ status: "running",
383
+ },
384
+ }) as ProviderAdapter.ProviderAdapterV2Event;
385
+ const ended = RunExecutionService.routeProviderEvent(
386
+ {
387
+ type: "turn.terminal",
388
+ driver,
389
+ providerThreadId: identity.providerThreadId,
390
+ providerTurnId: rootProviderTurnId,
391
+ runOrdinal: 1,
392
+ status: "completed",
393
+ failure: null,
394
+ threadDisposition: "reusable",
395
+ },
396
+ identity,
397
+ RunExecutionService.makeProviderEventRoutingState({
398
+ identity,
399
+ providerTurnId: rootProviderTurnId,
400
+ relatedThreadIds: [resumedChild, siblingChild],
401
+ relatedProviderThreadIds: [providerThreadOf(resumedChild), providerThreadOf(siblingChild)],
402
+ }),
403
+ )[1];
404
+ const [firstTurnAccepted, withChildTurn] = RunExecutionService.routeProviderEvent(
405
+ childTurn(resumedChild, 1),
406
+ identity,
407
+ ended,
408
+ );
409
+ assert.isTrue(firstTurnAccepted);
410
+ const [movedAccepted, afterMove] = RunExecutionService.routeProviderEvent(
411
+ {
412
+ type: "subagent.updated",
413
+ driver,
414
+ subagent: subagent(resumedChild, RunId.make("run:handoff:2")),
415
+ },
416
+ identity,
417
+ withChildTurn,
418
+ );
419
+ assert.isFalse(movedAccepted);
420
+ assert.isFalse(
421
+ RunExecutionService.routeProviderEvent(childMessage(resumedChild), identity, afterMove)[0],
422
+ );
423
+ assert.isTrue(
424
+ RunExecutionService.routeProviderEvent(childMessage(siblingChild), identity, afterMove)[0],
425
+ );
426
+ assert.isFalse(
427
+ RunExecutionService.routeProviderEvent(childTurn(resumedChild, 1), identity, afterMove)[0],
428
+ );
429
+ assert.isFalse(
430
+ RunExecutionService.routeProviderEvent(childTurn(resumedChild, 2), identity, afterMove)[0],
431
+ );
432
+ assert.isTrue(
433
+ RunExecutionService.routeProviderEvent(childTurn(siblingChild, 1), identity, afterMove)[0],
434
+ );
435
+ assert.isTrue(
436
+ RunExecutionService.routeProviderEvent(
437
+ { type: "subagent.updated", driver, subagent: subagent(siblingChild, identity.runId) },
438
+ identity,
439
+ afterMove,
440
+ )[0],
441
+ );
442
+ const resuming: RunExecutionService.ProviderEventRouteIdentity = {
443
+ ...identity,
444
+ runId: RunId.make("run:handoff:2"),
445
+ attemptId: RunAttemptId.make("attempt:handoff:2"),
446
+ };
447
+ const resumingState = RunExecutionService.makeProviderEventRoutingState({
448
+ identity: resuming,
449
+ providerTurnId: ProviderTurnId.make("provider-turn:handoff:2"),
450
+ });
451
+ assert.isFalse(
452
+ RunExecutionService.routeProviderEvent(childMessage(resumedChild), resuming, resumingState)[0],
453
+ );
454
+ const [moveAccepted, afterTake] = RunExecutionService.routeProviderEvent(
455
+ { type: "subagent.updated", driver, subagent: subagent(resumedChild, resuming.runId) },
456
+ resuming,
457
+ resumingState,
458
+ );
459
+ assert.isTrue(moveAccepted);
460
+ assert.isTrue(
461
+ RunExecutionService.routeProviderEvent(childMessage(resumedChild), resuming, afterTake)[0],
462
+ );
463
+});
464
+
465
it("does not route a superseded attempt through a reused provider thread", () => {
466
const threadId = ThreadId.make("thread:shared-runtime:restart");
467
const providerThreadId = ProviderThreadId.make("provider-thread:shared-runtime:restart");
@@ -1740,6 +1875,65 @@ it.effect("keeps ingesting a child thread's late background item completion", ()
1875
}),
1876
);
1877
1878
+it.effect.each([null, "run:nested-sdk"] as const)(
1879
+ "releases a settled run when its live child transfers to another run (%s)",
1880
+ (nestedRunId) =>
1881
+ Effect.gen(function* () {
1882
+ const consumed = yield* Deferred.make<void>();
1883
+ const result = yield* Effect.raceFirst(
1884
+ runBackgroundItemScenario(
1885
+ "child-transfer-release",
1886
+ (ids) => {
1887
+ const running = subagentEvent(ids, "running");
1888
+ if (running.type !== "subagent.updated") throw new Error("Missing subagent");
1889
+ const linked = {
1890
+ ...running,
1891
+ subagent: {
1892
+ ...running.subagent,
1893
+ origin: "provider_native" as const,
1894
+ childThreadId: ids.childThreadId,
1895
+ providerThreadId: null,
1896
+ },
1897
+ };
1898
+ return [
1899
+ childThreadCreatedEvent(ids),
1900
+ linked,
1901
+ {
1902
+ ...linked,
1903
+ subagent: {
1904
+ ...linked.subagent,
1905
+ id: NodeId.make("node:child-transfer-release:nested"),
1906
+ threadId: ids.childThreadId,
1907
+ runId: nestedRunId === null ? null : RunId.make(nestedRunId),
1908
+ childThreadId: null,
1909
+ },
1910
+ },
1911
+ childBackgroundTurnItemEvent(ids, "running", 1),
1912
+ rootTerminalEvent(ids, "completed"),
1913
+ { ...linked, subagent: { ...linked.subagent, runId: RunId.make("run:replacement") } },
1914
+ ];
1915
+ },
1916
+ {
1917
+ keepEventStreamOpen: true,
1918
+ onEventsConsumed: Deferred.succeed(consumed, undefined).pipe(Effect.asVoid),
1919
+ },
1920
+ ).pipe(Effect.map(Option.some)),
1921
+ Deferred.await(consumed).pipe(Effect.as(Option.none())),
1922
+ );
1923
+ assert.isTrue(
1924
+ Option.isSome(result),
1925
+ "the transferred child must release its prior subscription",
1926
+ );
1927
+ if (Option.isSome(result))
1928
+ assert.deepEqual(result.value, [
1929
+ "subagent:running",
1930
+ "subagent:running",
1931
+ "turn_item:running",
1932
+ "root-finalized",
1933
+ ]);
1934
+ }),
1935
+);
1936
+
1937
it.effect("keeps ingesting until the last of several background items terminalizes", () =>
1938
Effect.gen(function* () {
1939
const secondItemId = TurnItemId.make("turn-item:bg-multi:second");
@@ -4377,6 +4571,7 @@ function runBackgroundItemScenario(
4571
ReadonlyArray<{ readonly id: TurnItemId; readonly runId: RunId }>
4572
>;
4573
readonly onSubscribe?: Effect.Effect<void>;
4574
+ readonly onEventsConsumed?: Effect.Effect<void>;
4575
readonly onFinalized?: (
4576
events: ReadonlyArray<OrchestrationV2DomainEvent>,
4577
) => Effect.Effect<void>;
@@ -4444,7 +4639,11 @@ function runBackgroundItemScenario(
4639
events: Stream.empty,
4640
subscribeEvents: Effect.gen(function* () {
4641
yield* options?.onSubscribe ?? Effect.void;
4447
- const events = Stream.fromIterable(makeEvents(ids));
4642
+ const events = Stream.fromIterable(makeEvents(ids)).pipe(
4643
+ Stream.concat(
4644
+ Stream.fromEffect(options?.onEventsConsumed ?? Effect.void).pipe(Stream.drain),
4645
+ ),
4646
+ );
4647
return {
4648
events:
4649
options?.keepEventStreamOpen === true
apps/server/src/orchestration-v2/RunExecutionService.ts
+113
-13
@@ -60,7 +60,7 @@ export interface ProviderEventRoutingState {
60
readonly rootTurnEnded: boolean;
61
readonly workflowMemberParents: ReadonlyMap<ThreadId, ThreadId>;
62
readonly ownedProviderThreadIds: ReadonlySet<ProviderThreadId>;
63
- readonly ownedProviderTurnIds: ReadonlySet<ProviderTurnId>;
63
+ readonly ownedProviderTurns: ReadonlyMap<ProviderTurnId, ProviderThreadId>;
64
readonly inheritedBackgroundTurnItems: ReadonlyMap<TurnItemId, OrchestrationV2Run["id"]>;
65
readonly rootProviderTurnId: ProviderTurnId | null;
66
}
@@ -337,8 +337,10 @@ export function makeProviderEventRoutingState(input: {
337
input.identity.providerThreadId,
338
...(input.relatedProviderThreadIds ?? []),
339
]),
340
- ownedProviderTurnIds:
341
- input.providerTurnId === null ? new Set() : new Set([input.providerTurnId]),
340
+ ownedProviderTurns:
341
+ input.providerTurnId === null
342
+ ? new Map()
343
+ : new Map([[input.providerTurnId, input.identity.providerThreadId]]),
344
inheritedBackgroundTurnItems: new Map(
345
(input.inheritedBackgroundTurnItems ?? []).map((item) => [item.id, item.runId]),
346
),
@@ -361,10 +363,11 @@ export function routeProviderEvent(
363
});
364
const addProviderTurn = (
365
providerTurnId: ProviderTurnId,
366
+ providerThreadId: ProviderThreadId,
367
root: boolean,
368
): ProviderEventRoutingState => ({
369
...state,
367
- ownedProviderTurnIds: new Set([...state.ownedProviderTurnIds, providerTurnId]),
370
+ ownedProviderTurns: new Map(state.ownedProviderTurns).set(providerTurnId, providerThreadId),
371
rootProviderTurnId: root ? providerTurnId : state.rootProviderTurnId,
372
});
373
@@ -405,9 +408,14 @@ export function routeProviderEvent(
408
isRoot ||
409
(event.providerTurn.providerThreadId !== input.providerThreadId &&
410
state.ownedProviderThreadIds.has(event.providerTurn.providerThreadId)) ||
408
- state.ownedProviderTurnIds.has(event.providerTurn.id) ||
411
+ state.ownedProviderTurns.has(event.providerTurn.id) ||
412
(event.threadId !== undefined && ownsChildThread(event.threadId));
410
- return belongs ? [true, addProviderTurn(event.providerTurn.id, isRoot)] : [false, state];
413
+ return belongs
414
+ ? [
415
+ true,
416
+ addProviderTurn(event.providerTurn.id, event.providerTurn.providerThreadId, isRoot),
417
+ ]
418
+ : [false, state];
419
}
420
case "node.updated": {
421
const belongs = ownsRun(event.node.runId) || ownsChildThread(event.node.threadId);
@@ -417,6 +425,25 @@ export function routeProviderEvent(
425
return [true, addProviderThread(event.node.providerThreadId)];
426
}
427
case "subagent.updated": {
428
+ const moved = event.subagent;
429
+ if (
430
+ moved.origin === "provider_native" &&
431
+ moved.threadId === input.threadId &&
432
+ moved.runId !== null &&
433
+ !ownsRun(moved.runId) &&
434
+ moved.childThreadId !== null &&
435
+ ownsChildThread(moved.childThreadId)
436
+ ) {
437
+ const ownedThreadIds = new Set(state.ownedThreadIds);
438
+ ownedThreadIds.delete(moved.childThreadId);
439
+ const ownedProviderThreadIds = new Set(state.ownedProviderThreadIds);
440
+ if (moved.providerThreadId !== null) ownedProviderThreadIds.delete(moved.providerThreadId);
441
+ const ownedProviderTurns = new Map(state.ownedProviderTurns);
442
+ for (const [turnId, threadId] of ownedProviderTurns) {
443
+ if (threadId === moved.providerThreadId) ownedProviderTurns.delete(turnId);
444
+ }
445
+ return [false, { ...state, ownedThreadIds, ownedProviderThreadIds, ownedProviderTurns }];
446
+ }
447
const belongs = ownsRun(event.subagent.runId) || ownsChildThread(event.subagent.threadId);
448
const coordinator = event.subagent;
449
// A provider-native subagent's child thread follows the live run it is
@@ -478,7 +505,7 @@ export function routeProviderEvent(
505
return [
506
(event.threadId !== undefined && ownsChildThread(event.threadId)) ||
507
(event.runtimeRequest.providerTurnId !== null &&
481
- state.ownedProviderTurnIds.has(event.runtimeRequest.providerTurnId)),
508
+ state.ownedProviderTurns.has(event.runtimeRequest.providerTurnId)),
509
state,
510
];
511
case "command_output.delta":
@@ -974,7 +1001,7 @@ export const layer: Layer.Layer<
1001
const rootRunFinalized = yield* Ref.make(false);
1002
const providerThreadOwnerLost = yield* Ref.make(false);
1003
const activeChildProviderTurns = yield* Ref.make<ReadonlySet<ProviderTurnId>>(new Set());
977
- const activeChildSubagents = yield* Ref.make<ReadonlySet<NodeId>>(new Set());
1004
+ const activeChildSubagents = yield* Ref.make<ReadonlyMap<NodeId, ThreadId>>(new Map());
1005
const activeBackgroundTurnItems = yield* Ref.make<
1006
ReadonlySet<OrchestrationV2TurnItem["id"]>
1007
>(new Set(inheritedBackgroundTurnItemsById.keys()));
@@ -1050,11 +1077,11 @@ export const layer: Layer.Layer<
1077
routing.ownedThreadIds.has(event.subagent.threadId);
1078
if (belongsToRootRun || belongsToOwnedChildThread) {
1079
yield* Ref.update(activeChildSubagents, (current) => {
1053
- const next = new Set(current);
1080
+ const next = new Map(current);
1081
if (isSettledSubagentStatus(event.subagent.status)) {
1082
next.delete(event.subagent.id);
1083
} else {
1057
- next.add(event.subagent.id);
1084
+ next.set(event.subagent.id, event.subagent.threadId);
1085
}
1086
return next;
1087
});
@@ -1209,11 +1236,84 @@ export const layer: Layer.Layer<
1236
// when finally written, behind every item that began after it.
1237
const reservedHeldTurnItemIds = new Set<TurnItemId>();
1238
const providerEventFiber = yield* eventSubscription.events.pipe(
1212
- Stream.filterEffect((event) =>
1213
- Ref.modify(eventRouting, (state) => routeProviderEvent(event, routeIdentity, state)),
1239
+ Stream.mapEffect((event) =>
1240
+ Effect.gen(function* () {
1241
+ const previous = yield* Ref.get(eventRouting);
1242
+ const [accepted, routing] = routeProviderEvent(event, routeIdentity, previous);
1243
+ yield* Ref.set(eventRouting, routing);
1244
+ if (
1245
+ event.type === "subagent.updated" &&
1246
+ event.subagent.childThreadId !== null &&
1247
+ previous.ownedThreadIds.has(event.subagent.childThreadId) &&
1248
+ !routing.ownedThreadIds.has(event.subagent.childThreadId)
1249
+ ) {
1250
+ const moved = event.subagent;
1251
+ const detached = yield* Ref.modify(openRunOwnedSubagents, (current) => {
1252
+ const subagentIds = new Set([moved.id]);
1253
+ for (const subagent of current.subagents.values()) {
1254
+ if (subagent.threadId === moved.childThreadId) subagentIds.add(subagent.id);
1255
+ }
1256
+ const childTurnItems = new Map(
1257
+ [...current.childTurnItems].filter(
1258
+ ([, item]) => item.threadId !== moved.childThreadId,
1259
+ ),
1260
+ );
1261
+ const turnItems = new Map(current.turnItems);
1262
+ turnItems.delete(moved.id);
1263
+ const detachedItems = new Set(
1264
+ [...current.childTurnItems.values(), ...current.turnItems.values()]
1265
+ .filter(
1266
+ (item) => item.threadId === moved.childThreadId || item.nodeId === moved.id,
1267
+ )
1268
+ .map((item) => item.id),
1269
+ );
1270
+ return [
1271
+ { itemIds: detachedItems, subagentIds },
1272
+ {
1273
+ subagents: new Map(
1274
+ [...current.subagents].filter(([id]) => !subagentIds.has(id)),
1275
+ ),
1276
+ turnItems,
1277
+ childTurnItems,
1278
+ nodes: new Map(
1279
+ [...current.nodes].filter(
1280
+ ([id, node]) => id !== moved.id && node.threadId !== moved.childThreadId,
1281
+ ),
1282
+ ),
1283
+ linkedChildThreadIds: new Set(
1284
+ [...current.linkedChildThreadIds].filter(
1285
+ (id) => id !== moved.childThreadId,
1286
+ ),
1287
+ ),
1288
+ },
1289
+ ];
1290
+ });
1291
+ yield* Ref.update(
1292
+ activeChildSubagents,
1293
+ (current) =>
1294
+ new Map(
1295
+ [...current].filter(
1296
+ ([id, threadId]) =>
1297
+ !detached.subagentIds.has(id) && threadId !== moved.childThreadId,
1298
+ ),
1299
+ ),
1300
+ );
1301
+ yield* Ref.update(
1302
+ activeChildProviderTurns,
1303
+ (current) =>
1304
+ new Set([...current].filter((id) => routing.ownedProviderTurns.has(id))),
1305
+ );
1306
+ yield* Ref.update(
1307
+ activeBackgroundTurnItems,
1308
+ (current) => new Set([...current].filter((id) => !detached.itemIds.has(id))),
1309
+ );
1310
+ }
1311
+ return { event, accepted };
1312
+ }),
1313
),
1215
- Stream.tap((event) =>
1314
+ Stream.tap(({ event, accepted }) =>
1315
Effect.gen(function* () {
1316
+ if (!accepted) return;
1317
let storedEventCount = 0;
1318
const deliveredEvent = filterAssistantEvent(
1319
event,