From 6a7da7a350419d05a4c441b05d2ad67d146cc028 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 27 Oct 2026 07:15:32 +0000 Subject: [PATCH 1/6] test(server): reproduce #25796 steer offered mid-compaction This test reproduces pingdotgg/t3code#25796: a steer sent while Claude is compacting is offered to the SDK query at priority "now" right away, which aborts the compaction. The test expects the adapter to hold steers until the compact_result status arrives, then offer them in order. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 72 +++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 7fece9817ce01..74bac08759134 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -3041,6 +3041,78 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // regression: #25796 a `now` steer offered mid-compaction aborts the compaction + it.effect("holds steers sent during compaction until the compaction ends", () => + Effect.gen(function* () { + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const harness = yield* makeWakeHarness; + const input = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("steer-during-compaction"), + text: "Keep going.", + attachments: [], + }); + yield* harness.runtime.startTurn(input); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: "compacting", + uuid: "00000000-0000-4000-8000-000000000821", + session_id: WAKE_NATIVE_SESSION, + }), + ); + const providerTurnId = idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${input.attemptId}`, + }); + for (const text of ["First steer.", "Second steer."]) { + yield* harness.runtime.steerTurn({ + threadId: harness.threadId, + runId: input.runId, + providerThread: harness.providerThread, + providerTurnId, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`compaction-${text}`), + text, + attachments: [], + }, + }); + } + assert.lengthOf( + harness.offeredMessages, + 1, + "a steer sent while compacting reached Claude before the compaction ended", + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: null, + compact_result: "success", + uuid: "00000000-0000-4000-8000-000000000822", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.until(() => harness.offeredMessages.length >= 3); + const steers = harness.offeredMessages.slice(1); + assert.deepEqual( + steers.map((message) => message.priority), + ["now", "now"], + ); + assert.match(encodeJsonString(steers[0]?.message.content), /First steer/); + assert.match(encodeJsonString(steers[1]?.message.content), /Second steer/); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + const attachmentBudgetOutcomes = [ "resume", "legacy", From b571eaf98e3d2af6f211090fbc0bec22536d0b87 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 27 Oct 2026 07:25:01 +0000 Subject: [PATCH 2/6] fix(claude): steers sent during compaction no longer abort it Claude Code aborts automatic compaction when a priority "now" user message arrives while it compacts, then restarts it. The adapter now holds steers on the active turn while its compaction runs and offers them, in order and still with priority "now", once the compaction result status (or a bare compact_boundary) arrives, so the steer is answered in the same turn. steerTurn returns immediately, so Stop is never queued behind compaction. Stop offers held steers before interrupting, and a turn that ends with steers still held drops them and releases their PDF reservations. Fixes pingdotgg/t3code#25796 Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 62 ++++++++ .../Adapters/ClaudeAdapterV2.ts | 145 +++++++++++++++--- 2 files changed, 182 insertions(+), 25 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 74bac08759134..d3f557e084dd2 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -3113,6 +3113,68 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("offers a steer held for compaction before interrupting the turn", () => + Effect.gen(function* () { + const idAllocator = yield* IdAllocator.IdAllocatorV2; + let offeredAtInterrupt: number | undefined; + const harness = yield* makeWakeHarnessWithOptions({ + close: (sdkMessages) => Queue.shutdown(sdkMessages), + interrupt: Effect.sync(() => { + offeredAtInterrupt = harness.offeredMessages.length; + }), + }); + const input = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("steer-then-stop-during-compaction"), + text: "Keep going.", + attachments: [], + }); + yield* harness.runtime.startTurn(input); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: "compacting", + uuid: "00000000-0000-4000-8000-000000000831", + session_id: WAKE_NATIVE_SESSION, + }), + ); + const providerTurnId = idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${input.attemptId}`, + }); + yield* harness.runtime.steerTurn({ + threadId: harness.threadId, + runId: input.runId, + providerThread: harness.providerThread, + providerTurnId, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("steer-then-stop"), + text: "Then stop.", + attachments: [], + }, + }); + assert.lengthOf(harness.offeredMessages, 1); + yield* harness.runtime.interruptTurn({ + providerThread: harness.providerThread, + providerTurnId, + }); + assert.equal(offeredAtInterrupt, 2); + assert.equal(harness.offeredMessages[1]?.priority, "now"); + const terminal = yield* Queue.take(harness.terminalReceipts); + assert.equal(terminal.status, "interrupted"); + assert.lengthOf(harness.offeredMessages, 2); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + const attachmentBudgetOutcomes = [ "resume", "legacy", diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 94ccc16dda54c..cae24eb558eed 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -120,6 +120,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; +import * as Scope from "effect/Scope"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; @@ -3795,6 +3796,16 @@ interface ActiveClaudeTurnContext { nativeWakeStarted: boolean; gatedFramesBeforeEcho: number; readonly heldRootFrames: Array; + // A "now" steer offered while compaction runs aborts it. Read and written under sdkMessageLock. + readonly heldSteers: Array; +} + +interface HeldClaudeSteer { + readonly live: ClaudeLiveQueryContext; + readonly message: SDKUserMessage; + readonly pdfReservation: Effect.Success>; + // Owns the reservation past steerTurn; closing it releases an undelivered one. + readonly reservationScope: Scope.Closeable; } interface ActiveClaudeProviderRetry { @@ -7024,6 +7035,61 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( subagentToolCalls.clear(); }); + const offerSteer = Effect.fnUntraced(function* (input: { + readonly live: ClaudeLiveQueryContext; + readonly providerTurnId: OrchestrationV2ProviderTurn["id"]; + readonly message: SDKUserMessage; + readonly pdfReservation: HeldClaudeSteer["pdfReservation"]; + }) { + yield* Ref.update(steeredTurns, (current) => { + const next = new Set(current); + next.add(input.providerTurnId); + return next; + }); + yield* Effect.uninterruptibleMask((restore) => + restore( + input.live.query.offer(input.message, () => { + input.pdfReservation.commit(); + }), + ).pipe( + Effect.tap(() => + Effect.sync(() => { + input.pdfReservation.commit(); + }), + ), + ), + ); + }); + // Never offered once their turn ended: that would start a turn nobody asked for. + const dropHeldSteers = Effect.fnUntraced(function* (context: ActiveClaudeTurnContext) { + const dropped = context.heldSteers.splice(0); + if (dropped.length === 0) return; + for (const steer of dropped) { + yield* Scope.close(steer.reservationScope, Exit.void); + } + yield* Effect.logWarning("orchestration-v2.claude-held-steers-dropped", { + providerTurnId: context.providerTurnId, + count: dropped.length, + }); + }); + // Callers hold sdkMessageLock, so a newer steer cannot overtake the held ones. + const releaseHeldSteers = Effect.fnUntraced(function* (context: ActiveClaudeTurnContext) { + for (;;) { + const steer = context.heldSteers[0]; + if (steer === undefined) return; + if ( + (yield* Ref.get(activeTurn)) !== context || + (yield* Ref.get(queryContext)) !== steer.live + ) { + return yield* dropHeldSteers(context); + } + context.heldSteers.shift(); + yield* offerSteer({ ...steer, providerTurnId: context.providerTurnId }).pipe( + Effect.ensuring(Scope.close(steer.reservationScope, Exit.void)), + ); + } + }); + const finalizeActiveTurn = Effect.fnUntraced(function* (input: { readonly context: ActiveClaudeTurnContext; readonly status: Extract< @@ -7315,6 +7381,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( yield* Ref.update(activeTurn, (current) => current?.providerTurnId === input.context.providerTurnId ? null : current, ); + // After the turn is cleared, so a steer cannot be held on it once this runs. + yield* dropHeldSteers(input.context); if (input.status === "completed") { settledTurnByNativeThread.set(input.context.nativeThreadId, input.context); } else { @@ -8185,6 +8253,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (budget !== undefined) budget.compacting = null; } } + // Offered once compaction has ended, a "now" steer is answered in this turn. + yield* releaseHeldSteers(context); } if ( @@ -8304,6 +8374,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }, }); context.compaction = null; + // Some CLI versions end compaction with the boundary alone. + yield* releaseHeldSteers(context); return; } @@ -9985,6 +10057,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( nativeWakeStarted: false, gatedFramesBeforeEcho: 0, heldRootFrames: [], + heldSteers: [], }; const attachTurn = Effect.gen(function* () { querySession.lastTurn = context; @@ -10235,6 +10308,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( detail: `Claude provider turn ${turnInput.providerTurnId} is not the active turn.`, }); } + // Accepted steers reach Claude before Stop, not as a new turn after it. + if (currentTurn.heldSteers.length > 0) { + yield* sdkMessageLock.withPermits(1)(releaseHeldSteers(currentTurn)); + } yield* Ref.update(interruptedTurns, (current) => { const next = new Set(current); next.add(turnInput.providerTurnId); @@ -10369,6 +10446,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( detail: `Claude provider turn ${turnInput.providerTurnId} is not the active turn.`, }); } + // A held steer outlives this call, so its reservation has its own scope. + const reservationScope = yield* Scope.make(); + let held = false; + yield* Effect.addFinalizer((exit) => + held ? Effect.void : Scope.close(reservationScope, exit), + ); const pdfReservation = yield* reserveClaudePdfBudget( pdfBudgets.get(existing.nativeThreadId) ?? makeClaudeAttachmentBudget({ @@ -10376,7 +10459,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( bytesUsed: CLAUDE_ATTACHMENT_MAX_BYTES, }), persistAttachmentBudget(existing.nativeThreadId), - ); + ).pipe(Scope.provide(reservationScope)); const userMessage = yield* makeClaudeUserMessageWithAttachments({ text: applyClaudePromptEffortPrefix( turnInput.message.text, @@ -10393,36 +10476,48 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( Effect.provideService(Path.Path, path), ); yield* backgroundForegroundSubagents(existing, backgroundDeadline); - // The turn can end while the moves are answered. A steer offered - // then would start a new turn the orchestrator never asked for, so - // the steer fails and the orchestrator starts the follow-up turn. - if ( - (yield* Ref.get(activeTurn))?.providerTurnId !== turnInput.providerTurnId || - (yield* Ref.get(queryContext)) !== existing - ) { + // Under the frame lock, so a compaction cannot end between the check and the hold. + const delivery = yield* sdkMessageLock.withPermits(1)( + Effect.sync(() => { + // The turn can end while the moves are answered. A steer offered + // then would start a new turn the orchestrator never asked for, so + // the steer fails and the orchestrator starts the follow-up turn. + if ( + Ref.getUnsafe(activeTurn) !== currentTurn || + Ref.getUnsafe(queryContext) !== existing + ) { + return "ended" as const; + } + // Not waited for here: Stop runs after this steer and must not wait on compaction. + if ( + currentTurn.compaction?.status !== "running" && + currentTurn.heldSteers.length === 0 + ) { + return "offer" as const; + } + currentTurn.heldSteers.push({ + live: existing, + message: userMessage, + pdfReservation, + reservationScope, + }); + held = true; + return "held" as const; + }), + ); + if (delivery === "ended") { return yield* new ProviderAdapter.ProviderAdapterProtocolError({ driver: CLAUDE_PROVIDER, detail: `Claude provider turn ${turnInput.providerTurnId} ended before the steer was sent.`, }); } - yield* Ref.update(steeredTurns, (current) => { - const next = new Set(current); - next.add(turnInput.providerTurnId); - return next; + if (delivery === "held") return; + yield* offerSteer({ + live: existing, + providerTurnId: turnInput.providerTurnId, + message: userMessage, + pdfReservation, }); - yield* Effect.uninterruptibleMask((restore) => - restore( - existing.query.offer(userMessage, () => { - pdfReservation.commit(); - }), - ).pipe( - Effect.tap(() => - Effect.sync(() => { - pdfReservation.commit(); - }), - ), - ), - ); }, (effect, turnInput) => effect.pipe( From 5ab2885e8ce8e6ad8618eaaf482ca87f237323c7 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 27 Oct 2026 08:48:01 +0000 Subject: [PATCH 3/6] fix(claude): held steers report real delivery and Stop cancels them A steer held for compaction made steerTurn succeed at once, so a delegated message was accepted as delivered and then dropped if the turn ended before the compaction did. Stop also offered held steers mid-compaction instead of cancelling them. steerTurn now waits until its held steer is offered, and fails with the existing "ended before the steer was sent" error when the turn ends first, so the follow-up re-dispatch applies. Stop drops held steers without offering them. Because a waiting steer blocks the thread's effect queue, a run interrupt on a live provider turn now also cancels unsettled steer effects, which interrupts the waiting steerTurn instead of making Stop wait for the compaction. Fixes pingdotgg/t3code#25796 Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 187 ++++++++++-------- .../Adapters/ClaudeAdapterV2.ts | 90 +++++---- .../src/orchestration-v2/Orchestrator.ts | 9 +- .../SteeringCompletion.integration.test.ts | 59 +++++- 4 files changed, 223 insertions(+), 122 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index d3f557e084dd2..6b531877737b6 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -53,6 +53,7 @@ import { import { assert, describe, it } from "@effect/vitest"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; +import * as Cause from "effect/Cause"; import * as Deferred from "effect/Deferred"; import * as Crypto from "effect/Crypto"; import * as Effect from "effect/Effect"; @@ -60,6 +61,7 @@ import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; +import * as Logger from "effect/Logger"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PubSub from "effect/PubSub"; @@ -2959,7 +2961,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { ); if (outcome === "release-before") { yield* Deferred.succeed(release, undefined); - yield* Fiber.join(pending); } yield* harness.offerAndWait( claudeSdkFrame({ @@ -2976,6 +2977,9 @@ describe("ClaudeAdapterV2 background wake turns", () => { } else if (outcome === "release-after") { yield* Deferred.succeed(release, undefined); yield* Fiber.join(pending); + } else if (outcome === "release-before") { + // Held until the compaction ended. + yield* Fiber.join(pending); } // Flush the budget update through the event stream before trying again. yield* harness.offerAndWait( @@ -3041,47 +3045,80 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - // regression: #25796 a `now` steer offered mid-compaction aborts the compaction - it.effect("holds steers sent during compaction until the compaction ends", () => - Effect.gen(function* () { - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const harness = yield* makeWakeHarness; - const input = makeClaudeTestTurnInput({ + // Forks a steer and returns once the adapter holds it for the running compaction. + const holdSteerForCompaction = Effect.fnUntraced(function* ( + harness: Effect.Success, + input: { + readonly runId: ProviderAdapter.ProviderAdapterV2SteerInput["runId"]; + readonly providerTurnId: ProviderAdapter.ProviderAdapterV2SteerInput["providerTurnId"]; + readonly text: string; + }, + ) { + const held = yield* Deferred.make(); + const logger = Logger.make(({ message }) => { + if (String(message).includes("claude-steer-held-for-compaction")) { + Deferred.doneUnsafe(held, Effect.void); + } + }); + const steer = yield* harness.runtime + .steerTurn({ threadId: harness.threadId, + runId: input.runId, providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("steer-during-compaction"), - text: "Keep going.", - attachments: [], - }); - yield* harness.runtime.startTurn(input); - yield* harness.offerAndWait( - claudeSdkFrame({ - type: "system", - subtype: "status", - status: "compacting", - uuid: "00000000-0000-4000-8000-000000000821", - session_id: WAKE_NATIVE_SESSION, - }), - ); - const providerTurnId = idAllocator.derive.providerTurn({ + providerTurnId: input.providerTurnId, + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(`compaction-${input.text}`), + text: input.text, + attachments: [], + }, + }) + .pipe(Effect.provide(Logger.layer([logger], { mergeWithExisting: true })), Effect.forkChild); + yield* Deferred.await(held); + return steer; + }); + + const startCompactingTurn = Effect.fnUntraced(function* ( + harness: Effect.Success, + attemptId: string, + ) { + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const input = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make(attemptId), + text: "Keep going.", + attachments: [], + }); + yield* harness.runtime.startTurn(input); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "system", + subtype: "status", + status: "compacting", + uuid: "00000000-0000-4000-8000-000000000821", + session_id: WAKE_NATIVE_SESSION, + }), + ); + return { + runId: input.runId, + providerTurnId: idAllocator.derive.providerTurn({ driver: ClaudeAdapterV2.CLAUDE_PROVIDER, nativeTurnId: `turn:${input.attemptId}`, - }); + }), + }; + }); + + // regression: #25796 a `now` steer offered mid-compaction aborts the compaction + it.effect("holds steers sent during compaction until the compaction ends", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const turn = yield* startCompactingTurn(harness, "steer-during-compaction"); + const pending = []; for (const text of ["First steer.", "Second steer."]) { - yield* harness.runtime.steerTurn({ - threadId: harness.threadId, - runId: input.runId, - providerThread: harness.providerThread, - providerTurnId, - message: { - createdBy: "user", - creationSource: "web", - messageId: MessageId.make(`compaction-${text}`), - text, - attachments: [], - }, - }); + pending.push(yield* holdSteerForCompaction(harness, { ...turn, text })); } assert.lengthOf( harness.offeredMessages, @@ -3098,7 +3135,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { session_id: WAKE_NATIVE_SESSION, }), ); - yield* harness.until(() => harness.offeredMessages.length >= 3); + yield* Fiber.joinAll(pending); const steers = harness.offeredMessages.slice(1); assert.deepEqual( steers.map((message) => message.priority), @@ -3113,9 +3150,8 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("offers a steer held for compaction before interrupting the turn", () => + it.effect("cancels a steer held for compaction when the turn is stopped", () => Effect.gen(function* () { - const idAllocator = yield* IdAllocator.IdAllocatorV2; let offeredAtInterrupt: number | undefined; const harness = yield* makeWakeHarnessWithOptions({ close: (sdkMessages) => Queue.shutdown(sdkMessages), @@ -3123,51 +3159,42 @@ describe("ClaudeAdapterV2 background wake turns", () => { offeredAtInterrupt = harness.offeredMessages.length; }), }); - const input = makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("steer-then-stop-during-compaction"), - text: "Keep going.", - attachments: [], - }); - yield* harness.runtime.startTurn(input); - yield* harness.offerAndWait( - claudeSdkFrame({ - type: "system", - subtype: "status", - status: "compacting", - uuid: "00000000-0000-4000-8000-000000000831", - session_id: WAKE_NATIVE_SESSION, - }), - ); - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${input.attemptId}`, - }); - yield* harness.runtime.steerTurn({ - threadId: harness.threadId, - runId: input.runId, - providerThread: harness.providerThread, - providerTurnId, - message: { - createdBy: "user", - creationSource: "web", - messageId: MessageId.make("steer-then-stop"), - text: "Then stop.", - attachments: [], - }, - }); - assert.lengthOf(harness.offeredMessages, 1); + const turn = yield* startCompactingTurn(harness, "steer-then-stop-during-compaction"); + const steer = yield* holdSteerForCompaction(harness, { ...turn, text: "Then stop." }); yield* harness.runtime.interruptTurn({ providerThread: harness.providerThread, - providerTurnId, + providerTurnId: turn.providerTurnId, }); - assert.equal(offeredAtInterrupt, 2); - assert.equal(harness.offeredMessages[1]?.priority, "now"); + assert.equal(offeredAtInterrupt, 1); + const steerExit = yield* Fiber.await(steer); + assert.match( + Exit.isFailure(steerExit) ? Cause.pretty(steerExit.cause) : "steer succeeded", + /was stopped before the steer was sent/, + ); const terminal = yield* Queue.take(harness.terminalReceipts); assert.equal(terminal.status, "interrupted"); - assert.lengthOf(harness.offeredMessages, 2); + assert.lengthOf(harness.offeredMessages, 1); + }).pipe( + Effect.provide( + Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + ), + ), + ); + + it.effect("fails a steer held for compaction when the turn ends first", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const turn = yield* startCompactingTurn(harness, "turn-ends-during-compaction"); + const steer = yield* holdSteerForCompaction(harness, { ...turn, text: "Too late." }); + yield* harness.offerAndWait( + makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000823", result: "Done." }), + ); + const steerExit = yield* Fiber.await(steer); + assert.match( + Exit.isFailure(steerExit) ? Cause.pretty(steerExit.cause) : "steer succeeded", + /ended before the steer was sent/, + ); + assert.lengthOf(harness.offeredMessages, 1); }).pipe( Effect.provide( Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index cae24eb558eed..4760dee255ebd 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -120,7 +120,6 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Queue from "effect/Queue"; import * as Ref from "effect/Ref"; -import * as Scope from "effect/Scope"; import * as Schema from "effect/Schema"; import * as Semaphore from "effect/Semaphore"; import * as Stream from "effect/Stream"; @@ -3804,8 +3803,11 @@ interface HeldClaudeSteer { readonly live: ClaudeLiveQueryContext; readonly message: SDKUserMessage; readonly pdfReservation: Effect.Success>; - // Owns the reservation past steerTurn; closing it releases an undelivered one. - readonly reservationScope: Scope.Closeable; + // steerTurn waits on this, so it succeeds only once the steer is offered. + readonly sent: Deferred.Deferred< + void, + ClaudeAgentSdkQueryRunnerError | ProviderAdapter.ProviderAdapterProtocolError + >; } interface ActiveClaudeProviderRetry { @@ -7060,17 +7062,22 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ), ); }); + const steerNotSent = ( + providerTurnId: OrchestrationV2ProviderTurn["id"], + reason: "ended" | "was stopped", + ) => + new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CLAUDE_PROVIDER, + detail: `Claude provider turn ${providerTurnId} ${reason} before the steer was sent.`, + }); // Never offered once their turn ended: that would start a turn nobody asked for. - const dropHeldSteers = Effect.fnUntraced(function* (context: ActiveClaudeTurnContext) { - const dropped = context.heldSteers.splice(0); - if (dropped.length === 0) return; - for (const steer of dropped) { - yield* Scope.close(steer.reservationScope, Exit.void); + const dropHeldSteers = Effect.fnUntraced(function* ( + context: ActiveClaudeTurnContext, + reason: "ended" | "was stopped", + ) { + for (const steer of context.heldSteers.splice(0)) { + yield* Deferred.fail(steer.sent, steerNotSent(context.providerTurnId, reason)); } - yield* Effect.logWarning("orchestration-v2.claude-held-steers-dropped", { - providerTurnId: context.providerTurnId, - count: dropped.length, - }); }); // Callers hold sdkMessageLock, so a newer steer cannot overtake the held ones. const releaseHeldSteers = Effect.fnUntraced(function* (context: ActiveClaudeTurnContext) { @@ -7081,11 +7088,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( (yield* Ref.get(activeTurn)) !== context || (yield* Ref.get(queryContext)) !== steer.live ) { - return yield* dropHeldSteers(context); + return yield* dropHeldSteers(context, "ended"); } context.heldSteers.shift(); - yield* offerSteer({ ...steer, providerTurnId: context.providerTurnId }).pipe( - Effect.ensuring(Scope.close(steer.reservationScope, Exit.void)), + yield* Deferred.done( + steer.sent, + yield* Effect.exit(offerSteer({ ...steer, providerTurnId: context.providerTurnId })), ); } }); @@ -7382,7 +7390,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( current?.providerTurnId === input.context.providerTurnId ? null : current, ); // After the turn is cleared, so a steer cannot be held on it once this runs. - yield* dropHeldSteers(input.context); + yield* dropHeldSteers(input.context, "ended"); if (input.status === "completed") { settledTurnByNativeThread.set(input.context.nativeThreadId, input.context); } else { @@ -10308,9 +10316,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( detail: `Claude provider turn ${turnInput.providerTurnId} is not the active turn.`, }); } - // Accepted steers reach Claude before Stop, not as a new turn after it. + // Stop cancels steers still held for compaction instead of sending them. if (currentTurn.heldSteers.length > 0) { - yield* sdkMessageLock.withPermits(1)(releaseHeldSteers(currentTurn)); + yield* sdkMessageLock.withPermits(1)(dropHeldSteers(currentTurn, "was stopped")); } yield* Ref.update(interruptedTurns, (current) => { const next = new Set(current); @@ -10446,12 +10454,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( detail: `Claude provider turn ${turnInput.providerTurnId} is not the active turn.`, }); } - // A held steer outlives this call, so its reservation has its own scope. - const reservationScope = yield* Scope.make(); - let held = false; - yield* Effect.addFinalizer((exit) => - held ? Effect.void : Scope.close(reservationScope, exit), - ); const pdfReservation = yield* reserveClaudePdfBudget( pdfBudgets.get(existing.nativeThreadId) ?? makeClaudeAttachmentBudget({ @@ -10459,7 +10461,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( bytesUsed: CLAUDE_ATTACHMENT_MAX_BYTES, }), persistAttachmentBudget(existing.nativeThreadId), - ).pipe(Scope.provide(reservationScope)); + ); const userMessage = yield* makeClaudeUserMessageWithAttachments({ text: applyClaudePromptEffortPrefix( turnInput.message.text, @@ -10476,6 +10478,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( Effect.provideService(Path.Path, path), ); yield* backgroundForegroundSubagents(existing, backgroundDeadline); + const held: HeldClaudeSteer = { + live: existing, + message: userMessage, + pdfReservation, + sent: yield* Deferred.make< + void, + ClaudeAgentSdkQueryRunnerError | ProviderAdapter.ProviderAdapterProtocolError + >(), + }; // Under the frame lock, so a compaction cannot end between the check and the hold. const delivery = yield* sdkMessageLock.withPermits(1)( Effect.sync(() => { @@ -10488,30 +10499,35 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ) { return "ended" as const; } - // Not waited for here: Stop runs after this steer and must not wait on compaction. if ( currentTurn.compaction?.status !== "running" && currentTurn.heldSteers.length === 0 ) { return "offer" as const; } - currentTurn.heldSteers.push({ - live: existing, - message: userMessage, - pdfReservation, - reservationScope, - }); - held = true; + currentTurn.heldSteers.push(held); return "held" as const; }), ); if (delivery === "ended") { - return yield* new ProviderAdapter.ProviderAdapterProtocolError({ - driver: CLAUDE_PROVIDER, - detail: `Claude provider turn ${turnInput.providerTurnId} ended before the steer was sent.`, + return yield* steerNotSent(turnInput.providerTurnId, "ended"); + } + if (delivery === "held") { + yield* Effect.logInfo("orchestration-v2.claude-steer-held-for-compaction", { + providerTurnId: turnInput.providerTurnId, }); + // Stop cancels this effect rather than queueing behind the compaction it waits for. + return yield* Deferred.await(held.sent).pipe( + Effect.onInterrupt(() => + sdkMessageLock.withPermits(1)( + Effect.sync(() => { + const index = currentTurn.heldSteers.indexOf(held); + if (index !== -1) currentTurn.heldSteers.splice(index, 1); + }), + ), + ), + ); } - if (delivery === "held") return; yield* offerSteer({ live: existing, providerTurnId: turnInput.providerTurnId, diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index ee8ab83b952aa..0c35b84a3c1b2 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -10357,7 +10357,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } satisfies PendingOrchestrationEffectV2, ...otherProviderInterrupts, ]); - return undefined; + // A steer still waiting to reach the provider is cancelled, so the interrupt never queues behind it. + return { + effectTypes: ["provider-turn.steer"], + reason: `Run ${run.id} was interrupted before its steer was sent.`, + } satisfies { + readonly effectTypes: ReadonlyArray; + readonly reason: string; + }; }); /** Writes a parent's app-owned task, and sets its node and turn items to the task's status. */ diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index 2cc6ee6f825b2..b4c09c72cfbbb 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -408,11 +408,13 @@ const composerSelection = { const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* ( name: string, canRestart = false, + steerTurn?: (turn: ProviderAdapter.ProviderAdapterV2SteerInput) => Effect.Effect, ) { const cwd = yield* checkpointWorkspace(name); const events = yield* Queue.unbounded(); const started: ProviderAdapter.ProviderAdapterV2TurnInput[] = []; const steered: string[] = []; + const interrupted: ProviderTurnId[] = []; const capabilities = { ...CodexProviderCapabilitiesV2, turns: { @@ -488,11 +490,16 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* }, }); }), - steerTurn: (turn) => + steerTurn: + steerTurn ?? + ((turn) => + Effect.sync(() => { + steered.push(turn.message.text); + })), + interruptTurn: (turn) => Effect.sync(() => { - steered.push(turn.message.text); + interrupted.push(turn.providerTurnId); }), - interruptTurn: () => Effect.void, respondToRuntimeRequest: () => Effect.void, readThreadSnapshot: () => Effect.die("unused"), rollbackThread: () => Effect.die("unused"), @@ -547,7 +554,7 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* yield* Fiber.join(running); return threadId; }); - return { cwd, events, started, steered, layer, startFirstTurn }; + return { cwd, events, started, steered, interrupted, layer, startFirstTurn }; }); it.effect("sends a selected held message once and preserves the remaining queue order", () => @@ -825,6 +832,50 @@ it.effect("starts a steer that missed the turn on the saved next-turn selection" ), ); +// regression: #25796 Stop must not wait behind a steer the provider is still holding +it.effect("Stop cancels a steer still waiting to reach the provider", () => + Effect.scoped( + Effect.gen(function* () { + const steerWaiting = yield* Deferred.make(); + const { interrupted, layer, startFirstTurn } = yield* nextTurnSelectionHarness( + "stop-cancels-waiting-steer", + false, + () => Deferred.succeed(steerWaiting, undefined).pipe(Effect.andThen(Effect.never)), + ); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = yield* startFirstTurn; + const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("waiting-steer"), + threadId, + messageId: MessageId.make("message:waiting-steer"), + text: "steer", + attachments: [], + dispatchMode: { type: "steer_active", targetRunId: run.id }, + createdBy: "user", + creationSource: "web", + }); + const steering = yield* worker.runOnce.pipe(Effect.forkScoped); + yield* Deferred.await(steerWaiting); + yield* orchestrator.dispatch({ + type: "thread.stop", + commandId: CommandId.make("stop-waiting-steer"), + threadId, + }); + // The steer effect is cancelled, which ends its never-returning steerTurn. + yield* Fiber.join(steering); + yield* worker.drain(); + + const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + assert.deepEqual(interrupted, [turn.id]); + }).pipe(Effect.provide(layer)); + }), + ), +); + // Codex flushes held drafts after the final answer; reserve their pre-steer position before turn end. it.effect("keeps a held commentary draft before the steer when turn end flushes it", () => Effect.scoped( From bfe7f789276e852432df1d73d776b65080461207 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 01:06:23 +0000 Subject: [PATCH 4/6] test(server): adapt compaction steer tests to main's harness --- .../Adapters/ClaudeAdapterV2.test.ts | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index bbbab0c641c89..5e058a2a72a52 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -59,7 +59,6 @@ import { assert, describe, it } from "@effect/vitest"; import * as Cause from "effect/Cause"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; -import * as Cause from "effect/Cause"; import * as Deferred from "effect/Deferred"; import * as SecureRandom from "effect/crypto/SecureRandom"; import * as Effect from "effect/Effect"; @@ -3697,7 +3696,12 @@ describe("ClaudeAdapterV2 background wake turns", () => { assert.match(encodeJsonString(steers[1]?.message.content), /Second steer/); }).pipe( Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), ), ), ); @@ -3728,7 +3732,12 @@ describe("ClaudeAdapterV2 background wake turns", () => { assert.lengthOf(harness.offeredMessages, 1); }).pipe( Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), ), ), ); @@ -3749,7 +3758,12 @@ describe("ClaudeAdapterV2 background wake turns", () => { assert.lengthOf(harness.offeredMessages, 1); }).pipe( Effect.provide( - Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer), + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), ), ), ); From d183914a55c13fc9f1fa5bb583dc70a1764e9b0a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 01:27:34 +0000 Subject: [PATCH 5/6] fix(server): Stop sends a pending steer instead of discarding it Cancelling steer effects on Stop dropped the message while it still read as delivered, for every provider. Stop now leaves steers alone as on main, and the Claude adapter sends a steer held for compaction before it interrupts the turn. AI-assisted; verified with the tests and tools listed above. --- .../Adapters/ClaudeAdapterV2.test.ts | 12 +++---- .../Adapters/ClaudeAdapterV2.ts | 25 +++++--------- .../src/orchestration-v2/Orchestrator.ts | 9 +---- .../SteeringCompletion.integration.test.ts | 33 +++++-------------- 4 files changed, 23 insertions(+), 56 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 5e058a2a72a52..270034a572db6 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -3706,7 +3706,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("cancels a steer held for compaction when the turn is stopped", () => + it.effect("sends a steer held for compaction before the turn is stopped", () => Effect.gen(function* () { let offeredAtInterrupt: number | undefined; const harness = yield* makeWakeHarnessWithOptions({ @@ -3721,15 +3721,11 @@ describe("ClaudeAdapterV2 background wake turns", () => { providerThread: harness.providerThread, providerTurnId: turn.providerTurnId, }); - assert.equal(offeredAtInterrupt, 1); - const steerExit = yield* Fiber.await(steer); - assert.match( - Exit.isFailure(steerExit) ? Cause.pretty(steerExit.cause) : "steer succeeded", - /was stopped before the steer was sent/, - ); + assert.equal(offeredAtInterrupt, 2); + yield* Fiber.join(steer); const terminal = yield* Queue.take(harness.terminalReceipts); assert.equal(terminal.status, "interrupted"); - assert.lengthOf(harness.offeredMessages, 1); + assert.match(encodeJsonString(harness.offeredMessages[1]?.message.content), /Then stop/); }).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 99aba044f3225..400b76a91186a 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -7994,21 +7994,15 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ), ); }); - const steerNotSent = ( - providerTurnId: OrchestrationV2ProviderTurn["id"], - reason: "ended" | "was stopped", - ) => + const steerNotSent = (providerTurnId: OrchestrationV2ProviderTurn["id"]) => new ProviderAdapter.ProviderAdapterProtocolError({ driver: CLAUDE_PROVIDER, - detail: `Claude provider turn ${providerTurnId} ${reason} before the steer was sent.`, + detail: `Claude provider turn ${providerTurnId} ended before the steer was sent.`, }); // Never offered once their turn ended: that would start a turn nobody asked for. - const dropHeldSteers = Effect.fnUntraced(function* ( - context: ActiveClaudeTurnContext, - reason: "ended" | "was stopped", - ) { + const dropHeldSteers = Effect.fnUntraced(function* (context: ActiveClaudeTurnContext) { for (const steer of context.heldSteers.splice(0)) { - yield* Deferred.fail(steer.sent, steerNotSent(context.providerTurnId, reason)); + yield* Deferred.fail(steer.sent, steerNotSent(context.providerTurnId)); } }); // Callers hold sdkMessageLock, so a newer steer cannot overtake the held ones. @@ -8020,7 +8014,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( (yield* Ref.get(activeTurn)) !== context || (yield* Ref.get(queryContext)) !== steer.live ) { - return yield* dropHeldSteers(context, "ended"); + return yield* dropHeldSteers(context); } context.heldSteers.shift(); yield* Deferred.done( @@ -8334,7 +8328,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( current?.providerTurnId === input.context.providerTurnId ? null : current, ); // After the turn is cleared, so a steer cannot be held on it once this runs. - yield* dropHeldSteers(input.context, "ended"); + yield* dropHeldSteers(input.context); if (input.status === "completed") { settledTurnByNativeThread.set(input.context.nativeThreadId, input.context); } else { @@ -11647,9 +11641,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( detail: `Claude provider turn ${turnInput.providerTurnId} is not the active turn.`, }); } - // Stop cancels steers still held for compaction instead of sending them. + // Like an unheld steer, a held one reaches Claude before the interrupt. if (currentTurn.heldSteers.length > 0) { - yield* sdkMessageLock.withPermits(1)(dropHeldSteers(currentTurn, "was stopped")); + yield* sdkMessageLock.withPermits(1)(releaseHeldSteers(currentTurn)); } yield* Ref.update(interruptedTurns, (current) => { const next = new Set(current); @@ -11835,13 +11829,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }), ); if (delivery === "ended") { - return yield* steerNotSent(turnInput.providerTurnId, "ended"); + return yield* steerNotSent(turnInput.providerTurnId); } if (delivery === "held") { yield* Effect.logInfo("orchestration-v2.claude-steer-held-for-compaction", { providerTurnId: turnInput.providerTurnId, }); - // Stop cancels this effect rather than queueing behind the compaction it waits for. return yield* Deferred.await(held.sent).pipe( Effect.onInterrupt(() => sdkMessageLock.withPermits(1)( diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 710e61110d151..3157f55cacfa6 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -12170,14 +12170,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } satisfies PendingOrchestrationEffectV2, ...otherProviderInterrupts, ]); - // A steer still waiting to reach the provider is cancelled, so the interrupt never queues behind it. - return { - effectTypes: ["provider-turn.steer"], - reason: `Run ${run.id} was interrupted before its steer was sent.`, - } satisfies { - readonly effectTypes: ReadonlyArray; - readonly reason: string; - }; + return undefined; }); /** Writes a parent's app-owned task, and sets its node and turn items to the task's status. */ diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts index bad1117e72446..906e410131da5 100644 --- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts +++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts @@ -489,7 +489,6 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* interruptTurn: Effect.Effect = Effect.void, steeringAcceptsAttachments = true, nativeGoals?: boolean, - steerTurn?: (turn: ProviderAdapter.ProviderAdapterV2SteerInput) => Effect.Effect, ) { const driver = ProviderDriverKind.make(nativeGoals === undefined ? "codex" : "opencode"); const cwd = yield* checkpointWorkspace(name); @@ -581,12 +580,10 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function* resumeThread: ({ providerThread }) => Effect.succeed(providerThread), startTurn, compactThread: startTurn, - steerTurn: - steerTurn ?? - ((turn) => - Effect.sync(() => { - steered.push(turn.message.text); - })), + steerTurn: (turn) => + Effect.sync(() => { + steered.push(turn.message.text); + }), interruptTurn: ({ providerTurnId }) => Effect.sync(() => { interrupted.push(providerTurnId); @@ -1519,20 +1516,11 @@ it.effect( ), ); -// regression: #25796 Stop must not wait behind a steer the provider is still holding -it.effect("Stop cancels a steer still waiting to reach the provider", () => +it.effect("sends a pending steer before the Stop that follows it", () => Effect.scoped( Effect.gen(function* () { - const steerWaiting = yield* Deferred.make(); - const { interrupted, layer, startFirstTurn } = yield* nextTurnSelectionHarness( - "stop-cancels-waiting-steer", - false, - true, - Effect.void, - true, - undefined, - () => Deferred.succeed(steerWaiting, undefined).pipe(Effect.andThen(Effect.never)), - ); + const { steered, interrupted, layer, startFirstTurn } = + yield* nextTurnSelectionHarness("steer-before-stop"); yield* Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; @@ -1549,18 +1537,15 @@ it.effect("Stop cancels a steer still waiting to reach the provider", () => createdBy: "user", creationSource: "web", }); - const steering = yield* worker.runOnce.pipe(Effect.forkScoped); - yield* Deferred.await(steerWaiting); yield* orchestrator.dispatch({ type: "thread.stop", - commandId: CommandId.make("stop-waiting-steer"), + commandId: CommandId.make("stop-after-steer"), threadId, }); - // The steer effect is cancelled, which ends its never-returning steerTurn. - yield* Fiber.join(steering); yield* worker.drain(); const turn = (yield* orchestrator.getThreadProjection(threadId)).providerTurns[0]!; + assert.deepEqual(steered, ["steer"]); assert.deepEqual(interrupted, [turn.id]); }).pipe(Effect.provide(layer)); }), From 8d818fc0e7c27c4845856b64194e8a35710ab01d Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 11 Nov 2026 01:45:04 +0000 Subject: [PATCH 6/6] fix(claude): a steer held for compaction no longer blocks Stop The steer effect waited until compaction ended, and the outbox runs one effect per thread, so Stop's interrupt could not run until then. A held steer now settles at once; the adapter sends it when compaction ends or, on Stop, before it interrupts the turn. AI-assisted; verified with the tests and tools listed above. --- .../Adapters/ClaudeAdapterV2.test.ts | 12 ++--- .../Adapters/ClaudeAdapterV2.ts | 48 +++++++------------ 2 files changed, 23 insertions(+), 37 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 270034a572db6..ca8a97bd00c8d 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -3676,6 +3676,8 @@ describe("ClaudeAdapterV2 background wake turns", () => { 1, "a steer sent while compacting reached Claude before the compaction ended", ); + // Settled while held, so the thread's outbox is free for a Stop. + yield* Fiber.joinAll(pending); yield* harness.offerAndWait( claudeSdkFrame({ type: "system", @@ -3686,7 +3688,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { session_id: WAKE_NATIVE_SESSION, }), ); - yield* Fiber.joinAll(pending); const steers = harness.offeredMessages.slice(1); assert.deepEqual( steers.map((message) => message.priority), @@ -3738,7 +3739,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("fails a steer held for compaction when the turn ends first", () => + it.effect("does not send a held steer once its turn has ended", () => Effect.gen(function* () { const harness = yield* makeWakeHarness; const turn = yield* startCompactingTurn(harness, "turn-ends-during-compaction"); @@ -3746,11 +3747,8 @@ describe("ClaudeAdapterV2 background wake turns", () => { yield* harness.offerAndWait( makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000823", result: "Done." }), ); - const steerExit = yield* Fiber.await(steer); - assert.match( - Exit.isFailure(steerExit) ? Cause.pretty(steerExit.cause) : "steer succeeded", - /ended before the steer was sent/, - ); + yield* Fiber.join(steer); + yield* Queue.take(harness.terminalReceipts); assert.lengthOf(harness.offeredMessages, 1); }).pipe( Effect.provide( diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 400b76a91186a..2f92e72926996 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -4410,11 +4410,6 @@ interface HeldClaudeSteer { readonly live: ClaudeLiveQueryContext; readonly message: SDKUserMessage; readonly pdfReservation: Effect.Success>; - // steerTurn waits on this, so it succeeds only once the steer is offered. - readonly sent: Deferred.Deferred< - void, - ClaudeAgentSdkQueryRunnerError | ProviderAdapter.ProviderAdapterProtocolError - >; } interface ActiveClaudeProviderRetry { @@ -8001,9 +7996,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( }); // Never offered once their turn ended: that would start a turn nobody asked for. const dropHeldSteers = Effect.fnUntraced(function* (context: ActiveClaudeTurnContext) { - for (const steer of context.heldSteers.splice(0)) { - yield* Deferred.fail(steer.sent, steerNotSent(context.providerTurnId)); - } + const dropped = context.heldSteers.splice(0).length; + if (dropped === 0) return; + yield* Effect.logWarning("orchestration-v2.claude-held-steers-dropped", { + providerTurnId: context.providerTurnId, + dropped, + }); }); // Callers hold sdkMessageLock, so a newer steer cannot overtake the held ones. const releaseHeldSteers = Effect.fnUntraced(function* (context: ActiveClaudeTurnContext) { @@ -8017,9 +8015,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return yield* dropHeldSteers(context); } context.heldSteers.shift(); - yield* Deferred.done( - steer.sent, - yield* Effect.exit(offerSteer({ ...steer, providerTurnId: context.providerTurnId })), + yield* offerSteer({ ...steer, providerTurnId: context.providerTurnId }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("orchestration-v2.claude-held-steer-offer-failed", { + providerTurnId: context.providerTurnId, + cause: Cause.pretty(cause), + }), + ), ); } }); @@ -11797,15 +11799,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( Effect.provideService(Path.Path, path), ); yield* backgroundForegroundSubagents(existing, backgroundDeadline); - const held: HeldClaudeSteer = { - live: existing, - message: userMessage, - pdfReservation, - sent: yield* Deferred.make< - void, - ClaudeAgentSdkQueryRunnerError | ProviderAdapter.ProviderAdapterProtocolError - >(), - }; + const held: HeldClaudeSteer = { live: existing, message: userMessage, pdfReservation }; // Under the frame lock, so a compaction cannot end between the check and the hold. const delivery = yield* sdkMessageLock.withPermits(1)( Effect.sync(() => { @@ -11832,19 +11826,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( return yield* steerNotSent(turnInput.providerTurnId); } if (delivery === "held") { + // Returning frees the thread's outbox so Stop can reach interruptTurn, which sends + // held steers first. Committed now: this scope's release would otherwise drop it. + pdfReservation.commit(); yield* Effect.logInfo("orchestration-v2.claude-steer-held-for-compaction", { providerTurnId: turnInput.providerTurnId, }); - return yield* Deferred.await(held.sent).pipe( - Effect.onInterrupt(() => - sdkMessageLock.withPermits(1)( - Effect.sync(() => { - const index = currentTurn.heldSteers.indexOf(held); - if (index !== -1) currentTurn.heldSteers.splice(index, 1); - }), - ), - ), - ); + return; } yield* offerSteer({ live: existing,