The best way to control Claude Code, Codex and more from any computer or phone
fix(server): wake threads whose subagents' background work a restart cut (#19750)
maria committed
Oct 17, 2026 at 02:12 UTC
7111501be3e25f4a4fc18ab579377cb0d0c397b1
14 files changed
+640
-32
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+27
@@ -4694,6 +4694,33 @@ describe("ClaudeAdapterV2 background wake turns", () => {
4694
WAKE_TASK_ID,
4695
);
4696
4697
+ // A subagent's own background shell keeps the subagent waiting on it.
4698
+ yield* Queue.offer(
4699
+ harness.sdkMessages,
4700
+ claudeSdkFrame({
4701
+ type: "system",
4702
+ subtype: "background_tasks_changed",
4703
+ tasks: [
4704
+ {
4705
+ task_id: "subagent-shell",
4706
+ task_type: "local_bash",
4707
+ description: "sleep 150",
4708
+ parent_task_id: "agent-1",
4709
+ },
4710
+ ],
4711
+ uuid: "00000000-0000-4000-8000-000000000203",
4712
+ session_id: WAKE_NATIVE_SESSION,
4713
+ }),
4714
+ );
4715
+ yield* awaitUntil(
4716
+ () =>
4717
+ providerThreadRosterEvents(harness.events).some(
4718
+ (event) =>
4719
+ event.providerThread.pendingBackgroundTasks?.[0]?.parentTaskId === "agent-1",
4720
+ ),
4721
+ "subagent shell roster",
4722
+ );
4723
+
4724
yield* Queue.offer(harness.sdkMessages, emptyRoster);
4725
yield* awaitUntil(
4726
() =>
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+7
@@ -2043,6 +2043,8 @@ function claudePendingBackgroundTask(input: {
2043
// that started it tells it apart from a background Bash command.
2044
readonly startedByMonitor: boolean;
2045
readonly description: string | undefined;
2046
+ // Undeclared SDK field: the subagent whose own background work this is.
2047
+ readonly parentTaskId: unknown;
2048
}): OrchestrationV2PendingBackgroundTask {
2049
return {
2050
taskId: input.taskId,
@@ -2054,6 +2056,9 @@ function claudePendingBackgroundTask(input: {
2056
...(input.description !== undefined && input.description.trim().length > 0
2057
? { description: input.description }
2058
: {}),
2059
+ ...(typeof input.parentTaskId === "string" && input.parentTaskId.trim().length > 0
2060
+ ? { parentTaskId: input.parentTaskId }
2061
+ : {}),
2062
};
2063
}
2064
@@ -2105,6 +2110,7 @@ function parseClaudeBackgroundTaskEntry(
2110
taskType,
2111
startedByMonitor: monitorTasks.has(taskId),
2112
description: typeof description === "string" ? description : undefined,
2113
+ parentTaskId: Reflect.get(entry, "parent_task_id"),
2114
});
2115
}
2116
@@ -6285,6 +6291,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
6291
}),
6292
description:
6293
typeof message.description === "string" ? message.description : undefined,
6294
+ parentTaskId: Reflect.get(message, "parent_task_id"),
6295
}),
6296
);
6297
rosterChanged = true;
apps/server/src/orchestration-v2/Orchestrator.ts
+10
-2
@@ -92,7 +92,11 @@ import {
92
import { CommandReceiptStoreV2 } from "./CommandReceiptStore.ts";
93
import { ContextHandoffServiceV2 } from "./ContextHandoffService.ts";
94
import { notificationTurnItem } from "@t3tools/provider-core/server/notification";
95
-import { isRestartContinuationSource, runOutcome } from "./RestartBackgroundNote.ts";
95
+import {
96
+ cancelledBeforeStart,
97
+ isRestartContinuationSource,
98
+ runOutcome,
99
+} from "./RestartBackgroundNote.ts";
100
import {
101
isBufferedProviderNotification,
102
isUndeliveredMailboxSteer,
@@ -4569,7 +4573,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4573
projection.thread.deletedAt !== null ||
4574
projection.thread.providerInstanceId !== source.providerInstanceId ||
4575
projection.runs.some(
4572
- (run) => run.id !== source.id && run.status !== "queued" && runRanAfter(run, source),
4576
+ (run) =>
4577
+ run.id !== source.id &&
4578
+ run.status !== "queued" &&
4579
+ !cancelledBeforeStart(run) &&
4580
+ runRanAfter(run, source),
4581
) ||
4582
(yield* stopReachedRun(command, command.threadId, source.id))
4583
) {
apps/server/src/orchestration-v2/ProjectionRecovery.test.ts
+215
@@ -723,6 +723,221 @@ it.effect("reads the run that owns a background roster, not a queued or resumed
723
}).pipe(Effect.provide(layerTest)),
724
);
725
726
+it.effect("wakes the run whose subagent lost its shell, past a wake cut before it started", () =>
727
+ Effect.gen(function* () {
728
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
729
+ const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
730
+ const sql = yield* SqlClient.SqlClient;
731
+ const now = yield* DateTime.now;
732
+ const threadId = yield* createThread("subagent-shell");
733
+ const providerThreadId = ProviderThreadId.make(`provider-thread:${threadId}`);
734
+ const providerSessionId = ProviderSessionId.make(`session:${threadId}`);
735
+ yield* projections.apply({
736
+ id: EventId.make(`event:${threadId}:session`),
737
+ type: "provider-session.attached",
738
+ threadId,
739
+ driver,
740
+ providerInstanceId,
741
+ occurredAt: now,
742
+ payload: {
743
+ id: providerSessionId,
744
+ driver,
745
+ providerInstanceId,
746
+ status: "ready",
747
+ cwd: "/workspace",
748
+ model: modelSelection.model,
749
+ capabilities: CodexProviderCapabilitiesV2,
750
+ createdAt: now,
751
+ updatedAt: now,
752
+ lastError: null,
753
+ },
754
+ });
755
+ const settledRun = yield* createRun(threadId, "completed", { providerThreadId });
756
+ yield* createRun(threadId, "starting", {
757
+ ordinal: 2,
758
+ providerThreadId,
759
+ startedAt: null,
760
+ completedAt: null,
761
+ });
762
+ yield* projections.apply({
763
+ id: EventId.make(`event:${threadId}:roster`),
764
+ type: "provider-thread.updated",
765
+ threadId,
766
+ driver,
767
+ providerInstanceId,
768
+ occurredAt: now,
769
+ payload: {
770
+ id: providerThreadId,
771
+ appThreadId: threadId,
772
+ ownerNodeId: null,
773
+ driver,
774
+ providerInstanceId,
775
+ providerSessionId,
776
+ nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
777
+ nativeConversationHeadRef: null,
778
+ status: "idle",
779
+ firstRunOrdinal: 1,
780
+ lastRunOrdinal: 2,
781
+ handoffIds: [],
782
+ forkedFrom: null,
783
+ createdAt: now,
784
+ updatedAt: now,
785
+ pendingBackgroundTasks: [
786
+ { taskId: "shell", description: "sleep 150", kind: "command", parentTaskId: "agent" },
787
+ ],
788
+ },
789
+ });
790
+
791
+ yield* recovery.reconcile("startup");
792
+
793
+ const effects = yield* sql<{ readonly effect_id: string }>`
794
+ SELECT effect_id FROM orchestration_v2_effect_outbox WHERE thread_id = ${threadId}
795
+ `;
796
+ assert.deepEqual(effects, [{ effect_id: `effect:restart-continuation:${settledRun}` }]);
797
+ const projection = yield* projections.getThreadProjection(threadId);
798
+ assert.deepEqual(projection.runs[0]?.restartCancelledBackgroundWork, [
799
+ { kind: "subagent", label: "sleep 150 (subagent agent)", id: "agent" },
800
+ ]);
801
+ }).pipe(Effect.provide(layerRecoveryTest)),
802
+);
803
+
804
+it.effect("wakes a settled run whose native subagent ran on its own provider thread", () =>
805
+ Effect.gen(function* () {
806
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
807
+ const recovery = yield* ProviderRuntimeRecovery.ProviderRuntimeRecoveryService;
808
+ const sql = yield* SqlClient.SqlClient;
809
+ const now = yield* DateTime.now;
810
+ const threadId = yield* createThread("native-subagent");
811
+ const parentProviderThreadId = ProviderThreadId.make(`provider-thread:${threadId}`);
812
+ const childProviderThreadId = ProviderThreadId.make(`provider-thread:${threadId}:child`);
813
+ const providerSessionId = ProviderSessionId.make(`session:${threadId}`);
814
+ const subagentId = NodeId.make(`node:${threadId}:subagent`);
815
+ // An older thread on the same Codex session is recovered first and stops it.
816
+ const sibling = yield* createThread("a-shared-session");
817
+ yield* createRun(sibling, "completed");
818
+ for (const boundThreadId of [sibling, threadId]) {
819
+ yield* projections.apply({
820
+ id: EventId.make(`event:${boundThreadId}:session`),
821
+ type: "provider-session.attached",
822
+ threadId: boundThreadId,
823
+ driver,
824
+ providerInstanceId,
825
+ occurredAt: now,
826
+ payload: {
827
+ id: providerSessionId,
828
+ driver,
829
+ providerInstanceId,
830
+ status: "ready",
831
+ cwd: "/workspace",
832
+ model: modelSelection.model,
833
+ capabilities: CodexProviderCapabilitiesV2,
834
+ createdAt: now,
835
+ updatedAt: now,
836
+ lastError: null,
837
+ },
838
+ });
839
+ }
840
+ const settledRun = yield* createRun(threadId, "completed", {
841
+ providerThreadId: parentProviderThreadId,
842
+ });
843
+ for (const [id, nativeId] of [
844
+ [parentProviderThreadId, "native-thread"],
845
+ [childProviderThreadId, "agent-thread"],
846
+ ] as const) {
847
+ yield* projections.apply({
848
+ id: EventId.make(`event:${id}`),
849
+ type: "provider-thread.updated",
850
+ threadId,
851
+ driver,
852
+ providerInstanceId,
853
+ occurredAt: now,
854
+ payload: {
855
+ id,
856
+ appThreadId:
857
+ id === parentProviderThreadId ? threadId : ThreadId.make(`${threadId}:child`),
858
+ ownerNodeId: null,
859
+ driver,
860
+ providerInstanceId,
861
+ providerSessionId,
862
+ nativeThreadRef: { driver, nativeId, strength: "strong" },
863
+ nativeConversationHeadRef: null,
864
+ status: "idle",
865
+ firstRunOrdinal: id === parentProviderThreadId ? 1 : null,
866
+ lastRunOrdinal: id === parentProviderThreadId ? 1 : null,
867
+ handoffIds: [],
868
+ forkedFrom: null,
869
+ createdAt: now,
870
+ updatedAt: now,
871
+ },
872
+ });
873
+ }
874
+ const subagent = {
875
+ threadId,
876
+ runId: settledRun,
877
+ origin: "provider_native",
878
+ driver,
879
+ providerInstanceId,
880
+ childThreadId: null,
881
+ prompt: "audit src",
882
+ status: "running",
883
+ result: null,
884
+ startedAt: now,
885
+ completedAt: null,
886
+ updatedAt: now,
887
+ } as const;
888
+ yield* projections.apply({
889
+ id: EventId.make(`event:${threadId}:subagent`),
890
+ type: "subagent.updated",
891
+ threadId,
892
+ occurredAt: now,
893
+ payload: {
894
+ ...subagent,
895
+ id: subagentId,
896
+ parentNodeId: NodeId.make(`node:${threadId}:root`),
897
+ createdBy: "agent",
898
+ providerThreadId: childProviderThreadId,
899
+ nativeTaskRef: { driver, nativeId: "call_1:agent-thread", strength: "strong" },
900
+ title: null,
901
+ model: null,
902
+ },
903
+ });
904
+ yield* projections.apply({
905
+ id: EventId.make(`event:${threadId}:subagent-item`),
906
+ type: "turn-item.updated",
907
+ threadId,
908
+ occurredAt: now,
909
+ payload: {
910
+ ...subagent,
911
+ id: TurnItemId.make(`item:${threadId}:subagent`),
912
+ nodeId: subagentId,
913
+ providerThreadId: childProviderThreadId,
914
+ providerTurnId: null,
915
+ nativeItemRef: { driver, nativeId: "call_1:agent-thread", strength: "strong" },
916
+ parentItemId: null,
917
+ ordinal: 1,
918
+ type: "subagent",
919
+ title: "audit",
920
+ subagentId,
921
+ },
922
+ });
923
+
924
+ yield* recovery.reconcile("startup");
925
+
926
+ const effects = yield* sql<{ readonly effect_id: string }>`
927
+ SELECT effect_id FROM orchestration_v2_effect_outbox WHERE thread_id = ${threadId}
928
+ `;
929
+ assert.deepEqual(effects, [{ effect_id: `effect:restart-continuation:${settledRun}` }]);
930
+ const projection = yield* projections.getThreadProjection(threadId);
931
+ assert.deepEqual(projection.runs[0]?.restartCancelledBackgroundWork, [
932
+ {
933
+ kind: "subagent",
934
+ label: "audit (id agent-thread)",
935
+ id: TurnItemId.make(`item:${threadId}:subagent`),
936
+ },
937
+ ]);
938
+ }).pipe(Effect.provide(layerRecoveryTest)),
939
+);
940
+
941
it.effect("marks fork descendants unreadable when their source is missing or corrupt", () =>
942
Effect.gen(function* () {
943
const projections = yield* ProjectionStore.ProjectionStoreV2;
apps/server/src/orchestration-v2/ProjectionStore.ts
+14
@@ -4103,6 +4103,11 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4103
WHERE ended.thread_id = ${threadId}
4104
AND ended.provider_thread_id = roster.provider_thread_id
4105
AND ended.status NOT IN ('queued', 'rolled_back')
4106
+ -- A run that never started (see neverStarted) owns no work.
4107
+ AND NOT (
4108
+ json_type(ended.payload_json, '$.startedAt') = 'null'
4109
+ AND json_type(ended.payload_json, '$.restartContinuationOfRunId') IS NULL
4110
+ )
4111
ORDER BY ended.completed_at IS NULL DESC, ended.completed_at DESC,
4112
ended.ordinal DESC
4113
LIMIT 1
@@ -4252,6 +4257,15 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
4257
WHERE item.thread_id = ${threadId}
4258
AND item.status IN ('pending', 'running', 'waiting')
4259
)
4260
+ -- A native subagent's item names its own provider thread; the
4261
+ -- run that waits on it (see awaitingProviderThreadId) is woken.
4262
+ OR provider_thread.provider_thread_id IN (
4263
+ SELECT run.provider_thread_id
4264
+ FROM orchestration_v2_projection_turn_items AS item
4265
+ JOIN orchestration_v2_projection_runs AS run ON run.run_id = item.run_id
4266
+ WHERE item.thread_id = ${threadId}
4267
+ AND item.status IN ('pending', 'running', 'waiting')
4268
+ )
4269
)
4270
ORDER BY COALESCE(provider_thread.first_run_ordinal, 0), provider_thread.provider_thread_id ASC
4271
`,
apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts
+59
-9
@@ -29,9 +29,11 @@ import {
29
endRunlessRootTurns,
30
} from "@t3tools/provider-core/server/subagentProjection";
31
import {
32
+ awaitingProviderThreadId,
33
cancelledRosterTaskWork,
34
cancelledTurnItemWork,
35
mergeRestartCancelledBackgroundWork,
36
+ neverStarted,
37
} from "./RestartBackgroundNote.ts";
38
39
export class ProviderRuntimeRecoveryError extends Schema.TaggedError<ProviderRuntimeRecoveryError>()(
@@ -158,6 +160,7 @@ function latestStartedRun(
160
run.providerThreadId === providerThreadId &&
161
run.status !== "queued" &&
162
run.status !== "rolled_back" &&
163
+ !neverStarted(run) &&
164
(latest === undefined || runRanAfter(run, latest))
165
? run
166
: latest,
@@ -171,11 +174,33 @@ export const make = Effect.gen(function* () {
174
const eventSink = yield* EventSink.EventSinkV2;
175
const ids = yield* IdAllocator.IdAllocatorV2;
176
const outbox = yield* EffectOutbox.EffectOutboxV2;
177
+ type RecoverySession = ProjectionStore.ProjectionRuntimeRecoveryState["providerSessions"][number];
178
+ /**
179
+ * A session shared by several threads (one Codex app server) is stopped by the
180
+ * first thread recovery reaches. It was live when the server went down, so a
181
+ * later thread still decides its wake as if it were.
182
+ */
183
+ const sessionsLiveAtStart = (
184
+ projection: ProjectionStore.ProjectionRuntimeRecoveryState,
185
+ stoppedThisPass: ReadonlyMap<string, RecoverySession>,
186
+ ) => {
187
+ const sessions = new Map(projection.providerSessions.map((session) => [session.id, session]));
188
+ for (const providerThread of projection.providerThreads) {
189
+ const stopped =
190
+ providerThread.providerSessionId === null
191
+ ? undefined
192
+ : stoppedThisPass.get(providerThread.providerSessionId);
193
+ if (stopped !== undefined) sessions.set(stopped.id, stopped);
194
+ }
195
+ return [...sessions.values()];
196
+ };
197
+
198
const reconcileProjection = Effect.fn("ProviderRuntimeRecoveryService.reconcileProjection")(
199
function* (
200
projection: ProjectionStore.ProjectionRuntimeRecoveryState,
201
trigger: "startup" | "shutdown",
202
continueAfterRestart: boolean,
203
+ stoppedThisPass: ReadonlyMap<string, RecoverySession> = new Map(),
204
) {
205
const now = yield* DateTime.now;
206
const runs = [] as Array<OrchestrationV2ThreadProjection["runs"][number]>;
@@ -255,13 +280,19 @@ export const make = Effect.gen(function* () {
280
item: OrchestrationV2ThreadProjection["turnItems"][number],
281
) => {
282
if (!isBackgroundCapableTurnItemType(item.type)) return;
258
- const work = cancelledTurnItemWork(item);
259
- if (work === undefined) return;
260
- recordCancelledBackgroundWork(
261
- item.providerThreadId ??
262
- projection.runs.find((run) => run.id === item.runId)?.providerThreadId,
263
- work,
283
+ const awaitingId = awaitingProviderThreadId(item, projection.runs);
284
+ const ownProviderThread =
285
+ item.providerThreadId === awaitingId
286
+ ? undefined
287
+ : (projection.providerThreads ?? []).find(
288
+ (candidate) => candidate.id === item.providerThreadId,
289
+ );
290
+ const work = cancelledTurnItemWork(
291
+ item,
292
+ ownProviderThread?.nativeThreadRef?.nativeId ?? undefined,
293
);
294
+ if (work === undefined) return;
295
+ recordCancelledBackgroundWork(awaitingId, work);
296
if (item.nativeItemRef?.nativeId != null) {
297
cancelledBackgroundNativeIds.add(item.nativeItemRef.nativeId);
298
}
@@ -409,7 +440,11 @@ export const make = Effect.gen(function* () {
440
candidate.status === "running" ||
441
candidate.status === "waiting"),
442
)) {
443
+ // A native subagent does not come back when its cut turn resumes, so the
444
+ // turn's continuation is told to restart it.
445
if (run.status === "waiting") recordCancelledBackgroundItem(item);
446
+ else if (item.type === "subagent" && item.origin === "provider_native")
447
+ recordCancelledBackgroundItem(item);
448
events.push({
449
id: yield* allocateEventId(),
450
type: "turn-item.updated",
@@ -526,7 +561,13 @@ export const make = Effect.gen(function* () {
561
}
562
if (providerThread.ownerNodeId === null) {
563
for (const task of providerThread.pendingBackgroundTasks ?? []) {
529
- if (cancelledBackgroundNativeIds.has(task.taskId)) continue;
564
+ // A subagent already recorded covers the shells it started.
565
+ if (
566
+ cancelledBackgroundNativeIds.has(task.taskId) ||
567
+ (task.parentTaskId !== undefined &&
568
+ cancelledBackgroundNativeIds.has(task.parentTaskId))
569
+ )
570
+ continue;
571
cancelledBackgroundNativeIds.add(task.taskId);
572
recordCancelledBackgroundWork(providerThread.id, cancelledRosterTaskWork(task));
573
}
@@ -582,7 +623,10 @@ export const make = Effect.gen(function* () {
623
}
624
const continuationRun =
625
continueAfterRestart && trigger === "startup"
585
- ? restartContinuationRun(projection, now)
626
+ ? restartContinuationRun(
627
+ { ...projection, providerSessions: sessionsLiveAtStart(projection, stoppedThisPass) },
628
+ now,
629
+ )
630
: undefined;
631
const effects: Array<EffectOutbox.PendingOrchestrationEffectV2> = continuationRun
632
? [
@@ -668,6 +712,7 @@ export const make = Effect.gen(function* () {
712
let stoppedSessions = 0;
713
let closedRequests = 0;
714
let retiredEffects = 0;
715
+ const stoppedThisPass = new Map<string, RecoverySession>();
716
for (const threadId of threadIds) {
717
const projection = yield* projections.getRuntimeRecoveryProjection(threadId).pipe(
718
Effect.mapError(
@@ -683,7 +728,12 @@ export const make = Effect.gen(function* () {
728
continueAfterRestart !== null &&
729
resolveProjectSettings(continueAfterRestart, projection.thread.projectId).settings
730
.continueThreadsAfterServerUpdate;
686
- const result = yield* reconcileProjection(projection, trigger, enabled);
731
+ const result = yield* reconcileProjection(projection, trigger, enabled, stoppedThisPass);
732
+ for (const session of projection.providerSessions) {
733
+ if (session.status !== "stopped" && session.status !== "error") {
734
+ stoppedThisPass.set(session.id, session);
735
+ }
736
+ }
737
terminalizedRuns += result.terminalizedRuns;
738
stoppedSessions += result.stoppedSessions;
739
closedRequests += result.closedRequests;
apps/server/src/orchestration-v2/RestartBackgroundNote.test.ts
+42
@@ -11,6 +11,7 @@ import * as DateTime from "effect/DateTime";
11
import {
12
cancelledRosterTaskWork,
13
cancelledTurnItemWork,
14
+ isAwaitedWork,
15
isRestartNoteContinuation,
16
pendingRestartCancelledBackgroundWork,
17
restartCancelledBackgroundWorkNote,
@@ -113,6 +114,47 @@ it("bounds roster task labels including a long task id", () => {
114
assert.lengthOf(idOnly.label, 160);
115
});
116
117
+it("names a lost subagent by the id the agent resumes it with", () => {
118
+ const ownShell = cancelledRosterTaskWork({
119
+ kind: "command",
120
+ taskId: "shell-1",
121
+ description: "sleep 150",
122
+ parentTaskId: "agent-1",
123
+ });
124
+ // The agent waits on the subagent, which waits on its shell.
125
+ assert.deepEqual(ownShell, {
126
+ kind: "subagent",
127
+ label: "sleep 150 (subagent agent-1)",
128
+ id: "agent-1",
129
+ });
130
+ assert.isTrue(isAwaitedWork(ownShell));
131
+ const long = cancelledRosterTaskWork({
132
+ kind: "command",
133
+ taskId: "shell-1",
134
+ description: "d".repeat(400),
135
+ parentTaskId: "agent-1",
136
+ }).label;
137
+ assert.lengthOf(long, 160);
138
+ assert.isTrue(long.endsWith("(subagent agent-1)"));
139
+ const longId = cancelledRosterTaskWork({
140
+ kind: "command",
141
+ taskId: "shell-1",
142
+ parentTaskId: "a".repeat(400),
143
+ }).label;
144
+ assert.lengthOf(longId, 160);
145
+ assert.isFalse(isAwaitedWork(cancelledRosterTaskWork({ kind: "command", taskId: "shell-2" })));
146
+ assert.equal(
147
+ cancelledTurnItemWork({
148
+ id: "item-1",
149
+ type: "subagent",
150
+ origin: "provider_native",
151
+ title: "Review",
152
+ nativeItemRef: { driver: "claudeAgent", nativeId: "agent-1", strength: "strong" },
153
+ } as never)?.label,
154
+ "Review (id agent-1)",
155
+ );
156
+});
157
+
158
it("keeps separate cancelled tasks that share a kind and label", () => {
159
const first = { kind: "shell" as const, label: "sleep 20", id: "item-1" };
160
const second = { kind: "shell" as const, label: "sleep 20", id: "item-2" };
apps/server/src/orchestration-v2/RestartBackgroundNote.ts
+69
-6
@@ -13,21 +13,42 @@ type Attempt = Pick<OrchestrationV2RunAttempt, "id" | "runId">;
13
14
const MAX_LABEL_LENGTH = 160;
15
16
-function compactLabel(value: unknown): string | undefined {
16
+function compactLabel(value: unknown, maxLength = MAX_LABEL_LENGTH): string | undefined {
17
if (typeof value !== "string") return undefined;
18
const text = value.replaceAll(/\s+/g, " ").trim();
19
if (text.length === 0) return undefined;
20
- return text.length > MAX_LABEL_LENGTH ? `${text.slice(0, MAX_LABEL_LENGTH - 1)}…` : text;
20
+ return text.length > maxLength ? `${text.slice(0, maxLength - 1)}…` : text;
21
}
22
23
-export function cancelledTurnItemWork(item: OrchestrationV2TurnItem): Work | undefined {
23
+/** A bounded label that keeps its id suffix whole whenever it fits. */
24
+function labelWithId(name: unknown, fallback: string, suffix: string): string {
25
+ const budget = MAX_LABEL_LENGTH - suffix.length;
26
+ if (budget < 2) return compactLabel(`${fallback}${suffix}`) ?? fallback;
27
+ return `${compactLabel(name, budget) ?? compactLabel(fallback, budget)}${suffix}`;
28
+}
29
+
30
+/**
31
+ * `resumeId` is what the agent resumes a native subagent by, when that is not its
32
+ * item's native id (a Codex subagent resumes by its own provider thread's id).
33
+ */
34
+export function cancelledTurnItemWork(
35
+ item: OrchestrationV2TurnItem,
36
+ resumeId?: string,
37
+): Work | undefined {
38
switch (item.type) {
25
- case "subagent":
39
+ case "subagent": {
40
+ const nativeId =
41
+ item.origin === "provider_native" ? (resumeId ?? item.nativeItemRef?.nativeId) : undefined;
42
return {
43
kind: "subagent",
28
- label: compactLabel(item.title) ?? compactLabel(item.prompt) ?? "subagent",
44
+ label: labelWithId(
45
+ compactLabel(item.title) === undefined ? item.prompt : item.title,
46
+ "subagent",
47
+ nativeId === undefined ? "" : ` (id ${nativeId})`,
48
+ ),
49
id: item.id,
50
};
51
+ }
52
case "command_execution":
53
return {
54
kind: "shell",
@@ -50,6 +71,20 @@ export function cancelledTurnItemWork(item: OrchestrationV2TurnItem): Work | und
71
}
72
}
73
74
+/**
75
+ * The provider thread waiting on an item's work. A native subagent can run on
76
+ * its own child provider thread (Codex), but the turn that started it awaits it.
77
+ */
78
+export function awaitingProviderThreadId(
79
+ item: OrchestrationV2TurnItem,
80
+ runs: ReadonlyArray<Pick<OrchestrationV2Run, "id" | "providerThreadId">>,
81
+): OrchestrationV2Run["providerThreadId"] | undefined {
82
+ const runProviderThreadId = runs.find((run) => run.id === item.runId)?.providerThreadId;
83
+ return item.type === "subagent" && item.origin === "provider_native"
84
+ ? (runProviderThreadId ?? item.providerThreadId)
85
+ : (item.providerThreadId ?? runProviderThreadId);
86
+}
87
+
88
function restartWorkKind(task: OrchestrationV2PendingBackgroundTask): Work["kind"] {
89
switch (task.kind) {
90
case "command":
@@ -67,6 +102,13 @@ function restartWorkKind(task: OrchestrationV2PendingBackgroundTask): Work["kind
102
}
103
104
export function cancelledRosterTaskWork(task: OrchestrationV2PendingBackgroundTask): Work {
105
+ if (task.parentTaskId !== undefined) {
106
+ return {
107
+ kind: "subagent",
108
+ label: labelWithId(task.description, "background task", ` (subagent ${task.parentTaskId})`),
109
+ id: task.parentTaskId,
110
+ };
111
+ }
112
const kind = restartWorkKind(task);
113
const description = compactLabel(task.description);
114
return {
@@ -87,7 +129,7 @@ const MAX_NOTE_ENTRIES = 10;
129
export function restartCancelledBackgroundWorkNote(work: ReadonlyArray<Work>): string {
130
const omitted = work.length - MAX_NOTE_ENTRIES;
131
return [
90
- "Note: the T3 server restarted, and this background work was cancelled before it finished. It will not report back:",
132
+ "Note: the T3 server restarted, and this background work was cancelled before it finished. It will not report back on its own, so resume or restart what you still need and wait for its result:",
133
...work.slice(0, MAX_NOTE_ENTRIES).map((entry) => `- ${entry.kind}: ${entry.label}`),
134
...(omitted > 0 ? [`- and ${omitted} more`] : []),
135
].join("\n");
@@ -132,6 +174,27 @@ export function runOutcome(
174
: run.status;
175
}
176
177
+/**
178
+ * A run that never reached its provider, such as a provider wake the restart
179
+ * cut while it was starting: it lost no work and has no turn to continue. A
180
+ * prepared restart continuation still counts, since it carries its source.
181
+ */
182
+export function neverStarted(
183
+ run: Pick<OrchestrationV2Run, "startedAt" | "restartContinuationOfRunId">,
184
+): boolean {
185
+ return run.startedAt === null && run.restartContinuationOfRunId === undefined;
186
+}
187
+
188
+/**
189
+ * A run the restart cancelled before it started, so it supersedes nothing. A
190
+ * run the user stopped before it started still does.
191
+ */
192
+export function cancelledBeforeStart(
193
+ run: Pick<OrchestrationV2Run, "status" | "startedAt" | "restartContinuationOfRunId">,
194
+): boolean {
195
+ return run.status === "cancelled" && neverStarted(run);
196
+}
197
+
198
export function isRestartContinuationSource(
199
source: Pick<OrchestrationV2Run, "status" | "activeAttemptId" | "restartCancelledBackgroundWork">,
200
providerTurns: ReadonlyArray<Pick<ProviderTurnState, "runAttemptId" | "status">>,
apps/server/src/orchestration-v2/RestartContinuation.test.ts
+153
@@ -415,6 +415,86 @@ it.effect("lets a cut blocking delegate_task wake its parent like an async task"
415
}),
416
);
417
418
+it.effect.each(["running", "waiting"])(
419
+ "wakes a %s run to restart the native subagent it waited on",
420
+ (status) =>
421
+ Effect.gen(function* () {
422
+ const base = makeProjection();
423
+ const item = (id: string, extra: Record<string, unknown>) => ({
424
+ id,
425
+ threadId,
426
+ runId,
427
+ nodeId: null,
428
+ status: "running",
429
+ ...extra,
430
+ });
431
+ const projection = {
432
+ ...base,
433
+ runs: [{ ...base.runs[0]!, status }],
434
+ providerTurns: [
435
+ { ...base.providerTurns[0]!, status: status === "waiting" ? "completed" : "running" },
436
+ ],
437
+ turnItems: [
438
+ // Codex keeps a native subagent on its own child provider thread.
439
+ item("item:native", {
440
+ type: "subagent",
441
+ origin: "provider_native",
442
+ providerThreadId: ProviderThreadId.make("provider-thread:child"),
443
+ nativeItemRef: { driver, nativeId: "agent-1" },
444
+ title: "Sleeper",
445
+ childThreadId: ThreadId.make("thread:child"),
446
+ }),
447
+ item("item:shell", { type: "command_execution", providerThreadId, input: "ls" }),
448
+ ],
449
+ } as unknown as OrchestrationV2ThreadProjection;
450
+ let committed: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | undefined;
451
+ const recovery = yield* ProviderRuntimeRecovery.make.pipe(
452
+ Effect.provide(
453
+ Layer.mergeAll(
454
+ ServerSettings.layerTest({ continueThreadsAfterServerUpdate: true }),
455
+ Layer.mock(ProjectionStore.ProjectionStoreV2)({
456
+ getRecoveryThreadIds: () => Effect.succeed([threadId]),
457
+ getRuntimeRecoveryProjection: () => Effect.succeed(projection),
458
+ }),
459
+ Layer.mock(EventSink.EventSinkV2)({
460
+ commitCommand: (input) => {
461
+ committed = input;
462
+ return Effect.succeed({ committed: true, cancelledEffectCount: 0 } as never);
463
+ },
464
+ }),
465
+ IdAllocator.layer,
466
+ Layer.mock(EffectWorker.OrchestrationEffectWorkerV2)({}),
467
+ Layer.mock(EffectOutbox.EffectOutboxV2)({
468
+ listByCommandId: () => Effect.succeed([]),
469
+ reconcileAfterProcessLoss: Effect.succeed({ requeued: 0, cancelled: 0 }),
470
+ }),
471
+ ),
472
+ ),
473
+ );
474
+ yield* recovery.reconcile("startup");
475
+ const work = (committed?.events ?? []).flatMap((event) =>
476
+ event.type === "run.background-work-cancelled" ? [event.payload] : [],
477
+ );
478
+ // The subagent is reported on the run that awaited it. A running run's
479
+ // shell died with its turn.
480
+ assert.deepEqual(work, [
481
+ {
482
+ runId,
483
+ restartCancelledBackgroundWork: [
484
+ { kind: "subagent", label: "Sleeper (id agent-1)", id: "item:native" },
485
+ ...(status === "waiting"
486
+ ? [{ kind: "shell" as const, label: "ls", id: "item:shell" }]
487
+ : []),
488
+ ],
489
+ },
490
+ ]);
491
+ assert.deepEqual(
492
+ committed?.effects.map((effect) => effect.request),
493
+ [{ type: "provider-runtime.continue", sourceRunId: runId }],
494
+ );
495
+ }),
496
+);
497
+
498
it.effect("does not duplicate delivery and yields to newer user work or opt-out", () =>
499
Effect.gen(function* () {
500
let projection = makeProjection();
@@ -693,6 +773,79 @@ it("does not wake a settled run for work left by a session that already stopped"
773
);
774
});
775
776
+it.effect("wakes a run whose subagent's own shell the restart cut, past a wake it cut first", () =>
777
+ Effect.gen(function* () {
778
+ const base = makeProjection();
779
+ const cutWake = {
780
+ ...base.runs[0]!,
781
+ id: RunId.make("run:wake"),
782
+ ordinal: 2,
783
+ status: "starting",
784
+ startedAt: null,
785
+ };
786
+ const withShell = (parentTaskId?: string) =>
787
+ ({
788
+ ...base,
789
+ runs: [{ ...base.runs[0]!, status: "waiting", startedAt: now }, cutWake],
790
+ providerThreads: [
791
+ {
792
+ ...base.providerThreads[0]!,
793
+ status: "idle",
794
+ pendingBackgroundTasks: [
795
+ {
796
+ kind: "command",
797
+ taskId: "shell:1",
798
+ description: "sleep 150",
799
+ ...(parentTaskId === undefined ? {} : { parentTaskId }),
800
+ },
801
+ ],
802
+ },
803
+ ],
804
+ providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
805
+ }) as unknown as OrchestrationV2ThreadProjection;
806
+ assert.equal(restartContinuationRun(withShell("agent:1"), now)?.id, runId);
807
+ // A shell the agent started itself still does not wake it.
808
+ assert.isUndefined(restartContinuationRun(withShell(), now));
809
+
810
+ const texts = yield* continuationTexts({
811
+ ...base,
812
+ runs: [
813
+ {
814
+ ...base.runs[0]!,
815
+ status: "completed",
816
+ startedAt: now,
817
+ completedAt: now,
818
+ restartCancelledBackgroundWork: [
819
+ { kind: "subagent", label: "sleep 150 (subagent agent:1)", id: "agent:1" },
820
+ ],
821
+ },
822
+ { ...cutWake, status: "cancelled", completedAt: now },
823
+ ],
824
+ providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
825
+ } as unknown as OrchestrationV2ThreadProjection);
826
+ assert.lengthOf(texts, 1);
827
+ assert.include(texts[0], "- subagent: sleep 150 (subagent agent:1)");
828
+ // A run the user stopped before it started still takes precedence.
829
+ const stopped = yield* continuationTexts({
830
+ ...base,
831
+ runs: [
832
+ {
833
+ ...base.runs[0]!,
834
+ status: "completed",
835
+ startedAt: now,
836
+ completedAt: now,
837
+ restartCancelledBackgroundWork: [
838
+ { kind: "subagent", label: "sleep 150 (subagent agent:1)", id: "agent:1" },
839
+ ],
840
+ },
841
+ { ...cutWake, status: "interrupted", completedAt: now },
842
+ ],
843
+ providerTurns: [{ ...base.providerTurns[0]!, status: "completed" }],
844
+ } as unknown as OrchestrationV2ThreadProjection);
845
+ assert.lengthOf(stopped, 0);
846
+ }),
847
+);
848
+
849
it.effect("does not cancel or resume a run that completes while shutdown intent commits", () =>
850
Effect.gen(function* () {
851
let projection = makeProjection();
apps/server/src/orchestration-v2/RestartContinuation.ts
+16
-6
@@ -16,11 +16,14 @@ import * as ServerSettings from "../serverSettings.ts";
16
import { isNativeMaintenanceCommand } from "./CommandPolicy.ts";
17
import * as ThreadManagementService from "./ThreadManagementService.ts";
18
import {
19
+ awaitingProviderThreadId,
20
cancelledRosterTaskWork,
21
cancelledTurnItemWork,
22
isAwaitedWork,
23
isRestartContinuationSource,
24
+ cancelledBeforeStart,
25
isRestartNoteSource,
26
+ neverStarted,
27
restartCancelledBackgroundWorkNote,
28
restartContinuationNote,
29
} from "./RestartBackgroundNote.ts";
@@ -91,10 +94,11 @@ function hasOpenAwaitedWork(
94
if (item.type === "subagent" && item.origin === "app_owned" && item.childThreadId !== null)
95
return false;
96
const work = cancelledTurnItemWork(item);
94
- const providerThreadId =
95
- item.providerThreadId ??
96
- projection.runs.find((run) => run.id === item.runId)?.providerThreadId;
97
- return work !== undefined && isAwaitedWork(work) && providerThreadId === providerThread.id;
97
+ return (
98
+ work !== undefined &&
99
+ isAwaitedWork(work) &&
100
+ awaitingProviderThreadId(item, projection.runs) === providerThread.id
101
+ );
102
});
103
return (
104
openItem ||
@@ -124,7 +128,9 @@ export function restartContinuationRun(
128
): OrchestrationV2Run | undefined {
129
const run = projection.runs.reduce<OrchestrationV2Run | undefined>(
130
(latest, candidate) =>
127
- candidate.status !== "queued" && (!latest || runRanAfter(candidate, latest))
131
+ candidate.status !== "queued" &&
132
+ !neverStarted(candidate) &&
133
+ (!latest || runRanAfter(candidate, latest))
134
? candidate
135
: latest,
136
undefined,
@@ -211,7 +217,11 @@ export const continueRestartedRun = Effect.fn("RestartContinuation.continueResta
217
return;
218
if (
219
projection.runs.some(
214
- (run) => run.id !== source.id && run.status !== "queued" && runRanAfter(run, source),
220
+ (run) =>
221
+ run.id !== source.id &&
222
+ run.status !== "queued" &&
223
+ !cancelledBeforeStart(run) &&
224
+ runRanAfter(run, source),
225
)
226
)
227
return;
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+20
-4
@@ -3161,6 +3161,22 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
3161
occurredAt: now,
3162
payload: { ...original, status: "cancelled", completedAt: now },
3163
},
3164
+ // A provider wake the restart cut before it started does not supersede it.
3165
+ {
3166
+ id: EventId.make("restart-cut-wake-event"),
3167
+ type: "run.created",
3168
+ threadId,
3169
+ runId: RunId.make("restart-cut-wake"),
3170
+ occurredAt: now,
3171
+ payload: {
3172
+ ...original,
3173
+ id: RunId.make("restart-cut-wake"),
3174
+ ordinal: 2,
3175
+ status: "cancelled",
3176
+ startedAt: null,
3177
+ completedAt: now,
3178
+ },
3179
+ },
3180
],
3181
effects: [],
3182
});
@@ -3186,10 +3202,10 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
3202
yield* orchestrator.dispatch(command);
3203
yield* orchestrator.dispatch(command);
3204
const admitted = yield* orchestrator.getThreadProjection(threadId);
3189
- assert.lengthOf(admitted.runs, 2);
3190
- assert.equal(admitted.runs[1]?.restartContinuationOfRunId, original.id);
3205
+ assert.lengthOf(admitted.runs, 3);
3206
+ assert.equal(admitted.runs[2]?.restartContinuationOfRunId, original.id);
3207
const continuationItems = admitted.turnItems.filter(
3192
- (item) => item.runId === admitted.runs[1]?.id,
3208
+ (item) => item.runId === admitted.runs[2]?.id,
3209
);
3210
assert.isFalse(continuationItems.some((item) => item.type === "user_message"));
3211
assert.deepInclude(
@@ -3204,7 +3220,7 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
3220
messageId: MessageId.make("restart-stale-race"),
3221
});
3222
const raced = yield* orchestrator.getThreadProjection(threadId);
3207
- assert.lengthOf(raced.runs, 2);
3223
+ assert.lengthOf(raced.runs, 3);
3224
assert.isFalse(raced.messages.some((message) => message.id === "restart-stale-race"));
3225
}),
3226
);
apps/server/src/orchestration-v2/testkit/OrchestratorReplayRecovery.integration.test.ts
+2
-2
@@ -130,8 +130,8 @@ const readClaudeCancelledSubagentResumeTranscript = Effect.fn(
130
message: {
131
...frame.message.message,
132
content: [
133
- "Note: the T3 server restarted, and this background work was cancelled before it finished. It will not report back:",
134
- "- subagent: Audit src/math.ts",
133
+ "Note: the T3 server restarted, and this background work was cancelled before it finished. It will not report back on its own, so resume or restart what you still need and wait for its result:",
134
+ "- subagent: Audit src/math.ts (id a44c0ed810da9e4f3)",
135
"",
136
"User message:",
137
frame.message.message.content,
apps/server/src/orchestration-v2/testkit/OrchestratorReplayRestartBackgroundNote.integration.test.ts
+2
-2
@@ -31,8 +31,8 @@ const SESSION_ID = "cca274e4-25ae-4171-b972-bbb31118517e";
31
const FIRST_AFTER_RESTART = "Is the background subagent done yet?";
32
const SECOND_AFTER_RESTART = "Thanks. Anything else?";
33
const NOTE = [
34
- "Note: the T3 server restarted, and this background work was cancelled before it finished. It will not report back:",
35
- "- subagent: Background subagent test",
34
+ "Note: the T3 server restarted, and this background work was cancelled before it finished. It will not report back on its own, so resume or restart what you still need and wait for its result:",
35
+ "- subagent: Background subagent test (id a2995bfced8019363)",
36
].join("\n");
37
38
const readRestartTranscript = Effect.fn("readRestartTranscript")(function* (
packages/contracts/src/orchestrationV2.ts
+4
-1
@@ -799,6 +799,8 @@ function kindUnionWithFallback<
799
const PendingBackgroundTaskFields = {
800
taskId: TrimmedNonEmptyString,
801
description: Schema.optional(TrimmedNonEmptyString),
802
+ /** The subagent task that started this work and waits on it. */
803
+ parentTaskId: Schema.optional(TrimmedNonEmptyString),
804
};
805
806
export const OrchestrationV2PendingBackgroundTask = kindUnionWithFallback(
@@ -815,9 +817,10 @@ export const OrchestrationV2PendingBackgroundTask = kindUnionWithFallback(
817
Schema.Struct({ ...PendingBackgroundTaskFields, kind: Schema.Literal("background_task") }),
818
],
819
(kind) => Schema.Struct({ ...PendingBackgroundTaskFields, kind }),
818
- ({ taskId, description }) => ({
820
+ ({ taskId, description, parentTaskId }) => ({
821
taskId,
822
...(description === undefined ? {} : { description }),
823
+ ...(parentTaskId === undefined ? {} : { parentTaskId }),
824
kind: "background_task",
825
}),
826
);