TypeScript
fix(server): resume Codex parents after native children finish (#23840)
Julius Marminge11adcb0e25a0
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.tsindex 840205edfa6..e925c537f5c 100644--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts@@ -4907,6 +4907,335 @@ describe("CodexAdapterV2 post-settle continuation", () => {],});+ it.effect("wakes the parent when a native child finishes after the parent's turn", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const entries = resumeSubagentTranscript.entries;+ const labelIndex = (label: string) =>+ entries.findIndex((entry) => entry.type === "emit_inbound" && entry.label === label);+ const rootCompleted = labelIndex("turn/completed/root");+ const harness = yield* makeCodexReplayHarness(+ makeCodexReplayTranscript({+ scenario: RESUME_SCENARIO,+ entries: [+ ...entries.slice(0, labelIndex(`turn/started/${RESUME_CHILD_TURN_1}`) + 1),+ ...entries.slice(rootCompleted - 1, rootCompleted + 1),+ childAgentMessage({+ id: "child-late-answer",+ text: "NATIVE_CHILD_16900_DONE",+ turnId: RESUME_CHILD_TURN_1,+ completedAtMs: 1782622480000,+ afterMs: 60_000,+ }),+ childTurnCompleted(RESUME_CHILD_TURN_1),+ ],+ }),+ );++ yield* harness.runtime.startTurn(+ makeCodexTestTurnInput({+ threadId: harness.threadId,+ providerThread: harness.providerThread,+ now: yield* DateTime.now,+ attemptId: RunAttemptId.make("attempt-codex-late-child"),+ text: RESUME_PROMPT,+ }),+ );+ yield* harness.awaitTerminal(1);+ assert.equal(harness.terminalEvents()[0]?.status, "completed");+ assert.lengthOf(harness.continuationRequests, 0);++ yield* TestClock.adjust("60 seconds");+ yield* harness.until(+ () => harness.subagentUpdates().at(-1)?.subagent.result === "NATIVE_CHILD_16900_DONE",+ );+ assert.equal(harness.subagentUpdates().at(-1)?.subagent.status, "completed");+ assert.lengthOf(harness.continuationRequests, 1);+ assert.include(harness.continuationRequests[0]?.detail, "NATIVE_CHILD_16900_DONE");+ assert.equal(harness.continuationRequests[0]?.delivery, "message_text");+ }).pipe(+ Effect.provide(+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),+ ),+ ),+ ),+ );++ const lateChildPrefix = () => {+ const entries = resumeSubagentTranscript.entries;+ const labelIndex = (label: string) =>+ entries.findIndex((entry) => entry.type === "emit_inbound" && entry.label === label);+ const rootCompleted = labelIndex("turn/completed/root");+ return {+ spawned: entries.slice(0, labelIndex(`turn/started/${RESUME_CHILD_TURN_1}`) + 1),+ rootFinished: entries.slice(rootCompleted - 1, rootCompleted + 1),+ };+ };++ it.effect("names a late child spawned without a prompt in its wake", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const { spawned, rootFinished } = lateChildPrefix();+ const harness = yield* makeCodexReplayHarness(+ makeCodexReplayTranscript({+ scenario: RESUME_SCENARIO,+ entries: [+ ...spawned.map((entry) =>+ entry.type === "emit_inbound" &&+ entry.label === "item/completed/subAgentActivity-started"+ ? {+ ...entry,+ frame: {+ method: "item/completed",+ params: {+ item: {+ type: "collabAgentToolCall",+ id: "call-codex-resume-spawn",+ tool: "spawnAgent",+ status: "completed",+ senderThreadId: RESUME_NATIVE_THREAD,+ receiverThreadIds: [RESUME_CHILD_THREAD],+ agentsStates: {},+ },+ threadId: RESUME_NATIVE_THREAD,+ turnId: RESUME_NATIVE_TURN,+ completedAtMs: 1782622441000,+ },+ },+ }+ : entry,+ ),+ ...rootFinished,+ childAgentMessage({+ id: "child-late-answer",+ text: "UNPROMPTED_CHILD_DONE",+ turnId: RESUME_CHILD_TURN_1,+ completedAtMs: 1782622480000,+ afterMs: 60_000,+ }),+ childTurnCompleted(RESUME_CHILD_TURN_1),+ ],+ }),+ );++ yield* harness.runtime.startTurn(+ makeCodexTestTurnInput({+ threadId: harness.threadId,+ providerThread: harness.providerThread,+ now: yield* DateTime.now,+ attemptId: RunAttemptId.make("attempt-codex-unprompted-child"),+ text: RESUME_PROMPT,+ }),+ );+ yield* harness.awaitTerminal(1);+ yield* TestClock.adjust("60 seconds");+ yield* harness.until(() => harness.continuationRequests.length > 0);+ const subagent = harness.subagentUpdates().at(-1)?.subagent;+ assert.equal(subagent?.prompt, "");+ assert.equal(+ harness.continuationRequests[0]?.detail,+ `Subagent completed: ${subagent?.id}\n\nResult:\nUNPROMPTED_CHILD_DONE`,+ );+ }).pipe(+ Effect.provide(+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),+ ),+ ),+ ),+ );++ it.effect("wakes the root only when its direct child finishes, not a grandchild", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const grandchildThread = "native-codex-resume-grandchild-thread";+ const grandchildTurn = "native-codex-resume-grandchild-turn";+ const { spawned, rootFinished } = lateChildPrefix();+ const harness = yield* makeCodexReplayHarness(+ makeCodexReplayTranscript({+ scenario: RESUME_SCENARIO,+ entries: [+ ...spawned,+ {+ type: "emit_inbound",+ label: "item/completed/grandchild-spawn",+ frame: {+ method: "item/completed",+ params: {+ item: {+ type: "subAgentActivity",+ id: "call-codex-grandchild-spawn",+ kind: "started",+ agentThreadId: grandchildThread,+ agentPath: "/root/resume_agent/grandchild",+ },+ threadId: RESUME_CHILD_THREAD,+ turnId: RESUME_CHILD_TURN_1,+ completedAtMs: 1782622441500,+ },+ },+ },+ {+ type: "emit_inbound",+ label: "turn/started/grandchild",+ frame: {+ method: "turn/started",+ params: {+ threadId: grandchildThread,+ turn: makeCodexReplayTurn({ id: grandchildTurn, status: "inProgress" }),+ },+ },+ },+ ...rootFinished,+ {+ type: "emit_inbound",+ label: "item/completed/grandchild-answer",+ afterMs: 30_000,+ frame: {+ method: "item/completed",+ params: {+ item: {+ type: "agentMessage",+ id: "grandchild-answer",+ text: "GRANDCHILD_DONE",+ phase: "final_answer",+ memoryCitation: null,+ },+ threadId: grandchildThread,+ turnId: grandchildTurn,+ completedAtMs: 1782622470000,+ },+ },+ },+ {+ type: "emit_inbound",+ label: "turn/completed/grandchild",+ frame: {+ method: "turn/completed",+ params: {+ threadId: grandchildThread,+ turn: makeCodexReplayTurn({ id: grandchildTurn, status: "completed" }),+ },+ },+ },+ childAgentMessage({+ id: "child-late-answer",+ text: "CHILD_AFTER_GRANDCHILD",+ turnId: RESUME_CHILD_TURN_1,+ completedAtMs: 1782622500000,+ afterMs: 30_000,+ }),+ childTurnCompleted(RESUME_CHILD_TURN_1),+ ],+ }),+ );++ yield* harness.runtime.startTurn(+ makeCodexTestTurnInput({+ threadId: harness.threadId,+ providerThread: harness.providerThread,+ now: yield* DateTime.now,+ attemptId: RunAttemptId.make("attempt-codex-late-grandchild"),+ text: RESUME_PROMPT,+ }),+ );+ yield* harness.awaitTerminal(1);++ yield* TestClock.adjust("30 seconds");+ yield* harness.until(() =>+ harness.subagentUpdates().some((event) => event.subagent.result === "GRANDCHILD_DONE"),+ );+ assert.lengthOf(harness.continuationRequests, 0);++ yield* TestClock.adjust("30 seconds");+ yield* harness.until(() => harness.continuationRequests.length > 0);+ assert.lengthOf(harness.continuationRequests, 1);+ assert.include(harness.continuationRequests[0]?.detail, "CHILD_AFTER_GRANDCHILD");+ }).pipe(+ Effect.provide(+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),+ ),+ ),+ ),+ );++ it.effect("leaves a late child's result to the root's next turn when one is running", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const secondPrompt = "Wait for the sub-agent.";+ const secondTurn = "native-codex-resume-root-turn-2";+ const { spawned, rootFinished } = lateChildPrefix();+ // Reuse the preamble's turn/start exchange under the session's next request id.+ const secondTurnStart = codexReplayPreamble({+ nativeThreadId: RESUME_NATIVE_THREAD,+ nativeTurnId: secondTurn,+ prompt: secondPrompt,+ })+ .slice(-3)+ .map((entry) =>+ entry.type !== "runtime_exit" &&+ typeof entry.frame === "object" &&+ entry.frame !== null &&+ "id" in entry.frame+ ? { ...entry, frame: { ...entry.frame, id: 4 } }+ : entry,+ );+ const harness = yield* makeCodexReplayHarness(+ makeCodexReplayTranscript({+ scenario: RESUME_SCENARIO,+ entries: [+ ...spawned,+ ...rootFinished,+ ...secondTurnStart,+ childAgentMessage({+ id: "child-late-answer",+ text: "CHILD_DURING_SECOND_TURN",+ turnId: RESUME_CHILD_TURN_1,+ completedAtMs: 1782622480000,+ }),+ childTurnCompleted(RESUME_CHILD_TURN_1),+ {+ type: "emit_inbound",+ label: "turn/completed/root-2",+ frame: {+ method: "turn/completed",+ params: {+ threadId: RESUME_NATIVE_THREAD,+ turn: makeCodexReplayTurn({ id: secondTurn, status: "completed" }),+ },+ },+ },+ ],+ }),+ );++ const turnInput = (index: number, text: string) =>+ Effect.gen(function* () {+ return {+ ...makeCodexTestTurnInput({+ threadId: harness.threadId,+ providerThread: harness.providerThread,+ now: yield* DateTime.now,+ attemptId: RunAttemptId.make(`attempt-codex-active-root-${index}`),+ text,+ }),+ runOrdinal: index,+ providerTurnOrdinal: index,+ };+ });+ yield* harness.runtime.startTurn(yield* turnInput(1, RESUME_PROMPT));+ yield* harness.awaitTerminal(1);+ yield* harness.runtime.startTurn(yield* turnInput(2, secondPrompt));+ yield* harness.awaitTerminal(2);+ assert.equal(harness.subagentUpdates().at(-1)?.subagent.result, "CHILD_DURING_SECOND_TURN");+ assert.lengthOf(harness.continuationRequests, 0);+ }).pipe(+ Effect.provide(+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),+ ),+ ),+ ),+ );+it.effect.each(["model/rerouted"] as const)("keeps %s child metadata when an older lookup finishes later",(method) =>@@ -5046,7 +5375,9 @@ describe("CodexAdapterV2 post-settle continuation", () => {});assert.isFalse(yield* harness.hasPendingBackgroundWork);assert.lengthOf(harness.terminalEvents(), 1);- assert.lengthOf(harness.continuationRequests, 0);+ // The first child turn finished inside the root turn; only the resume wakes it.+ assert.lengthOf(harness.continuationRequests, 1);+ assert.include(harness.continuationRequests[0]?.detail, "CODEX_RESUME_DONE");}).pipe(Effect.provide(Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.tsindex 067551ff9a9..73d1e1f6498 100644--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts@@ -448,6 +448,18 @@ function codexBackgroundCommandDetail(item: {return outputTail.length === 0 ? header : `${header}\n\nOutput tail:\n${outputTail}`;}+// Codex spawns can omit the prompt, which registers as an empty string.+function codexNativeSubagentLabel(task: OrchestrationV2Subagent): string | undefined {+ return task.title?.trim() || task.prompt.trim() || undefined;+}++function codexNativeSubagentDetail(task: OrchestrationV2Subagent): string {+ const header = `Subagent ${task.status}: ${codexNativeSubagentLabel(task) ?? task.id}`;+ return task.result == null || task.result.length === 0+ ? header+ : `${header}\n\nResult:\n${task.result}`;+}+export interface CodexDynamicToolProjection extends McpToolPresentation {readonly toolName: string;readonly title?: string;@@ -6053,6 +6065,41 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (status: input.status,completedAt: input.completedAt,});+ // Codex does not wake a parent whose turn already completed, so+ // the child's result would sit unread until the next message.+ // Only direct children of a root turn wake it: a grandchild+ // reports to its own parent, and a root turn already running on+ // the thread receives the result natively.+ const parent = input.context.subagent.parentContext;+ if (+ continuationRequests !== undefined &&+ parent.subagent === null &&+ (input.status === "completed" || input.status === "failed") &&+ !(yield* Ref.get(terminalizedNonCompletedNativeTurns)).has(parent.nativeTurnId) &&+ ![...(yield* Ref.get(activeTurns)).values()].some(+ (active) =>+ active.subagent === null &&+ active.providerThread.id === parent.providerThread.id,+ )+ ) {+ const task = input.context.subagent.task;+ yield* continuationRequests.offer({+ threadId: parent.projectionThreadId,+ providerThreadId: parent.providerThread.id,+ driver: CODEX_PROVIDER,+ detail: codexNativeSubagentDetail(task),+ // The detail is the whole wake; Codex buffers no output for it.+ delivery: "message_text",+ notification: backgroundWorkNotification([+ {+ kind: "subagent",+ label: codexNativeSubagentLabel(task),+ outcome: input.status,+ childThreadId: input.context.subagent.childThreadId,+ },+ ]),+ });+ }}if (input.status === "interrupted" || input.status === "failed") {yield* terminalizeRunningCommandItems(