The best way to control Claude Code, Codex and more from any computer or phone
fix(server): finished delegated Codex children no longer pile up in Codex Recents (#34829)
Julius Marminge committed
Nov 11, 2026 at 23:52 UTC
eeae0b278319a9b176ce8418bc6504125b60c40a
4 files changed
+270
-7
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+6
@@ -7740,6 +7740,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
7740
function* (unloadInput) {
7741
const nativeThreadId = yield* getNativeThreadId(unloadInput.providerThread);
7742
sessionApprovals.delete(nativeThreadId);
7743
+ // Archive also unloads, inline and without thread/closed; resumeNativeThread
7744
+ // unarchives it on the next turn.
7745
+ if (unloadInput.archive === true) {
7746
+ yield* client.request("thread/archive", { threadId: nativeThreadId });
7747
+ return;
7748
+ }
7749
// A resume may already wait on the pending entry; replacing it would strand that wait.
7750
if (!threadClosings.has(nativeThreadId)) {
7751
threadClosings.set(nativeThreadId, yield* Deferred.make<void>());
apps/server/src/orchestration-v2/ProviderSessionManager.test.ts
+184
-2
@@ -448,6 +448,8 @@ const makeProviderAdapter = Effect.fnUntraced(function* (
448
readonly startTurn?: Effect.Effect<void>;
449
readonly interruptTurn?: Effect.Effect<void>;
450
readonly beforeUnload?: Effect.Effect<void>;
451
+ readonly unloads?: Queue.Queue<string>;
452
+ readonly archive?: Effect.Effect<void, ProviderAdapter.ProviderAdapterProtocolError>;
453
readonly spawnBeforeOpen?: boolean;
454
readonly scopeCloseReached?: Deferred.Deferred<void>;
455
} = {},
@@ -457,7 +459,11 @@ const makeProviderAdapter = Effect.fnUntraced(function* (
459
Ref.update(state, (current) => ({
460
...current,
461
closeCount: current.closeCount + 1,
460
- })),
462
+ })).pipe(
463
+ Effect.andThen(
464
+ options.unloads === undefined ? Effect.void : Queue.offer(options.unloads, "close"),
465
+ ),
466
+ ),
467
);
468
// Register after countClose to wedge teardown before its finalizer, matching a provider stream that never yields.
469
const hangClose = Effect.addFinalizer(() =>
@@ -563,7 +569,7 @@ const makeProviderAdapter = Effect.fnUntraced(function* (
569
...current,
570
interruptCount: current.interruptCount + 1,
571
})).pipe(Effect.andThen(options.interruptTurn ?? Effect.void)),
566
- unloadThread: ({ providerThread }) =>
572
+ unloadThread: ({ providerThread, archive }) =>
573
(options.beforeUnload ?? Effect.void).pipe(
574
Effect.andThen(
575
Ref.update(state, (current) => ({
@@ -574,6 +580,15 @@ const makeProviderAdapter = Effect.fnUntraced(function* (
580
],
581
})),
582
),
583
+ Effect.andThen(
584
+ options.unloads === undefined
585
+ ? Effect.void
586
+ : Queue.offer(
587
+ options.unloads,
588
+ `${archive === true ? "archive" : "unload"}:${providerThread.nativeThreadRef?.nativeId}`,
589
+ ),
590
+ ),
591
+ Effect.andThen(archive === true ? (options.archive ?? Effect.void) : Effect.void),
592
),
593
respondToRuntimeRequest: () => Effect.void,
594
readThreadSnapshot: () => unimplemented("readThreadSnapshot unused in test"),
@@ -614,6 +629,8 @@ function layerTest(input: {
629
readonly startTurn?: Effect.Effect<void>;
630
readonly interruptTurn?: Effect.Effect<void>;
631
readonly beforeUnload?: Effect.Effect<void>;
632
+ readonly unloads?: Queue.Queue<string>;
633
+ readonly archive?: Effect.Effect<void, ProviderAdapter.ProviderAdapterProtocolError>;
634
readonly spawnBeforeOpen?: boolean;
635
readonly scopeCloseReached?: Deferred.Deferred<void>;
636
readonly serverSettingsLayer?: ReturnType<typeof ServerSettings.layerTest>;
@@ -657,6 +674,8 @@ function layerTest(input: {
674
...(input.startTurn === undefined ? {} : { startTurn: input.startTurn }),
675
...(input.interruptTurn === undefined ? {} : { interruptTurn: input.interruptTurn }),
676
...(input.beforeUnload === undefined ? {} : { beforeUnload: input.beforeUnload }),
677
+ ...(input.unloads === undefined ? {} : { unloads: input.unloads }),
678
+ ...(input.archive === undefined ? {} : { archive: input.archive }),
679
...(input.spawnBeforeOpen === undefined ? {} : { spawnBeforeOpen: input.spawnBeforeOpen }),
680
...(input.scopeCloseReached === undefined
681
? {}
@@ -4706,6 +4725,169 @@ it.effect(
4725
}),
4726
);
4727
4728
+it.effect.each([
4729
+ { keptOpen: true, archive: "succeeds" },
4730
+ { keptOpen: false, archive: "succeeds" },
4731
+ { keptOpen: false, archive: "fails" },
4732
+ { keptOpen: false, archive: "hangs" },
4733
+] as const)(
4734
+ "ProviderSessionManagerV2 archives an idle delegated child once its parent has the result (session kept open: $keptOpen, archive $archive)",
4735
+ ({ keptOpen, archive }) =>
4736
+ Effect.gen(function* () {
4737
+ const state = yield* Ref.make(emptyState);
4738
+ const unloads = yield* Queue.unbounded<string>();
4739
+ const effect = Effect.gen(function* () {
4740
+ const eventSink = yield* EventSink.EventSinkV2;
4741
+ const idAllocator = yield* IdAllocator.IdAllocatorV2;
4742
+ const manager = yield* ProviderSessionManager.ProviderSessionManagerV2;
4743
+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;
4744
+ const now = yield* DateTime.now;
4745
+ const parentThreadId = ThreadId.make("thread-provider-session-manager-archive-parent");
4746
+ const parentRunId = idAllocator.derive.run({ threadId: parentThreadId, ordinal: 1 });
4747
+ const providerSessionId = idAllocator.derive.providerSession({
4748
+ providerInstanceId: modelSelection.instanceId,
4749
+ });
4750
+ yield* eventSink.write({
4751
+ events: [yield* makeThreadCreatedEvent({ idAllocator, threadId: parentThreadId, now })],
4752
+ });
4753
+ let deliverPending: OrchestrationV2DomainEvent | undefined;
4754
+ for (const delivery of ["pending", "delivered"] as const) {
4755
+ const threadId = ThreadId.make(`thread-provider-session-manager-archive-${delivery}`);
4756
+ const runId = idAllocator.derive.run({ threadId, ordinal: 1 });
4757
+ const taskId = idAllocator.derive.rootNode({ runId });
4758
+ const providerThread = makeProviderThread({
4759
+ idAllocator,
4760
+ threadId,
4761
+ providerSessionId,
4762
+ now,
4763
+ nativeThreadId: `native-${delivery}`,
4764
+ });
4765
+ const created = yield* makeThreadCreatedEvent({
4766
+ idAllocator,
4767
+ threadId,
4768
+ now,
4769
+ delegatedBy: parentThreadId,
4770
+ });
4771
+ const taskEvent = (state: "pending" | "delivered") =>
4772
+ Effect.gen(function* () {
4773
+ return {
4774
+ id: yield* idAllocator.allocate.event({ threadId: parentThreadId }),
4775
+ type: "subagent.updated",
4776
+ threadId: parentThreadId,
4777
+ nodeId: taskId,
4778
+ providerInstanceId: modelSelection.instanceId,
4779
+ occurredAt: now,
4780
+ payload: {
4781
+ id: taskId,
4782
+ threadId: parentThreadId,
4783
+ runId: parentRunId,
4784
+ parentNodeId: idAllocator.derive.rootNode({ runId: parentRunId }),
4785
+ origin: "app_owned",
4786
+ createdBy: "agent",
4787
+ driver: CODEX_DRIVER,
4788
+ providerInstanceId: modelSelection.instanceId,
4789
+ providerThreadId: null,
4790
+ childThreadId: threadId,
4791
+ nativeTaskRef: null,
4792
+ prompt: "Delegated work",
4793
+ title: null,
4794
+ model: null,
4795
+ completionDelivery: { state, observedByRunId: null },
4796
+ status: "completed",
4797
+ result: "Done.",
4798
+ startedAt: now,
4799
+ completedAt: now,
4800
+ updatedAt: now,
4801
+ },
4802
+ } satisfies OrchestrationV2DomainEvent;
4803
+ });
4804
+ if (delivery === "pending") deliverPending = yield* taskEvent("delivered");
4805
+ yield* eventSink.write({
4806
+ events: [
4807
+ {
4808
+ ...created,
4809
+ payload: { ...created.payload, forkedFrom: { type: "node", nodeId: taskId } },
4810
+ },
4811
+ yield* taskEvent(delivery),
4812
+ ],
4813
+ });
4814
+ const runtime = yield* manager.open({
4815
+ threadId,
4816
+ providerSessionId,
4817
+ modelSelection,
4818
+ runtimePolicy,
4819
+ });
4820
+ yield* runtime.startTurn({
4821
+ appThread: (yield* projectionStore.getThreadProjection(threadId)).thread,
4822
+ threadId,
4823
+ runId,
4824
+ runOrdinal: 1,
4825
+ providerTurnOrdinal: 1,
4826
+ attemptId: idAllocator.derive.runAttempt({ runId, attemptOrdinal: 1 }),
4827
+ rootNodeId: idAllocator.derive.rootNode({ runId }),
4828
+ providerThread,
4829
+ message: {
4830
+ createdBy: "agent",
4831
+ creationSource: "server",
4832
+ messageId: yield* idAllocator.allocate.message({ threadId, ordinal: 1 }),
4833
+ text: "Delegated work",
4834
+ attachments: [],
4835
+ },
4836
+ modelSelection,
4837
+ runtimePolicy,
4838
+ });
4839
+ // The pump marks the thread idle before subscribers see its terminal.
4840
+ const subscription = yield* runtime.subscribeEvents!;
4841
+ yield* Queue.offer((yield* Ref.get(state)).eventQueues.get(String(providerSessionId))!, {
4842
+ type: "turn.terminal",
4843
+ driver: CODEX_DRIVER,
4844
+ providerThreadId: providerThread.id,
4845
+ providerTurnId: idAllocator.derive.providerTurn({
4846
+ driver: CODEX_DRIVER,
4847
+ nativeTurnId: `native-turn-${delivery}`,
4848
+ }),
4849
+ runOrdinal: 1,
4850
+ status: "completed",
4851
+ failure: null,
4852
+ threadDisposition: "reusable",
4853
+ });
4854
+ yield* subscription.events.pipe(Stream.runHead);
4855
+ }
4856
+
4857
+ yield* TestClock.adjust("1 second");
4858
+ assert.equal(yield* Queue.take(unloads), "archive:native-delivered");
4859
+ if (archive !== "succeeds") {
4860
+ if (archive === "hangs") yield* TestClock.adjust("10 seconds");
4861
+ // An archive that never finished may have left the thread loaded.
4862
+ assert.equal(yield* Queue.take(unloads), "unload:native-delivered");
4863
+ return;
4864
+ }
4865
+ // The pending child stays loaded, and keeps the session open, until its parent takes the result.
4866
+ yield* eventSink.write({ events: [deliverPending!] });
4867
+ yield* TestClock.adjust("1 second");
4868
+ assert.equal(yield* Queue.take(unloads), "archive:native-pending");
4869
+ if (!keptOpen) assert.equal(yield* Queue.take(unloads), "close");
4870
+ });
4871
+
4872
+ yield* effect.pipe(
4873
+ Effect.provide(
4874
+ layerTest({
4875
+ state,
4876
+ idleTimeoutMs: 1000,
4877
+ unloads,
4878
+ ...(archive === "fails"
4879
+ ? { archive: unimplemented("archive refused") }
4880
+ : archive === "hangs"
4881
+ ? { archive: Effect.never }
4882
+ : {}),
4883
+ // Another thread's work keeps the shared session open past the children's idle unloads.
4884
+ hasPendingBackgroundWork: Effect.succeed(keptOpen),
4885
+ }),
4886
+ ),
4887
+ );
4888
+ }),
4889
+);
4890
+
4891
it.effect(
4892
"ProviderSessionManagerV2 re-attaching a thread waits for its in-flight unload, then reloads it",
4893
() =>
apps/server/src/orchestration-v2/ProviderSessionManager.ts
+78
-5
@@ -1216,11 +1216,19 @@ export const layerWithOptions = (
1216
// Capture runtime identity before yielding; replacements can reuse the session id.
1217
const probedRuntime = entry.runtime;
1218
const hasPendingWork =
1219
- probedRuntime.hasPendingBackgroundWork === undefined
1219
+ (probedRuntime.hasPendingBackgroundWork === undefined
1220
? false
1221
: yield* probedRuntime.hasPendingBackgroundWork.pipe(
1222
Effect.catchCause(() => Effect.succeed(false)),
1223
- );
1223
+ )) ||
1224
+ // Closing now would skip the archive of a child whose parent has not taken its result.
1225
+ Option.isSome(
1226
+ yield* Effect.findFirst(entry.idleThreadUnloads.keys(), (threadId) =>
1227
+ delegatedChildArchive(threadId).pipe(
1228
+ Effect.map((child) => child === "awaiting_delivery"),
1229
+ ),
1230
+ ),
1231
+ );
1232
if (hasPendingWork) {
1233
const now = yield* Clock.currentTimeMillis;
1234
const pinnedSinceMs = entry.pinnedSinceMs ?? now;
@@ -1255,6 +1263,18 @@ export const layerWithOptions = (
1263
pinnedForMs: now - pinnedSinceMs,
1264
});
1265
}
1266
+ // Closing skips the threads' own idle unloads, so archive delivered children first.
1267
+ yield* Effect.forEach(
1268
+ entry.idleThreadUnloads,
1269
+ ([threadId, pending]) =>
1270
+ unloadIdleThread({
1271
+ providerSessionId: input.providerSessionId,
1272
+ threadId,
1273
+ generation: pending.generation,
1274
+ archiveOnly: true,
1275
+ }),
1276
+ { discard: true },
1277
+ );
1278
// Adapter probes yield; guard busyTurns and idleGeneration atomically when removing the entry.
1279
yield* releaseEntry({
1280
providerSessionId: input.providerSessionId,
@@ -1672,11 +1692,44 @@ export const layerWithOptions = (
1692
},
1693
);
1694
1695
+ // Provider clients list a delegated child as an ordinary conversation, so a
1696
+ // finished one is archived once its parent has the result.
1697
+ const delegatedChildArchive = Effect.fn("ProviderSessionManager.delegatedChildArchive")(
1698
+ function* (threadId: ThreadId) {
1699
+ const { thread, runs } = yield* projectionStore.getThreadRecords(threadId, ["runs"], {
1700
+ runStatuses: [],
1701
+ includeLatestRun: true,
1702
+ });
1703
+ // Follow-up tasks name their run; the initial task is the node the child forked from.
1704
+ const taskId =
1705
+ runs.at(-1)?.delegatedTaskId ??
1706
+ (thread.forkedFrom?.type === "node" ? thread.forkedFrom.nodeId : undefined);
1707
+ const parentThreadId = thread.lineage.parentThreadId;
1708
+ if (parentThreadId === null || taskId === undefined) return undefined;
1709
+ const task = (yield* projectionStore.getThreadRecords(parentThreadId, ["subagents"], {
1710
+ subagentIds: [taskId],
1711
+ })).subagents[0];
1712
+ if (
1713
+ task?.origin !== "app_owned" ||
1714
+ task.childThreadId !== threadId ||
1715
+ task.status !== "completed"
1716
+ ) {
1717
+ return undefined;
1718
+ }
1719
+ const delivery = task.completionDelivery?.state;
1720
+ if (delivery === "pending" || delivery === "claimed") return "awaiting_delivery";
1721
+ return delivery === "delivered" || delivery === "acknowledged" ? "ready" : undefined;
1722
+ },
1723
+ (effect) => effect.pipe(Effect.orElseSucceed(() => undefined)),
1724
+ );
1725
+
1726
const unloadIdleThread = Effect.fn("ProviderSessionManager.unloadIdleThread")(
1727
function* (input: {
1728
readonly providerSessionId: ProviderSessionId;
1729
readonly threadId: ThreadId;
1730
readonly generation: number;
1731
+ /** Session release unloads only the threads it would archive, and never waits. */
1732
+ readonly archiveOnly?: boolean;
1733
}): Effect.fn.Return<void> {
1734
const outcome = yield* threadAttachment.withLock(
1735
threadAttachmentKey(input),
@@ -1703,6 +1756,11 @@ export const layerWithOptions = (
1756
.hasPendingBackgroundWorkForThread(pending.providerThread)
1757
.pipe(Effect.catchCause(() => Effect.succeed(false)));
1758
if (hasPendingWork) return "deferred" as const;
1759
+ const child = yield* delegatedChildArchive(input.threadId);
1760
+ // Unloading now would miss the archive once the parent takes the result.
1761
+ if (child === "awaiting_delivery") return "deferred" as const;
1762
+ const archive = child === "ready";
1763
+ if (input.archiveOnly === true && !archive) return "skipped" as const;
1764
const unloading = yield* Ref.modify(sessions, (current) => {
1765
const latest = current.get(key);
1766
if (
@@ -1726,8 +1784,23 @@ export const layerWithOptions = (
1784
return [true, updated] as const;
1785
});
1786
if (!unloading) return "skipped" as const;
1729
- yield* unloadThread({ providerThread: pending.providerThread }).pipe(
1730
- Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS),
1787
+ const unload = (archiveThread: boolean) =>
1788
+ unloadThread({
1789
+ providerThread: pending.providerThread,
1790
+ archive: archiveThread,
1791
+ }).pipe(Effect.timeout(UNLOAD_THREAD_TIMEOUT_MS));
1792
+ yield* unload(archive).pipe(
1793
+ // A failed or timed-out archive may have left the thread loaded.
1794
+ Effect.catch((cause) =>
1795
+ archive
1796
+ ? Effect.logWarning("orchestration-v2.driver-session.idle-archive-failed", {
1797
+ providerSessionId: input.providerSessionId,
1798
+ threadId: input.threadId,
1799
+ providerThreadId: pending.providerThread.id,
1800
+ cause,
1801
+ }).pipe(Effect.andThen(unload(false)))
1802
+ : Effect.fail(cause),
1803
+ ),
1804
Effect.tap(() =>
1805
Ref.update(sessions, (current) => {
1806
const latest = current.get(key);
@@ -1750,7 +1823,7 @@ export const layerWithOptions = (
1823
}),
1824
);
1825
// Wait outside the lock so the next attach is not blocked.
1753
- if (outcome === "deferred") {
1826
+ if (outcome === "deferred" && input.archiveOnly !== true) {
1827
yield* Effect.sleep(Duration.millis(idleTimeoutMs));
1828
return yield* unloadIdleThread(input);
1829
}
packages/provider-core/src/server/ProviderAdapter.ts
+2
@@ -734,6 +734,8 @@ export interface ProviderAdapterV2SessionRuntime {
734
}) => Effect.Effect<void | ProviderAdapterV2SubagentOutcome, ProviderAdapterV2Error>;
735
readonly unloadThread?: (input: {
736
readonly providerThread: OrchestrationV2ProviderThread;
737
+ /** Also hide it from the provider's own clients where it can; resuming it must restore it. */
738
+ readonly archive?: boolean;
739
}) => Effect.Effect<void, ProviderAdapterV2Error>;
740
readonly respondToRuntimeRequest: (
741
input: ProviderAdapterV2RuntimeRequestResponseInput,