TypeScript
fix(server): a failed Codex turn no longer traps the queue behind its subagents (#21366)
Julius Marminge07d38b8d1716
diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.tsindex 661f735e6c1..cf327f13b30 100644--- a/apps/mobile/src/lib/threadActivity.test.ts+++ b/apps/mobile/src/lib/threadActivity.test.ts@@ -1314,6 +1314,20 @@ describe("buildThreadFeed", () => {).toEqual([{ type: "thinking", id: "live-activity-row", createdAt: startedAt, runId }]);});+ it("does not show Thinking once the open run's provider turn has ended", () => {+ const startedAt = "2026-04-01T00:00:01.000Z";+ const run = { runId, status: "running" as const, startedAt, completedAt: null };+ expect(+ deriveThreadFeedPresentation(+ [],+ { ...run, turnEnded: true },+ new Set(),+ new Set(),+ startedAt,+ ),+ ).toEqual([]);+ });+it("uses a stable Thinking row while work has started without a projected item", () => {const startedAt = "2026-04-01T00:00:01.000Z";const presented = deriveThreadFeedPresentation([], null, new Set(), new Set(), startedAt);diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.tsindex 8b7ac4aa469..631c2639357 100644--- a/apps/mobile/src/lib/threadActivity.ts+++ b/apps/mobile/src/lib/threadActivity.ts@@ -240,6 +240,7 @@ export interface ThreadFeedLatestRun {readonly status: OrchestrationV2RunStatus;readonly startedAt: string | null;readonly completedAt: string | null;+ readonly turnEnded?: boolean;}export interface AgentSpawnSummary {@@ -1343,6 +1344,7 @@ export function deriveThreadFeedPresentation(if (isWorking &&activeWorkStartedAt !== null &&+ latestRun?.turnEnded !== true &&!result.some((row) =>row.id === LIVE_ACTIVITY_ROW_ID ||diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.tsindex a16df458e20..51d072951b4 100644--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts@@ -5804,6 +5804,87 @@ describe("CodexAdapterV2 post-settle continuation", () => {),);+ const childTurnStartedIndex = interruptSubagentCommandTranscript.entries.findIndex(+ (entry) => entry.type === "emit_inbound" && entry.label === "turn/started/child",+ );+ const failedRootLiveChildTranscript = makeCodexReplayTranscript({+ scenario: "codex-failed-root-live-subagent",+ entries: [+ ...interruptSubagentCommandTranscript.entries.slice(0, childTurnStartedIndex + 1),+ {+ type: "emit_inbound",+ label: "turn/completed/root-failed",+ frame: {+ method: "turn/completed",+ params: {+ threadId: INTERRUPT_NATIVE_THREAD,+ turn: {+ ...makeCodexReplayTurn({ id: INTERRUPT_NATIVE_TURN, status: "failed" }),+ error: {+ message: "unsupported websocket request type: response.interrupt",+ codexErrorInfo: "other",+ additionalDetails: null,+ },+ },+ },+ },+ },+ {+ type: "emit_inbound",+ label: "turn/completed/child",+ afterMs: 30_000,+ frame: {+ method: "turn/completed",+ params: {+ threadId: INTERRUPT_CHILD_NATIVE_THREAD,+ turn: makeCodexReplayTurn({ id: INTERRUPT_CHILD_NATIVE_TURN, status: "completed" }),+ },+ },+ },+ { type: "runtime_exit", status: "success" },+ ],+ });++ it.effect("settles a failed root without waiting for subagents that keep running", () =>+ Effect.scoped(+ Effect.gen(function* () {+ const harness = yield* makeCodexReplayHarness(failedRootLiveChildTranscript);+ const now = yield* DateTime.now;+ const childTurnCompleted = () =>+ harness.events.some(+ (event) =>+ event.type === "provider_turn.updated" &&+ event.threadId !== harness.threadId &&+ event.providerTurn.status === "completed",+ );++ yield* harness.runtime.startTurn(+ makeCodexTestTurnInput({+ threadId: harness.threadId,+ providerThread: harness.providerThread,+ now,+ attemptId: RunAttemptId.make("attempt-codex-failed-root-live-subagent"),+ text: INTERRUPT_PROMPT,+ }),+ );+ yield* awaitUntil(() => harness.terminalEvents().length === 1, "failed root terminal");++ const terminal = harness.terminalEvents()[0];+ assert.equal(terminal?.status, "failed");+ assert.isTrue(terminal?.status === "failed" && terminal.childTurnsContinue === true);+ assert.isFalse(childTurnCompleted(), "the subagent is still running");++ yield* TestClock.adjust("30 seconds");+ yield* awaitUntil(childTurnCompleted, "subagent turn completion");+ assert.lengthOf(harness.terminalEvents(), 1);+ }).pipe(+ Effect.provide(+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),+ ),+ ),+ ),+ );+const childTerminationResponseIndex = interruptSubagentCommandTranscript.entries.findIndex((entry) =>entry.type === "emit_inbound" && entry.label === "thread/backgroundTerminals/terminate/child",diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.tsindex 19d1e7b7ffe..928ae4a7e13 100644--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts@@ -5637,6 +5637,14 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (const hasActiveDescendants = Array.from((yield* Ref.get(activeTurns)).values()).some((candidate) => isDescendantCodexTurn(candidate, input.context),);+ // Native subagents run on their own threads, so a failed root leaves+ // them working. Holding the root until they finish would keep the+ // run open with no turn to steer. Stop interrupts the whole lineage,+ // so an interrupted root still waits for its descendants to settle.+ if (event.status === "failed" && hasActiveDescendants) {+ yield* emitRootTerminal(input.context, { ...event, childTurnsContinue: true });+ return;+ }if (event.status !== "completed" && hasActiveDescendants) {yield* Ref.update(deferredRootTerminals, (current) => {const updated = new Map(current);diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.tsindex 7e88b49789d..8cf9a4f28a4 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts@@ -4377,6 +4377,9 @@ function runBackgroundItemScenario(ReadonlyArray<{ readonly id: TurnItemId; readonly runId: RunId }>>;readonly onSubscribe?: Effect.Effect<void>;+ readonly onFinalized?: (+ events: ReadonlyArray<OrchestrationV2DomainEvent>,+ ) => Effect.Effect<void>;},) {return Effect.gen(function* () {@@ -4400,6 +4403,7 @@ function runBackgroundItemScenario()) {yield* Ref.update(observed, (current) => [...current, "root-finalized"]);+ yield* options?.onFinalized?.(input.events) ?? Effect.void;}return [];}),@@ -4504,6 +4508,54 @@ function runBackgroundItemScenario(});}+it.effect("keeps a failed root's still-running native children live while the run settles", () =>+ Effect.gen(function* () {+ const finalized = yield* Ref.make<ReadonlyArray<OrchestrationV2DomainEvent>>([]);+ const childTurn = (+ ids: BackgroundScenarioIds,+ status: "running" | "completed",+ ): ProviderAdapter.ProviderAdapterV2Event =>+ ({+ type: "provider_turn.updated",+ driver,+ threadId: ids.childThreadId,+ providerTurn: {+ id: ProviderTurnId.make(`${ids.rootProviderTurnId}:child`),+ providerThreadId: ProviderThreadId.make(`${ids.providerThreadId}:child`),+ nodeId: NodeId.make(`${ids.subagentNodeId}:child-root`),+ runAttemptId: null,+ status,+ },+ }) as ProviderAdapter.ProviderAdapterV2Event;+ const observed = yield* runBackgroundItemScenario(+ "failed-root-live-child",+ (ids) => [+ childThreadCreatedEvent(ids),+ subagentEvent(ids, "running"),+ childTurn(ids, "running"),+ { ...rootTerminalEvent(ids, "failed"), childTurnsContinue: true },+ subagentEvent(ids, "completed"),+ childTurn(ids, "completed"),+ ],+ {+ keepEventStreamOpen: true,+ onFinalized: (events) => Ref.set(finalized, events),+ },+ );++ assert.deepEqual(observed, ["subagent:running", "root-finalized", "subagent:completed"]);+ const written = yield* Ref.get(finalized);+ assert.deepEqual(+ written.flatMap((event) => (event.type === "run.updated" ? [event.payload.status] : [])),+ ["failed"],+ );+ assert.isFalse(+ written.some((event) => event.type === "subagent.updated"),+ "a child that outlives the failed root must not be settled with it",+ );+ }),+);+it.effect("releases ingestion after idle subagent rows and items settle", () =>Effect.gen(function* () {const observed = yield* runBackgroundItemScenario(diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.tsindex eb0f28310de..9abe812c3d1 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.ts@@ -167,6 +167,10 @@ function isRunOwnedSubagentTerminalStatus(return status === "interrupted" || status === "failed" || status === "cancelled";}+function childTurnsContinue(terminal: ProviderTerminalEvent): boolean {+ return terminal.status === "failed" && terminal.childTurnsContinue === true;+}+/*** A running subagent stays with the run that launched it, which keeps ingesting until it ends;* taking it over too would store its events twice.@@ -645,7 +649,9 @@ export const layer: Layer.Layer<open.childTurnItems.size > 0 ||open.nodes.size > 0;const cascadedSubagentEvents =- isRunOwnedSubagentTerminalStatus(input.terminal.status) && hasOpenSubagentProjection+ isRunOwnedSubagentTerminalStatus(input.terminal.status) &&+ !childTurnsContinue(input.terminal) &&+ hasOpenSubagentProjection? yield* cascadeTerminalizeRunOwnedSubagents({run: input.run,open,@@ -1011,7 +1017,10 @@ export const layer: Layer.Layer<(cause) => new RunExecutionIngestError({ runId: input.run.id, cause }),),);- if (isRunOwnedSubagentTerminalStatus(terminal.status)) {+ if (+ isRunOwnedSubagentTerminalStatus(terminal.status) &&+ !childTurnsContinue(terminal)+ ) {yield* Ref.set(openRunOwnedSubagents, emptyOpenRunOwnedSubagentProjection());}yield* Ref.set(rootRunFinalized, true);@@ -1161,7 +1170,11 @@ export const layer: Layer.Layer<return false;}const terminal = yield* Ref.get(terminalEvent);- if (terminal !== null && terminal.status !== "completed") {+ if (+ terminal !== null &&+ terminal.status !== "completed" &&+ !childTurnsContinue(terminal)+ ) {return true;}const childProviderTurns = yield* Ref.get(activeChildProviderTurns);diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.tsindex cd2da1dabb3..d55a621d875 100644--- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts+++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts@@ -1929,6 +1929,44 @@ describe("deriveMessagesTimelineRows", () => {expect(rows.at(-1)).toMatchObject({ kind: "thinking" });});+ it("does not show Thinking once the open run's provider turn has ended", () => {+ const input = {+ timelineEntries: [+ {+ id: "user-entry",+ kind: "message" as const,+ createdAt: "2026-01-01T00:00:00Z",+ message: {+ id: "user" as never,+ role: "user" as const,+ text: "Take over the queue",+ runId: "turn-1" as never,+ createdAt: "2026-01-01T00:00:00Z",+ updatedAt: "2026-01-01T00:00:00Z",+ streaming: false,+ },+ },+ ],+ latestRun: {+ runId: "turn-1" as never,+ status: "running" as const,+ startedAt: "2026-01-01T00:00:00Z",+ completedAt: null,+ },+ isWorking: true,+ activeTurnStartedAt: "2026-01-01T00:00:00Z",+ turnDiffSummaries: [],+ supportsConversationRollback: false,+ };++ expect(deriveMessagesTimelineRows(input).at(-1)?.kind).toBe("thinking");+ const ended = deriveMessagesTimelineRows({+ ...input,+ latestRun: { ...input.latestRun, turnEnded: true },+ });+ expect(ended.some((row) => row.kind === "thinking")).toBe(false);+ });+it("does not fold the active in-progress turn", () => {const rows = deriveMessagesTimelineRows({timelineEntries: [diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.ts b/apps/web/src/components/chat/MessagesTimeline.logic.tsindex f528ed2ee69..1024f11a213 100644--- a/apps/web/src/components/chat/MessagesTimeline.logic.ts+++ b/apps/web/src/components/chat/MessagesTimeline.logic.ts@@ -470,7 +470,7 @@ export interface TimelineDurationMessage {export type TimelineLatestRun = Pick<ThreadRunSummary,- "runId" | "status" | "startedAt" | "completedAt"+ "runId" | "status" | "startedAt" | "completedAt" | "turnEnded">;const LIVE_ACTIVITY_ROW_ID = "live-activity-row";@@ -1874,6 +1874,7 @@ export function deriveMessagesTimelineRows(input: {}if (input.isWorking &&+ input.latestRun?.turnEnded !== true &&!setupOwnsWorkingSlot &&!hasActiveCompaction &&(!hasActivityRow || latestToolFailed)diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.tsindex 020b690a602..36535a273cc 100644--- a/packages/client-runtime/src/state/models.ts+++ b/packages/client-runtime/src/state/models.ts@@ -41,6 +41,11 @@ export interface ThreadRunSummary {readonly startedAt: string | null;readonly completedAt: string | null;readonly assistantMessageId: MessageId | null;+ /**+ * The run is still open, but its provider turn already ended, so nothing is+ * generating while the server settles it.+ */+ readonly turnEnded?: boolean;readonly sourcePlanRef?: {readonly threadId: ThreadId;readonly planId: PlanId;diff --git a/packages/client-runtime/src/state/threadExecution.test.ts b/packages/client-runtime/src/state/threadExecution.test.tsindex 2d61f6d95f0..231f200f375 100644--- a/packages/client-runtime/src/state/threadExecution.test.ts+++ b/packages/client-runtime/src/state/threadExecution.test.ts@@ -6,6 +6,8 @@ import {ProviderThreadId,ProviderSessionId,ProviderDriverKind,+ ProviderTurnId,+ RunAttemptId,RunId,ThreadId,type OrchestrationV2ExecutionNode,@@ -191,6 +193,34 @@ describe("thread execution presentation", () => {expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(true);});+ it("marks an open run whose provider turn already ended", () => {+ const attemptId = RunAttemptId.make("attempt-open");+ const openRun = { ...run("run-open", 1, "running"), activeAttemptId: attemptId };+ const providerTurn = (status: "running" | "failed") => ({+ id: ProviderTurnId.make("provider-turn-open"),+ providerThreadId: ProviderThreadId.make("provider-thread-open"),+ nodeId: NodeId.make("node-open"),+ runAttemptId: attemptId,+ nativeTurnRef: null,+ ordinal: 1,+ status,+ startedAt: now,+ completedAt: status === "running" ? null : now,+ });+ const projection = (status: "running" | "failed") => ({+ ...v2Projection,+ runs: [openRun],+ providerTurns: [providerTurn(status)],+ updatedAt: now,+ });++ expect(deriveThreadActivityRun(projection("running"))?.turnEnded).toBeUndefined();+ expect(deriveThreadActivityRun(projection("failed"))).toMatchObject({+ status: "running",+ turnEnded: true,+ });+ });+it("presents a held queue as the stopped run instead of queued work", () => {const interrupted = { ...run("run-interrupted", 1, "interrupted"), completedAt: now };const held = { ...run("run-held", 2, "queued"), queueHeld: true };diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.tsindex 75ae3404e4b..e3e1cd92f74 100644--- a/packages/client-runtime/src/state/threadExecution.ts+++ b/packages/client-runtime/src/state/threadExecution.ts@@ -7,6 +7,7 @@ import {import {isOrchestrationV2WorkActive,isProviderNativeSubagentThread,+ latestProviderTurnForAttempt,type ModelSelection,type OrchestrationV2NotificationSource,type OrchestrationV2PendingBackgroundTask,@@ -52,6 +53,9 @@ function summarizeThreadRun(projection: OrchestrationV2ThreadProjection,run: OrchestrationV2ThreadProjection["runs"][number],): ThreadRunSummary {+ const turnStatus = ACTIVITY_RUN_STATUSES.has(run.status)+ ? latestProviderTurnForAttempt(projection.providerTurns, run.activeAttemptId)?.status+ : undefined;return {runId: run.id,status: run.status,@@ -62,6 +66,9 @@ function summarizeThreadRun(projection.messages.findLast((message) => message.runId === run.id && message.role === "assistant",)?.id ?? null,+ ...(turnStatus === undefined || turnStatus === "pending" || turnStatus === "running"+ ? {}+ : { turnEnded: true }),...(run.sourcePlanRef === undefined ? {} : { sourcePlanRef: run.sourcePlanRef }),};}diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.tsindex 1cc66c77f9c..d9a0f2fc95e 100644--- a/packages/provider-core/src/server/ProviderAdapter.ts+++ b/packages/provider-core/src/server/ProviderAdapter.ts@@ -164,6 +164,12 @@ export const ProviderAdapterV2Event = Schema.Union([retry: Schema.optional(OrchestrationV2ProviderRetry),retryStartedAt: Schema.optional(Schema.DateTimeUtc),threadDisposition: Schema.Literals(["reusable", "broken"]),+ /**+ * Child turns the root started outlive its failure and will report their+ * own terminals, as after a completed root. Without it, the run settles+ * every child it still sees as open.+ */+ childTurnsContinue: Schema.optional(Schema.Literal(true)),}),]);export type ProviderAdapterV2Event = typeof ProviderAdapterV2Event.Type;