diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index b2b27327b66dc..6981e80464f41 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -13229,6 +13229,132 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // An API error fails the turn, but the CLI process and its background tasks keep running. + const liveProcessFailedResult = makeResultFrame({ + uuid: "00000000-0000-4000-8000-000000000311", + result: "API Error: 502 Bad Gateway", + isError: true, + apiErrorStatus: 502, + terminalReason: "api_error", + }); + + it.effect("keeps background tasks waitable after a turn fails on a live process", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const awaitBackgroundTasks = harness.runtime.awaitBackgroundTasks; + if (awaitBackgroundTasks === undefined) { + throw new Error("Claude adapter runtime must expose awaitBackgroundTasks."); + } + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-failed-live-roster"), + text: "Run the build in the background.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer(harness.sdkMessages, liveProcessFailedResult); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "failed"); + + assert.deepStrictEqual( + providerThreadRosterEvents(harness.events) + .at(-1) + ?.providerThread.pendingBackgroundTasks?.map((task) => task.taskId), + [WAKE_TASK_ID], + ); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + const marked = yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: [WAKE_TASK_ID], + awaited: true, + }); + assert.deepStrictEqual(marked.matched, [WAKE_TASK_ID]); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("clears background tasks when the Claude process exits mid-turn", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-probe-exit"), + text: "Run the build in the background.", + attachments: [], + }), + ); + yield* harness.offerAndWait(wakeTaskStarted); + assert.isTrue(yield* harness.hasPendingBackgroundWork); + yield* Queue.shutdown(harness.sdkMessages); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "failed"); + assert.deepStrictEqual( + providerThreadRosterEvents(harness.events) + .at(-1) + ?.providerThread.pendingBackgroundTasks?.map((task) => task.taskId) ?? [], + [], + ); + assert.isFalse(yield* harness.hasPendingBackgroundWork); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + it.effect("wakes the idle thread when a task outlives a turn that failed on a live process", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-claude-failed-live-wake"), + text: "Run the build in the background.", + attachments: [], + }), + ); + yield* Queue.offer(harness.sdkMessages, wakeTaskStarted); + yield* Queue.offer(harness.sdkMessages, liveProcessFailedResult); + assert.equal((yield* Queue.take(harness.terminalReceipts)).status, "failed"); + + yield* harness.offerAndWait(wakeNotification); + yield* harness.offerAndWait(wakeAssistant); + assert.deepStrictEqual( + harness.continuationRequests.map((request) => request.detail), + [WAKE_SUMMARY], + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("ScheduleWakeup stop:true releases the pending wakeup's hold", () => Effect.gen(function* () { const harness = yield* makeWakeHarness; @@ -14435,10 +14561,17 @@ describe("ClaudeAdapterV2 background wake turns", () => { const rosterBAfterFail = providerThreadRosterEvents(events).findLast( (event) => event.providerThread.id === providerThreadB.id, )?.providerThread.pendingBackgroundTasks; - assert.deepEqual(rosterBAfterFail ?? [], []); + assert.deepEqual(rosterBAfterFail ?? [], [ + { + taskId: taskB, + description: "work on B", + kind: "command", + nativeItemId: "toolu-roster-b", + }, + ]); assert.isFalse(yield* hasPendingBackgroundWorkForThread(providerThreadA)); - assert.isFalse(yield* hasPendingBackgroundWorkForThread(providerThreadB)); - assert.isFalse(yield* hasPendingBackgroundWork); + assert.isTrue(yield* hasPendingBackgroundWorkForThread(providerThreadB)); + assert.isTrue(yield* hasPendingBackgroundWork); }).pipe( Effect.provide( Layer.mergeAll( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 34d81c88d3559..1ae83853ed26a 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -9471,11 +9471,18 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( Effect.gen(function* () { const nativeThreadId = input.context.input.providerThread.nativeThreadRef?.nativeId ?? null; + const liveQuery = yield* Ref.get(queryContext); + // Background tasks outlive a failed turn while the process that ran it stays open. + const processKeepsTasks = + input.status === "failed" && + liveQuery !== null && + !liveQuery.stopping && + liveQuery.lastTurn === input.context; if (nativeThreadId !== null) { - if (input.status !== "completed") { + if (input.status !== "completed" && !processKeepsTasks) { // Stop cancels Claude's wakeup and an exited process loses it; a failed // turn on a live process leaves it pending. Process exits null the query first. - if (input.status !== "failed" || (yield* Ref.get(queryContext)) === null) { + if (input.status !== "failed" || liveQuery === null) { scheduledWakeupsByNativeThread.delete(nativeThreadId); } yield* clearPendingBackgroundTasksForNativeThread(nativeThreadId); @@ -9515,7 +9522,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeThreadId === null ? undefined : goalsByNativeThread.get(nativeThreadId); const goalChecked = goalCheckedTurns.delete(input.context.providerTurnId); const terminalReason = input.result?.terminal_reason; - const liveQuery = yield* Ref.get(queryContext); if ( nativeThreadId !== null && goal?.status === "active" && diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.ts index 8a3540a6a61f0..bbac6607820d8 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts @@ -10,6 +10,7 @@ import { type OrchestrationV2CheckpointScope, type OrchestrationV2DomainEvent, type OrchestrationV2ExecutionNode, + type OrchestrationV2PendingBackgroundTask, type OrchestrationV2ProviderThread, type OrchestrationV2ProviderTurn, type OrchestrationV2Run, @@ -2393,15 +2394,17 @@ it.effect("keeps ingesting a failed root's background item when its work continu }), ); -it.effect("does not pin ingestion on background items when the root turn is interrupted", () => - Effect.gen(function* () { - const observed = yield* runBackgroundItemScenario("bg-interrupted", (ids) => [ - backgroundTurnItemEvent(ids, "command_execution", "running", 1), - rootTerminalEvent(ids, "interrupted"), - backgroundTurnItemEvent(ids, "command_execution", "completed", 2), - ]); - assert.deepEqual(observed, ["turn_item:running", "root-finalized"]); - }), +it.effect.each(["interrupted", "failed"] as const)( + "does not pin ingestion on background items when the root turn is %s", + (status) => + Effect.gen(function* () { + const observed = yield* runBackgroundItemScenario(`bg-${status}`, (ids) => [ + backgroundTurnItemEvent(ids, "command_execution", "running", 1), + rootTerminalEvent(ids, status), + backgroundTurnItemEvent(ids, "command_execution", "completed", 2), + ]); + assert.deepEqual(observed, ["turn_item:running", "root-finalized"]); + }), ); it.effect("seeds inherited background items before their next update", () => @@ -3927,6 +3930,57 @@ it.effect("keeps completed runs completed when pull request refresh fails", () = }), ); +it.effect.each(["completed", "failed"] as const)( + "persists a background-task roster clear that arrives after a %s turn", + (status) => + Effect.gen(function* () { + const pending = yield* Ref.make(true); + const ingested = yield* Ref.make>([]); + yield* captureRootRunTermination({ + key: `roster-clear-${status}`, + shouldFinalizeRun: () => Effect.succeed(true), + hasPendingBackgroundWorkForThread: () => Ref.get(pending), + events: (ids) => { + const runningBuild: OrchestrationV2PendingBackgroundTask = { + taskId: "running-build", + kind: "command", + }; + const roster = (hasTask: boolean): ProviderAdapter.ProviderAdapterV2Event => { + const pendingBackgroundTasks: ReadonlyArray = + hasTask ? [runningBuild] : []; + return { + type: "provider_thread.updated", + driver, + providerThread: { + id: ids.providerThreadId, + driver, + appThreadId: ids.threadId, + pendingBackgroundTasks, + } as OrchestrationV2ProviderThread, + }; + }; + return Stream.fromIterable([roster(true), rootTerminalEvent(ids, status), roster(false)]); + }, + // The adapter clears its live roster before ingestion reaches the queued clear. + beforeTerminalWrite: () => Ref.set(pending, false).pipe(Effect.as(true)), + ingestNormalized: (input) => + Ref.update(ingested, (all) => [...all, input.event]).pipe( + Effect.as( + input.event.type === "provider_thread.updated" + ? [{} as OrchestrationV2StoredEvent] + : [], + ), + ), + }); + const rosters = (yield* Ref.get(ingested)).flatMap((event) => + event.type === "provider_thread.updated" + ? [event.providerThread.pendingBackgroundTasks] + : [], + ); + assert.deepEqual(rosters.at(-1), [], "an ended task must leave the persisted roster"); + }), +); + function captureRootRunTermination(input: { readonly key: string; readonly shouldFinalizeRun: () => Effect.Effect; diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.ts index d7a021a873799..113e0866b1402 100644 --- a/apps/server/src/orchestration-v2/RunExecutionService.ts +++ b/apps/server/src/orchestration-v2/RunExecutionService.ts @@ -1249,7 +1249,7 @@ export const layer: Layer.Layer< const openRunOwnedSubagents = yield* Ref.make(emptyOpenRunOwnedSubagentProjection()); // Open tool calls on the root thread, to end from their stored rows if the runtime is lost. const openRootToolCalls = new Set(); - // The last stored root snapshot's pendingBackgroundWork; adapters that omit it leave it false. + // The last stored root snapshot still reports background work, by flag or task roster. let rootSnapshotPendingWork = false; // Owned child threads whose last snapshot reported pending work, such as a queued native // continuation. Unlike the root's, these must hold the stream past owner loss. @@ -1614,6 +1614,21 @@ export const layer: Layer.Layer< const childSubagents = yield* Ref.get(activeChildSubagents); return childSubagents.size === 0; }); + // Claude background Bash has no turn-item projection. Use only the + // thread-scoped probe: session-wide pending work (siblings, wake + // buffers, session subagents) must not pin this root subscription. + const threadHasPendingBackgroundWork = Effect.gen(function* () { + // The live probe reads adapter state, which can be ahead of the events consumed here. + if (rootSnapshotPendingWork) { + return true; + } + if (input.session.hasPendingBackgroundWorkForThread === undefined) { + return false; + } + return yield* input.session + .hasPendingBackgroundWorkForThread(yield* Ref.get(latestProviderThread)) + .pipe(Effect.catchCause(() => Effect.succeed(false))); + }); const shouldStopProviderEventIngestion = Effect.gen(function* () { if (!(yield* agentTurnsSettled)) { return false; @@ -1624,7 +1639,12 @@ export const layer: Layer.Layer< terminal.status !== "completed" && !childTurnsContinue(terminal) ) { - return true; + // A failed turn can leave background work running in a live provider process. + return ( + terminal.status !== "failed" || + (yield* Ref.get(providerThreadOwnerLost)) || + !(yield* threadHasPendingBackgroundWork) + ); } // Newly owned items depend on adapters emitting a non-terminal event before the root // terminal. Owner loss (a newer run claimed lastRunOrdinal) must not close this stream @@ -1637,23 +1657,7 @@ export const layer: Layer.Layer< if (yield* Ref.get(providerThreadOwnerLost)) { return true; } - // The live probe reads adapter state, which can be ahead of the events consumed here. - if (rootSnapshotPendingWork) { - return false; - } - // Claude background Bash has no turn-item projection. Use only the - // thread-scoped probe: session-wide pending work (siblings, wake - // buffers, session subagents) must not pin this root subscription. - const latestProviderThreadSnapshot = yield* Ref.get(latestProviderThread); - if (input.session.hasPendingBackgroundWorkForThread !== undefined) { - const hasPendingWork = yield* input.session - .hasPendingBackgroundWorkForThread(latestProviderThreadSnapshot) - .pipe(Effect.catchCause(() => Effect.succeed(false))); - if (hasPendingWork) { - return false; - } - } - return true; + return !(yield* threadHasPendingBackgroundWork); }); // Held text writes nothing, so its item would take a position only // when finally written, behind every item that began after it. @@ -1934,7 +1938,9 @@ export const layer: Layer.Layer< if (event.type === "provider_thread.updated") { if (event.providerThread.id === input.providerThread.id && storedEventCount > 0) { yield* Ref.set(latestProviderThread, event.providerThread); - rootSnapshotPendingWork = event.pendingBackgroundWork === true; + rootSnapshotPendingWork = + event.pendingBackgroundWork === true || + (event.providerThread.pendingBackgroundTasks?.length ?? 0) > 0; } else if (event.providerThread.id !== input.providerThread.id) { if (event.pendingBackgroundWork === true) { childSnapshotPendingWork.add(event.providerThread.id);