From 1d6fbc42ad18ce7857563b69ba3e3d96602be92f Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 08:59:20 +0000 Subject: [PATCH 1/7] test(server): Claude steers must not cancel running tool calls (#21895) Fails on main: steerTurn offers the steer with priority "now", which makes Claude Code abort running and waiting tool calls and report them as a user refusal. AI-assisted; verified with the tests and tools listed above. --- .../Adapters/ClaudeAdapterV2.test.ts | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index c73956d3aa74f..e153e2885a997 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -5756,6 +5756,57 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("steering does not hand Claude an input that cancels the running tool calls", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const input = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("steer-priority"), + text: "Run the slow commands", + attachments: [], + }); + yield* harness.runtime.startTurn(input); + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const providerTurnId = idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${input.attemptId}`, + }); + for (const [createdBy, creationSource] of [ + ["user", "web"], + ["agent", "mcp"], + ] as const) { + yield* harness.runtime.steerTurn({ + threadId: harness.threadId, + runId: input.runId, + providerThread: harness.providerThread, + providerTurnId, + message: { + createdBy, + creationSource, + messageId: MessageId.make(`steer-priority-${createdBy}`), + text: "Progress note, nothing to change.", + attachments: [], + }, + }); + } + // Claude Code aborts in-flight and waiting tool calls for a "now" input and + // reports the waiting ones as "The user doesn't want to take this action". + assert.notEqual(harness.offeredMessages[1]?.priority, "now"); + assert.notEqual(harness.offeredMessages[2]?.priority, "now"); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #29750 Claude sets a goal only from a prompt that opens with /goal it("keeps a /goal that mentions a skill as one native goal command", () => { const message = ClaudeAdapterV2.makeClaudeUserMessage({ From d6cf7a848cbc66c302e68a26dbf522bc9ee8902a Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 09:15:27 +0000 Subject: [PATCH 2/7] fix(server): steers on Claude threads no longer cancel running tool calls T3 offered every steer to Claude Code with priority "now", which Claude Code treats as an interrupt: tool calls waiting in the current batch were cancelled and reported to the agent as "The user doesn't want to take this action right now". Composer steers and agent t3_thread_send steers both hit this. Steers are now offered with priority "next", so Claude Code delivers them at the next turn boundary without cancelling the batch. Fixes pingdotgg/t3code#21895 AI-assisted; verified with the tests and tools listed above. --- .../Adapters/ClaudeAdapterV2.test.ts | 10 +++++----- .../orchestration-v2/Adapters/ClaudeAdapterV2.ts | 5 +++-- .../ClaudeAutomaticDelivery.integration.test.ts | 16 ++++++---------- .../message_steering/claude_transcript.ndjson | 2 +- 4 files changed, 15 insertions(+), 18 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index e153e2885a997..61aa77e96cf06 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -2636,7 +2636,7 @@ describe("ClaudeAdapterV2 attachments", () => { }, }); - assert.equal(offeredMessages[1]?.priority, "now"); + assert.equal(offeredMessages[1]?.priority, "next"); assert.deepEqual(offeredMessages[1]?.message.content, expectedContent); const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!); for (const scenario of [ @@ -5739,7 +5739,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { }, }); const attachmentNote = `\n\n[Attached file "requirements.pdf" is saved at: ${path.join(harness.attachmentsDir, attachmentRelativePath(attachment)!)}]`; - assert.equal(harness.offeredMessages[1]?.priority, "now"); + assert.equal(harness.offeredMessages[1]?.priority, "next"); assert.deepEqual(harness.offeredMessages[1]?.message.content, [ { type: "text", text: `${leadingText}${attachmentNote}` }, { type: "text", text: `/implement the fixes${attachmentNote}` }, @@ -5881,7 +5881,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { }, }), ); - // Past task_started the CLI queues a "now" steer until the call returns. + // Past task_started the CLI queues a steer until the call returns. yield* harness.offerAndWait( claudeSdkFrame({ type: "system", @@ -6083,7 +6083,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { let settleDuringOffer: (message: SDKUserMessage) => Effect.Effect = () => Effect.void; const harness = yield* makeWakeHarnessWithOptions({ offer: (message) => - message.priority === "now" + message.priority === "next" ? Effect.suspend(() => settleDuringOffer(message)) : Effect.void, }); @@ -8238,7 +8238,7 @@ describe("ClaudeAdapterV2 background wake turns", () => { attachments: [], }, }); - assert.equal(harness.offeredMessages[1]?.priority, "now"); + assert.equal(harness.offeredMessages[1]?.priority, "next"); } const partialText = "The audit covers the `integ"; if (!queryExits) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 4a9ed9093d66d..d5e1806da6dc8 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -13681,7 +13681,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ), ); - // Move subagents to the background before priority "now" steers cancel foreground tools. + // Move subagents to the background so a steer reaches Claude without waiting for them to finish. const backgroundForegroundSubagents = Effect.fnUntraced(function* ( live: ClaudeLiveQueryContext, deadline: number, @@ -13811,7 +13811,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ).promptEffort, ), attachments: turnInput.message.attachments, - priority: "now", + // "now" makes Claude Code cancel the tool calls in flight and report them as a user refusal. + priority: "next", uuid: steerUuid, attachmentsDir, fileSystem, diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts index 1fa7047aff428..0ea75469e461d 100644 --- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts +++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts @@ -134,7 +134,7 @@ const deliveries = [ ] as const; it.effect.each(deliveries)( - "delivers %s with Claude's native pending-tool cancellation behavior", + "delivers %s without Claude cancelling the pending tool calls in its batch", (delivery) => Effect.gen(function* () { const cwd = yield* checkpointWorkspace("claude-automatic-delivery"); @@ -403,7 +403,7 @@ it.effect.each(deliveries)( yield* worker.drain(); const explicitSteer = delivery === "user steering" || delivery === "promoted queued message"; - assert.equal(batchAbort.signal.aborted, explicitSteer); + assert.equal(batchAbort.signal.aborted, false); assert.equal(offers.length, explicitSteer ? 2 : 1); const finished = yield* watch( (event) => @@ -414,7 +414,6 @@ it.effect.each(deliveries)( yield* Queue.offer(sdkMessages, toolResult("build", false)); for (const id of statusIds) yield* Queue.offer(sdkMessages, toolResult(id, batchAbort.signal.aborted)); - if (explicitSteer) yield* Queue.offer(sdkMessages, result("aborted", true)); yield* Queue.offer(sdkMessages, result("completed", false)); yield* Fiber.join(finished); yield* worker.drain(); @@ -447,15 +446,12 @@ it.effect.each(deliveries)( ); assert.equal(reads.length, 4); for (const read of reads) { - assert.equal(read.status, explicitSteer ? "cancelled" : "completed"); - assert.equal(read.toolNonExecutionKind, explicitSteer ? "cancelled" : undefined); - assert.equal(read.type === "dynamic_tool" && read.output === refusal, explicitSteer); + assert.equal(read.status, "completed"); + assert.equal(read.toolNonExecutionKind, undefined); + assert.equal(read.type === "dynamic_tool" && read.output === refusal, false); } assert.equal(offers.length, 2); - assert.equal( - offers.filter((offer) => offer.priority === "now").length, - explicitSteer ? 1 : 0, - ); + assert.equal(offers.filter((offer) => offer.priority === "now").length, 0); if (!explicitSteer) { assert.equal(after.runs.length, 2); if (delivery === "child completion") { diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/claude_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/claude_transcript.ndjson index a1cacf97d8002..157d98d0162d8 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/claude_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/message_steering/claude_transcript.ndjson @@ -1,7 +1,7 @@ {"type":"transcript_start","provider":"claudeAgent","protocol":"claude-agent-sdk.query","version":"0.2.111","scenario":"message_steering","metadata":{"prompts":["Respond with exactly: steering fixture initial response","Actually, respond with exactly: steering fixture observed"],"model":"claude-sonnet-4-6","nativeSessionId":"05f72f7d-81d5-4db9-a3cf-234191cf79f9","queryMode":"active_steering","tools":"claude_code","permissionMode":"bypassPermissions","generatedBy":"recordClaudeAgentSdkReplayTranscript"}} {"type":"expect_outbound","label":"query.open","frame":{"type":"query.open","options":{"model":"claude-sonnet-4-6","tools":{"type":"preset","preset":"claude_code"},"permissionMode":"bypassPermissions","allowDangerouslySkipPermissions":true,"sessionId":"05f72f7d-81d5-4db9-a3cf-234191cf79f9","settings":{"showThinkingSummaries":true}}}} {"type":"expect_outbound","label":"prompt.offer:1","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Respond with exactly: steering fixture initial response"},"parent_tool_use_id":null}}} -{"type":"expect_outbound","label":"prompt.offer:2","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Actually, respond with exactly: steering fixture observed"},"parent_tool_use_id":null,"priority":"now"}}} +{"type":"expect_outbound","label":"prompt.offer:2","frame":{"type":"prompt.offer","message":{"type":"user","message":{"role":"user","content":"Actually, respond with exactly: steering fixture observed"},"parent_tool_use_id":null,"priority":"next"}}} {"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_started","hook_id":"2961831d-241e-47c4-8099-b8779c6b3878","hook_name":"SessionStart:startup","hook_event":"SessionStart","uuid":"d45438eb-d485-490f-9668-a02c5721a6b3","session_id":"05f72f7d-81d5-4db9-a3cf-234191cf79f9"}} {"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"hook_response","hook_id":"2961831d-241e-47c4-8099-b8779c6b3878","hook_name":"SessionStart:startup","hook_event":"SessionStart","output":"","stdout":"","stderr":"","exit_code":0,"outcome":"success","uuid":"40ef0c52-1168-4049-99af-4c3beb507994","session_id":"05f72f7d-81d5-4db9-a3cf-234191cf79f9"}} {"type":"emit_inbound","label":"system","frame":{"type":"system","subtype":"init","agents":[],"apiKeySource":"none","claude_code_version":"2.1.111","cwd":"/tmp/claude-replay-message_steering","tools":[],"mcp_servers":[],"model":"claude-sonnet-4-6","permissionMode":"bypassPermissions","slash_commands":[],"output_style":"default","skills":[],"plugins":[],"fast_mode_state":"off","uuid":"71579637-9bc5-4182-b104-4ebb8f2bda0d","session_id":"05f72f7d-81d5-4db9-a3cf-234191cf79f9"}} From cee0871669a5cc22235691cb2235f68fbdc4a19c Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 12 Nov 2026 09:36:25 +0000 Subject: [PATCH 3/7] fix(server): a Claude turn stays open until Claude answers a steer it has not read With steers offered as "next", Claude answers a steer still unread at the end of the turn as its next native turn, after a normal success result. That result settled the T3 turn, marked the unread steer completed and cleared the active turn, so the steer's reply was dropped and its tool requests were denied for having no active turn. A completed result that echoes prompt uuids while a steer is still pending now keeps the turn open, as an aborted steered segment already does; the result that answers the steer settles it. AI-assisted; verified with the tests and tools listed above. --- .../Adapters/ClaudeAdapterV2.test.ts | 40 +++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 15 +++++++ 2 files changed, 55 insertions(+) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 61aa77e96cf06..00bb688e0e472 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -6059,7 +6059,47 @@ describe("ClaudeAdapterV2 background wake turns", () => { user_message_uuid: harness.promptUuid(0), }), ); + // Claude answers the unread steer as its next native turn, which belongs to this turn. + assert.equal(harness.terminalEvents().length, 0); + yield* expectSteers({ + "message-steer-read": "completed", + "message-steer-unread": "pending", + }); + const decision = yield* Effect.promise(() => + harness.getOpenedOptions()!.canUseTool!( + "Read", + { file_path: "README.md" }, + { + signal: new AbortController().signal, + toolUseID: "steer-read", + requestId: "request-steer-read", + }, + ), + ).pipe(Effect.forkScoped); + const first = yield* Effect.raceFirst( + Queue.take(harness.runtimeRequestReceipts).pipe(Effect.as("request")), + Fiber.join(decision).pipe(Effect.map((result) => result?.behavior)), + ); + assert.notEqual(first, "deny"); + yield* harness.offerAndWait( + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000002397", + text: "Steer reply.", + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002398", result: "Done." }), + user_message_uuid: harness.promptUuid(2), + }), + ); yield* harness.awaitTerminal(1); + assert.equal(harness.terminalEvents()[0]?.status, "completed"); + assert.ok( + harness.events.some( + (event) => event.type === "message.updated" && event.message.text === "Steer reply.", + ), + ); yield* expectSteers({ "message-steer-read": "completed", "message-steer-unread": "completed", diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index d5e1806da6dc8..1e8bb99cddb99 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -11887,6 +11887,21 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); return; } + // Claude answers a steer it has not read yet as the next native turn, which echoes + // the steer. A result without echoes cannot prove that turn will come. + if ( + !interrupted && + context.pendingSteers.size > 0 && + claudeEchoedPromptUuids(message).length > 0 && + terminalStatusFromResult(message) === "completed" + ) { + context.steeredSegmentUsage.push(message.usage); + context.steeredLedgerUsage = addClaudeLedgerUsage( + context.steeredLedgerUsage, + resultLedgerUsage.get(message), + ); + return; + } yield* Ref.update(steeredTurns, (current) => { const next = new Set(current); next.delete(context.providerTurnId); From 906a07a1167fada22c219d8a68f68f3919d67bcd Mon Sep 17 00:00:00 2001 From: Alb11747 Date: Thu, 19 Nov 2026 07:29:32 +0000 Subject: [PATCH 4/7] test(server): an unread Claude steer must not hang the turn or be lost Fails on the parent commit: - a steer Claude cancels before reading it leaves the turn open forever; - cancelling one steer must not end a turn Claude is still answering another in; - an unread steer is dropped when Claude exits or the server restarts, and Stop after Claude cancels it leaves it pending with no notice; - a requeued steer keeps its place and model among queued messages, even in the same millisecond, and survives a second drop. Co-Authored-By: Claude Opus 5.5 (implementation) Co-Authored-By: Claude Fable 5.2 (coordination) Co-Authored-By: GPT-6.2 Sol (review, live test) --- .../Adapters/ClaudeAdapterV2.test.ts | 92 ++++++ ...laudeAutomaticDelivery.integration.test.ts | 305 ++++++++++++++++++ .../ProviderRuntimeRecoveryService.test.ts | 19 +- 3 files changed, 412 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 00bb688e0e472..db23684f54662 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -6117,6 +6117,98 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + // A steer Claude starts after holding the result answers in this turn, so dropping another + // steer then must not end the turn under it. + it.effect("keeps the turn open for a started steer when Claude drops another", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const attemptId = RunAttemptId.make("attempt-steer-dropped"); + const input = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId, + text: "Run the build.", + attachments: [], + }); + yield* harness.runtime.startTurn(input); + for (const id of ["message-steer-started", "message-steer-dropped"]) { + yield* harness.runtime.steerTurn({ + threadId: harness.threadId, + runId: input.runId, + providerThread: harness.providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }), + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make(id), + text: `Steer ${id}`, + attachments: [], + }, + }); + } + const lifecycle = (index: number, state: string, uuid: string) => + harness.offerAndWait( + claudeSdkFrame({ + type: "command_lifecycle", + command_uuid: harness.promptUuid(index), + state, + uuid, + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002500", result: "Built." }), + user_message_uuid: harness.promptUuid(0), + }), + ); + yield* lifecycle(1, "started", "00000000-0000-4000-8000-000000002501"); + yield* lifecycle(2, "cancelled", "00000000-0000-4000-8000-000000002502"); + yield* harness.offerAndWait( + makeAssistantTextFrame({ + uuid: "00000000-0000-4000-8000-000000002503", + text: "Steer reply.", + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002504", result: "Done." }), + user_message_uuid: harness.promptUuid(1), + }), + ); + yield* harness.awaitTerminal(1); + const reply = harness.events.find( + (event) => event.type === "message.updated" && event.message.text === "Steer reply.", + ); + assert.equal(reply?.type === "message.updated" ? reply.message.runId : null, input.runId); + assert.deepEqual( + harness.events.flatMap((event) => + event.type === "steer.updated" ? [[event.messageId, event.status]] : [], + ), + [ + ["message-steer-started", "pending"], + ["message-steer-dropped", "pending"], + ["message-steer-started", "completed"], + ], + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // Claude can answer a steer while its offer is still being logged. it.effect("settles a turn whose result echoes only a steer before the offer returns", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts index 0ea75469e461d..93177fffbdde8 100644 --- a/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts +++ b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts @@ -10,6 +10,7 @@ import { NodeId, ProjectId, ProviderInstanceId, + type RunId, ScheduledTaskUpsertInput, ThreadId, type OrchestrationV2DomainEvent, @@ -1030,3 +1031,307 @@ it.effect("offers a continuation for a later wake after a queued continuation is ), ), ); + +// A steer Claude never read runs as the next turn, between the messages sent before and after +// it, even when they share a millisecond and the later one picks another model. +it.effect.each([ + "Claude cancels it twice", + "the Claude process exits", + "the server restarts", + "Claude cancels it and the user stops", +] as const)("handles an unread steer when %s", (outcome) => + Effect.gen(function* () { + const cwd = yield* checkpointWorkspace("claude-unread-steer"); + const sdkMessages = yield* Queue.unbounded(); + const offers: SDKUserMessage[] = []; + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({ + instanceId: modelSelection.instanceId, + settings, + environment: {}, + attachmentsDir: cwd, + fileSystem: yield* FileSystem.FileSystem, + path: yield* Path.Path, + random: yield* SecureRandom.SecureRandom, + idAllocator: yield* IdAllocator.IdAllocatorV2, + queryRunner: { + allocateSessionId: Effect.succeed(sessionId), + open: () => + Effect.succeed({ + messages: Stream.fromQueue(sdkMessages), + offer: (message) => Effect.sync(() => void offers.push(message)), + setModel: () => Effect.void, + applyFlagSettings: () => Effect.void, + setPermissionMode: () => Effect.void, + renameSession: () => Effect.void, + backgroundTasks: () => Effect.succeed(false), + mcpServerStatus: Effect.succeed([]), + readMcpResource: () => Effect.die("unexpected MCP resource read"), + callMcpTool: () => Effect.die("unexpected MCP tool call"), + listPermissionRules: Effect.die("unexpected permission rules read"), + stopTask: () => Effect.void, + interrupt: Queue.shutdown(sdkMessages), + close: Effect.void, + }), + forkSession: () => Effect.die("unused"), + subagentLaunchToolUseId: () => Effect.succeed(null), + subagentModel: () => Effect.succeed(null), + assertComplete: Effect.void, + }, + }); + yield* Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2; + const threadId = ThreadId.make("thread:unread-steer"); + const steerId = MessageId.make("steer"); + const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) => + orchestrator.streamDomainEvents.pipe( + Stream.filter(predicate), + Stream.take(1), + Stream.runDrain, + Effect.forkScoped, + ); + const settled = (runId: RunId, status: "waiting") => + watch( + (event) => + event.type === "run.updated" && + event.payload.id === runId && + event.payload.status === status, + ); + const pending = () => + watch( + (event) => + event.type === "turn-item.updated" && + event.payload.type === "user_message" && + event.payload.messageId === steerId && + event.payload.status === "pending", + ); + const answer = (offer: SDKUserMessage) => + Queue.offer( + sdkMessages, + frame({ + ...(result(`result-${offer.uuid}`, false) as object), + user_message_uuid: offer.uuid, + }), + ); + const cancel = (offer: SDKUserMessage) => + Queue.offer( + sdkMessages, + frame({ + type: "command_lifecycle", + command_uuid: offer.uuid, + state: "cancelled", + uuid: `cancelled-${offer.uuid}`, + session_id: sessionId, + }), + ); + const offeredText = (offer: SDKUserMessage | undefined) => + JSON.stringify(offer?.message.content ?? null); + const queued = Effect.map(orchestrator.getThreadProjection(threadId), (projection) => + projection.runs + .filter((run) => run.status === "queued") + .toSorted( + (left, right) => + (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal), + ), + ); + const queuedOrder = Effect.map(queued, (runs) => + runs.map((run) => [run.userMessageId, run.queueHeld === true]), + ); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create"), + threadId, + projectId: ProjectId.make("project:unread-steer"), + title: "Unread steer", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: cwd, + createdBy: "user", + creationSource: "web", + }); + const running = yield* watch( + (event) => event.type === "provider-turn.updated" && event.payload.status === "running", + ); + const send = ( + id: string, + dispatchMode: + | { readonly type: "start_immediately" | "queue_after_active" } + | { readonly type: "steer_active"; readonly targetRunId: RunId }, + model?: string, + ) => + orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(id), + threadId, + messageId: MessageId.make(id), + text: `Message ${id}`, + attachments: [], + ...(model === undefined ? {} : { modelSelection: { ...modelSelection, model } }), + dispatchMode, + createdBy: "user", + creationSource: "web", + }); + yield* send("first", { type: "start_immediately" }); + yield* worker.drain(); + yield* Fiber.join(running); + const parent = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!; + yield* send("before", { type: "queue_after_active" }); + const unread = yield* pending(); + yield* send("steer", { type: "steer_active", targetRunId: parent.id }); + yield* worker.drain(); + yield* Fiber.join(unread); + yield* send("after", { type: "queue_after_active" }, "claude-opus-4-1"); + assert.deepEqual( + offers.map((offer) => offer.priority), + [undefined, "next"], + ); + + if (outcome === "Claude cancels it twice") { + const ended = yield* settled(parent.id, "waiting"); + const nextRunning = yield* watch( + (event) => + event.type === "provider-turn.updated" && + event.payload.status === "running" && + event.payload.runAttemptId !== parent.activeAttemptId, + ); + yield* answer(offers[0]!); + yield* cancel(offers[1]!); + yield* Fiber.join(ended); + yield* worker.drain(); + yield* Fiber.join(nextRunning); + // The older message runs first; the steer waits right behind it on its own model. + const behind = yield* queued; + assert.deepEqual( + behind.map((run) => run.userMessageId), + [steerId, MessageId.make("after")], + ); + assert.deepEqual(behind[0]?.modelSelection, modelSelection); + assert.include(offeredText(offers[2]), "Message before"); + // Promoted into that run, Claude drops it again; it is queued again, then reaches Claude. + const before = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.userMessageId === MessageId.make("before"), + )!; + yield* orchestrator.dispatch({ + type: "queued-message.promote-to-steer", + commandId: CommandId.make("promote"), + threadId, + queuedRunId: behind[0]!.id, + targetRunId: before.id, + }); + yield* worker.drain(); + assert.equal(offers[3]?.priority, "next"); + const beforeEnded = yield* settled(before.id, "waiting"); + yield* answer(offers[2]!); + yield* cancel(offers[3]!); + yield* Fiber.join(beforeEnded); + yield* worker.drain(); + assert.deepEqual(yield* queuedOrder, [[MessageId.make("after"), false]]); + assert.equal(offers.length, 5); + assert.equal(offers[4]?.priority, undefined); + assert.include(offeredText(offers[4]), "Message steer"); + return; + } + + if (outcome === "the Claude process exits") { + const requeued = yield* watch( + (event) => + event.type === "run.updated" && + event.payload.userMessageId === steerId && + event.payload.status === "queued", + ); + yield* Queue.shutdown(sdkMessages); + yield* Fiber.join(requeued); + yield* worker.drain(); + // The provider failure holds the queue, the follow-up included, until someone resumes it. + assert.deepEqual(yield* queuedOrder, [ + [MessageId.make("before"), true], + [steerId, true], + [MessageId.make("after"), true], + ]); + assert.equal(offers.length, 2); + return; + } + + if (outcome === "Claude cancels it and the user stops") { + yield* cancel(offers[1]!); + const dropped = yield* watch( + (event) => + event.type === "turn-item.updated" && + event.payload.type === "user_message" && + event.payload.messageId === steerId && + event.payload.status === "cancelled", + ); + yield* orchestrator.dispatch({ + type: "run.interrupt", + commandId: CommandId.make("stop"), + threadId, + runId: parent.id, + holdQueue: true, + }); + yield* worker.drain(); + yield* Fiber.join(dropped); + const after = yield* orchestrator.getThreadProjection(threadId); + assert.equal( + after.turnItems.find((item) => item.type === "user_message" && item.messageId === steerId) + ?.status, + "cancelled", + ); + assert.isTrue( + after.turnItems.some( + (item) => item.type === "system_notice" && item.message?.includes("Message steer"), + ), + ); + assert.deepEqual(yield* queuedOrder, [ + [MessageId.make("before"), true], + [MessageId.make("after"), true], + ]); + return; + } + + // Recovery cancels the run, holds the queue and leaves the unread steer pending. + const projection = yield* orchestrator.getThreadProjection(threadId); + const now = yield* DateTime.now; + yield* (yield* EventSink.EventSinkV2).write({ + commandId: CommandId.make("command:runtime-reconcile:startup:unread-steer"), + events: projection.runs.map((run, index) => ({ + id: EventId.make(`recovered-run-${index}`), + type: "run.updated" as const, + threadId, + runId: run.id, + occurredAt: now, + payload: + run.id === parent.id + ? { ...run, status: "cancelled" as const, completedAt: now } + : { ...run, queueHeld: true }, + })), + }); + yield* orchestrator.recoverDelegatedTasks; + yield* worker.drain(); + assert.deepEqual(yield* queuedOrder, [ + [MessageId.make("before"), true], + [steerId, true], + [MessageId.make("after"), true], + ]); + assert.equal(offers.length, 2); + }).pipe( + Effect.provide( + ProviderReplayHarness.layerWithRegistry( + { name: "claude-unread-steer" }, + ProviderAdapterRegistry.layerSingle(adapter), + { runEffectWorker: false }, + ), + ), + ); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), +); diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts index 0a1e71f78d098..fb879295bcdab 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts @@ -419,7 +419,7 @@ it.effect("cancels a stale waiting run when no checkpoint capture can finish it" }).pipe(Effect.provide(layer)); }); -it.effect("recovery closes a secret card's form but leaves a link card open", () => { +it.effect("recovery closes a secret card but leaves a link card and an unread steer open", () => { const threadId = ThreadId.make("thread_secret_recovery"); const runId = RunId.make("run_secret_recovery"); let committedInput: Parameters[0] | null = @@ -467,6 +467,16 @@ it.effect("recovery closes a secret card's form but leaves a link card open", () url: "https://box.example.ts.net", reason: "Run the suite there.", }, + { + id: "turn-item:steer:recovery", + threadId, + runId, + nodeId: null, + type: "user_message", + status: "pending", + inputIntent: "steer", + messageId: "message:steer:recovery", + }, ], } as unknown as OrchestrationV2ThreadProjection; const layer = ProviderRuntimeRecovery.layer.pipe( @@ -504,9 +514,10 @@ it.effect("recovery closes a secret card's form but leaves a link card open", () assert.equal(secret?.status, "cancelled"); assert.equal(secret?.type === "secret_request" ? secret.secretStatus : null, "cancelled"); // Nothing in memory waits on a link card; the user can still answer it. - assert.equal( - cards.some((card) => card.type === "link_request"), - false, + // Claude never reported reading the steer, so the orchestrator queues it. + assert.deepEqual( + cards.filter((card) => card.type === "link_request" || card.type === "user_message"), + [], ); }).pipe(Effect.provide(layer)); }); From 5d961dfafc1aa8f2c1f6e9ef3e04b22245f90583 Mon Sep 17 00:00:00 2001 From: Alb11747 Date: Thu, 19 Nov 2026 07:29:59 +0000 Subject: [PATCH 5/7] fix(server): a steer Claude never read runs as the next turn With steers offered as "next", a turn held open for an unread steer never ended when Claude cancelled the steer instead of starting it, and a steer lost to an exited Claude process or a server restart was dropped. A steer is read only when Claude reports it started. The held turn settles when Claude cancels, discards or refuses the last unread steer, unless another steer Claude started is still being answered. A steer Claude dropped, or whose process exited, stays pending; when its run ends the orchestrator sends it through the existing steer follow-up path, placed by the ordinal its first steer effect recorded and on its own model. A provider failure holds that follow-up like the rest of the queue. Recovery leaves such a steer pending and startup queues it held. Stop keeps its notice, and a steer still pending on a stopped run gets the same notice instead of staying unread. Co-Authored-By: Claude Opus 5.5 (implementation) Co-Authored-By: Claude Fable 5.2 (coordination) Co-Authored-By: GPT-6.2 Sol (review, live test) --- .../Adapters/ClaudeAdapterV2.ts | 81 +++++--- .../src/orchestration-v2/EffectOutbox.ts | 24 +++ .../src/orchestration-v2/Orchestrator.ts | 181 +++++++++++++++++- .../src/orchestration-v2/ProjectionStore.ts | 13 +- .../ProviderRuntimeRecoveryService.ts | 7 + docs/user/providers-claude.md | 9 + 6 files changed, 290 insertions(+), 25 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 1e8bb99cddb99..121b1a8842c56 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -5099,6 +5099,9 @@ interface ActiveClaudeTurnContext { >; // Claude may settle a turn with a result that echoes only a steer's uuid. readonly steerUuids: Set; + // A completed result whose turn stays open while Claude still holds a steer; it settles the + // turn if Claude drops that steer instead of starting it. + heldResult: SDKResultMessage | undefined; // Claude can run another model than requested, such as when an organization disallows it. executedModel: string | undefined; } @@ -9219,6 +9222,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( status, }); + // A held result's usage joins the steered segments once another result settles the turn. + const absorbHeldResult = (context: ActiveClaudeTurnContext) => { + if (context.heldResult === undefined) return; + context.steeredSegmentUsage.push(context.heldResult.usage); + context.steeredLedgerUsage = addClaudeLedgerUsage( + context.steeredLedgerUsage, + resultLedgerUsage.get(context.heldResult), + ); + context.heldResult = undefined; + }; + const markSteersAccepted = Effect.fnUntraced(function* ( context: ActiveClaudeTurnContext, message: SDKMessage, @@ -9236,8 +9250,28 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const steer = context.pendingSteers.get(uuid); if (steer === undefined) continue; context.pendingSteers.delete(uuid); + // Claude now answers this steer, and that answer's result ends the turn. + absorbHeldResult(context); yield* emitSteerStatus(context, steer.messageId, "completed"); } + // Claude removed the steer before reading it. Its item stays pending, so the orchestrator + // sends it as the next turn once this run ends. + if ( + lifecycle !== null && + (lifecycle.state === "cancelled" || + lifecycle.state === "discarded" || + lifecycle.state === "refused") && + context.pendingSteers.delete(lifecycle.uuid) && + context.pendingSteers.size === 0 && + context.heldResult !== undefined + ) { + yield* finalizeActiveTurn({ + context, + status: "completed", + completedAt: yield* DateTime.now, + result: context.heldResult, + }); + } }); const finalizeActiveTurn = Effect.fnUntraced(function* (requested: { @@ -9267,10 +9301,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( if (input.status === "completed" && input.context.appContextOffered !== undefined) { deliveredAppContext.set(input.context.nativeThreadId, input.context.appContextOffered); } - // A turn that completes has taken in every steer; one that stops drops them unread. + // A live Claude still runs a steer queued at a completed result, and Stop drops them unread + // with a notice below. A steer whose process exited stays pending: nothing can read it now, + // so the orchestrator sends it as the next turn. const droppedSteers = [...input.context.pendingSteers]; input.context.pendingSteers.clear(); - for (const [, { messageId }] of droppedSteers) { + const currentQuery = yield* Ref.get(queryContext); + for (const [, { messageId, liveQuery }] of droppedSteers) { + if (input.status !== "interrupted" && liveQuery !== currentQuery) continue; yield* emitSteerStatus( input.context, messageId, @@ -11866,6 +11904,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( const completedAt = yield* DateTime.now; const interrupted = (yield* Ref.get(interruptedTurns)).has(context.providerTurnId); const wasSteered = (yield* Ref.get(steeredTurns)).has(context.providerTurnId); + absorbHeldResult(context); if (!interrupted && wasSteered && isClaudeActiveSteeringAbortResult(message)) { const cutOffReply = context.assistant.lastReply; context.assistant.lastReply = null; @@ -11887,21 +11926,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); return; } - // Claude answers a steer it has not read yet as the next native turn, which echoes - // the steer. A result without echoes cannot prove that turn will come. - if ( - !interrupted && - context.pendingSteers.size > 0 && - claudeEchoedPromptUuids(message).length > 0 && - terminalStatusFromResult(message) === "completed" - ) { - context.steeredSegmentUsage.push(message.usage); - context.steeredLedgerUsage = addClaudeLedgerUsage( - context.steeredLedgerUsage, - resultLedgerUsage.get(message), - ); - return; - } yield* Ref.update(steeredTurns, (current) => { const next = new Set(current); next.delete(context.providerTurnId); @@ -11995,13 +12019,25 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( resultFailure?.class === "usage_limit" ? { ...resultFailure, resetAt } : resultFailure; + const status = interrupted + ? "interrupted" + : limitedCompaction !== null + ? "failed" + : terminalStatusFromResult(message, failureHint); + // Claude answers a steer it has not read yet as the next native turn, which echoes + // the steer. A result without echoes cannot prove that turn will come. + if ( + status === "completed" && + terminalFailure === null && + context.pendingSteers.size > 0 && + claudeEchoedPromptUuids(message).length > 0 + ) { + context.heldResult = message; + return; + } yield* finalizeActiveTurn({ context, - status: interrupted - ? "interrupted" - : limitedCompaction !== null - ? "failed" - : terminalStatusFromResult(message, failureHint), + status, completedAt, result: message, ...(terminalFailure === null ? {} : { failure: terminalFailure }), @@ -13353,6 +13389,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( heldRootFrames: [], pendingSteers: new Map(), steerUuids: new Set(), + heldResult: undefined, executedModel: undefined, }; const attachTurn = Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/EffectOutbox.ts b/apps/server/src/orchestration-v2/EffectOutbox.ts index 69fd60684bbcb..4c94016e1c423 100644 --- a/apps/server/src/orchestration-v2/EffectOutbox.ts +++ b/apps/server/src/orchestration-v2/EffectOutbox.ts @@ -226,6 +226,11 @@ export interface EffectOutboxV2Shape { readonly listByCommandId: ( commandId: CommandId, ) => Effect.Effect, EffectOutboxError>; + /** A message's first steer effect: it records which runs were queued before the message. */ + readonly firstSteer: ( + threadId: ThreadId, + messageId: MessageId, + ) => Effect.Effect, EffectOutboxError>; readonly cancelUnsettled: (input: { readonly threadId: ThreadId; readonly effectTypes: ReadonlyArray; @@ -472,6 +477,25 @@ export const layer: Layer.Layer = La : new EffectOutboxError({ operation: "list", cause }), ), ), + firstSteer: (threadId, messageId) => + sql` + SELECT * + FROM orchestration_v2_effect_outbox + WHERE thread_id = ${threadId} + AND effect_type = 'provider-turn.steer' + AND json_extract(payload_json, '$.messageId') = ${messageId} + ORDER BY rowid ASC + LIMIT 1 + `.pipe( + NodeSqliteClient.readOnly, + Effect.flatMap((rows) => decodeRows("first-steer", rows)), + Effect.map((effects) => Option.fromNullishOr(effects[0])), + Effect.mapError((cause) => + isEffectOutboxError(cause) + ? cause + : new EffectOutboxError({ operation: "first-steer", cause }), + ), + ), cancelUnsettled: Effect.fn("EffectOutbox.cancelUnsettled")( function* ({ threadId, effectTypes, reason }) { if (effectTypes.length === 0) return []; diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 1ae3ef3b7bcb7..ee66f016e99bb 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -3365,6 +3365,135 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); }); + // A steer still pending after its run ended was never read: the provider marks one it read + // completed, and one Stop dropped cancelled. It runs next, in its place among waiting messages. + const requeueUnreadSteers = Effect.fn("Orchestrator.requeueUnreadSteers")(function* ( + threadId: ThreadId, + runIds?: ReadonlyArray, + ) { + const { turnItems } = yield* projectionStore.getThreadRecords(threadId, ["turnItems"], { + turnItemTypes: ["user_message"], + turnItemStatuses: ["pending"], + ...(runIds === undefined ? {} : { turnItemRunIds: runIds }), + }); + const unread = turnItems + .filter( + (item) => + item.type === "user_message" && + (item.inputIntent === "steer" || item.inputIntent === "promoted_queued_to_steer"), + ) + .toSorted((left, right) => left.ordinal - right.ordinal); + if (unread.length === 0) return; + const projection = yield* projectionStore.getThreadRecords(threadId, ["runs", "messages"], { + messageIds: unread.flatMap((item) => (item.type === "user_message" ? [item.messageId] : [])), + }); + for (const item of unread) { + const run = projection.runs.find((candidate) => candidate.id === item.runId); + const message = projection.messages.find( + (candidate) => + item.type === "user_message" && + candidate.id === item.messageId && + candidate.runId === item.runId, + ); + if (run === undefined || message === undefined || isActiveRun(run)) continue; + // Stop drops a steer it reached; say so, as the adapter does for steers it still held. + if (yield* projectionStore.hasRunInterruptRequest(threadId, run.id)) { + const now = yield* DateTime.now; + yield* writeSystemEvents([ + { + type: "turn-item.updated", + threadId, + runId: run.id, + ...(item.nodeId === null ? {} : { nodeId: item.nodeId }), + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { ...item, status: "cancelled" as const, completedAt: now, updatedAt: now }, + }, + { + type: "turn-item.updated", + threadId, + runId: run.id, + ...(item.nodeId === null ? {} : { nodeId: item.nodeId }), + providerInstanceId: run.providerInstanceId, + occurredAt: now, + payload: { + id: idAllocator.derive.runSignalTurnItem({ + runId: run.id, + signal: `unread-steer:${message.id}`, + }), + threadId, + runId: run.id, + nodeId: item.nodeId, + providerThreadId: item.providerThreadId ?? null, + providerTurnId: item.providerTurnId ?? null, + nativeItemRef: null, + parentItemId: null, + ordinal: item.ordinal, + type: "system_notice" as const, + status: "completed" as const, + title: "Steer delivery not confirmed", + message: `The agent did not confirm reading your steer before Stop. It may not have been delivered. Resend it if needed: "${message.text}"`, + startedAt: now, + completedAt: now, + updatedAt: now, + }, + }, + ]); + continue; + } + // The message's first steer effect recorded which runs were queued before it was sent; a + // queued message that was promoted also stays behind only the runs queued before its own. + const steer = Option.getOrUndefined( + yield* effectOutbox.firstSteer(threadId, message.id), + )?.request; + const steeredAfter = + steer?.type === "provider-turn.steer" ? steer.steerFollowUpAfterRunOrdinal : undefined; + yield* dispatchWithReceiptEffect({ + type: "message.dispatch", + commandId: CommandId.make(`command:unread-steer:${run.id}:${message.id}`), + threadId, + messageId: message.id, + steerFollowUpOfRunId: run.id, + steerFollowUpAfterRunOrdinal: Math.max( + 0, + Math.min( + steeredAfter ?? Math.max(...projection.runs.map((candidate) => candidate.ordinal)), + ...projection.runs.flatMap((candidate) => + candidate.userMessageId === message.id ? [candidate.ordinal - 1] : [], + ), + ), + ), + modelSelection: + steer?.type === "provider-turn.steer" && steer.modelSelection !== undefined + ? steer.modelSelection + : run.modelSelection, + text: message.text, + ...(message.context ? { context: message.context } : {}), + attachments: message.attachments, + ...(message.delegatedCompletion === undefined + ? {} + : { delegatedCompletion: message.delegatedCompletion }), + ...(message.notification === undefined ? {} : { notification: message.notification }), + dispatchMode: { type: "queue_after_active" }, + createdBy: message.createdBy, + creationSource: message.creationSource, + ...(message.scheduledTaskId === undefined + ? {} + : { scheduledTaskId: message.scheduledTaskId }), + ...(message.senderThreadId === undefined ? {} : { senderThreadId: message.senderThreadId }), + ...(message.linkedSender === undefined ? {} : { linkedSender: message.linkedSender }), + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to requeue an unread steer", { + threadId, + messageId: message.id, + cause, + }), + ), + ); + } + }); + const resumeQueuedRuns = Effect.gen(function* () { const threadIds = yield* projectionStore.getRecoveryThreadIds("queued-runs"); let resumed = 0; @@ -7575,7 +7704,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio projection.thread.worktreePath === null ? latestRun : undefined; - const queueBehindRun = activeRun ?? worktreeMissingRun; + // A steer whose run already ended still keeps its place in the queue. + const steerFollowUpSource = + command.steerFollowUpOfRunId === undefined + ? undefined + : projection.runs.find((run) => run.id === command.steerFollowUpOfRunId); + const queueBehindRun = activeRun ?? worktreeMissingRun ?? steerFollowUpSource; const pendingMergeBackTransfers = pendingMergeBackTransfersForThread(projection); const startsOrQueuesRun = dispatchMode.type === "defer_start" || @@ -7588,6 +7722,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const incomingMessage = { ...command, delegatedCompletion }; if ( shouldQueue && + // A steer whose run ended keeps the thread's selection, as it did before it queued. + queueBehindRun !== steerFollowUpSource && steerWhenReadyRunId === undefined && command.modelSelection === undefined && queuedRunStop === undefined && @@ -7774,7 +7910,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio activeAttemptId: attemptId, status: "queued", ...(steerWhenReadyRunId === undefined ? {} : { steerWhenReadyRunId }), + // A restart cancels its run; nobody knows whether the provider read the steer, so a person decides. ...(worktreeMissingRun !== undefined || + steerFollowUpSource?.status === "cancelled" || (heldRunsToRelease.length === 0 && queueIsHeld && !wakeSkipsHold && @@ -15589,15 +15727,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // The run-end release can lag behind a new send; start the queue first so the send waits behind it. // A restart continuation resumes the ended run, so it must not be overtaken by the queue. + // A steer follow-up takes its place first and starts the queue after it commits. A send that + // beats the run-end reaction places the ended run's unread steers before it starts anything. if ( command.type === "message.dispatch" && command.restartContinuationOfRunId === undefined && + command.steerFollowUpOfRunId === undefined && (command.dispatchMode.type === "start_immediately" || command.dispatchMode.type === "queue_after_active" || command.dispatchMode.type === "defer_start") ) { yield* mapDispatchError(command)( - startNextQueuedRun(command.threadId, { latestRunEnded: true }), + requeueUnreadSteers(command.threadId).pipe( + Effect.andThen(startNextQueuedRun(command.threadId, { latestRunEnded: true })), + ), ); } @@ -15814,6 +15957,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio yield* mapDispatchError(command)(offerDelegatedCompletionDeliveries(command.parentThreadId)); } + if (command.type === "message.dispatch" && command.steerFollowUpOfRunId !== undefined) { + yield* mapDispatchError(command)( + startNextQueuedRun(command.threadId, { latestRunEnded: true }), + ); + } + return { sequence: committed.receipt.resultSequence, storedEvents: committed.storedEvents, @@ -15913,6 +16062,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ? releaseUnattendedHolds(threadId, run.id) : Effect.void ).pipe( + Effect.andThen( + requeueUnreadSteers(threadId, [run.id]).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to read unread steers", { threadId, cause }), + ), + ), + ), Effect.andThen( startNextQueuedRun(threadId, { endedRunId: run.id, @@ -16182,6 +16338,27 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio }), ), ); + // Recovery leaves a steer the provider had not read pending, and no run update follows it. + yield* projectionStore.getRecoveryThreadIds("unread-steers").pipe( + Effect.flatMap((threadIds) => + Effect.forEach( + threadIds, + (threadId) => + threadDispatch.withLock(threadId, requeueUnreadSteers(threadId)).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to requeue an unread steer during recovery", { + threadId, + cause, + }), + ), + ), + { discard: true }, + ), + ), + Effect.catchCause((cause) => + Effect.logWarning("Failed to inspect unread steers during recovery", { cause }), + ), + ); }); const delegatedTaskResultPending = Effect.fn("Orchestrator.delegatedTaskResultPending")( diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index f3ac98ca9c252..6e64d2558164d 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -179,7 +179,8 @@ export type ProjectionRecoveryKind = | "runtime" | "restart-continuations" | "subagent-results" - | "delegated-completions"; + | "delegated-completions" + | "unread-steers"; export type ProjectionLimitRecoveryCandidate = Pick< OrchestrationV2ThreadShell, @@ -4968,6 +4969,16 @@ export const layer: Layer.Layer = AND active.status IN ('preparing', 'starting', 'running', 'waiting') ) `; + case "unread-steers": + return sql` + SELECT item.thread_id FROM orchestration_v2_projection_turn_items AS item + JOIN orchestration_v2_projection_runs AS run ON run.run_id = item.run_id + WHERE item.type = 'user_message' AND item.status = 'pending' + AND run.status IN ('completed', 'interrupted', 'failed', 'cancelled') + AND CASE WHEN json_valid(item.payload_json) + THEN json_extract(item.payload_json, '$.inputIntent') IN ('steer', 'promoted_queued_to_steer') + ELSE 0 END + `; case "delegated-completions": return sql` SELECT thread_id FROM orchestration_v2_projection_runs diff --git a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts index 0cd4377a23b3d..3a3466dfca559 100644 --- a/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts +++ b/apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts @@ -778,6 +778,13 @@ export const make = Effect.gen(function* () { !isAppOwnedDelegationItem(candidate) && // A link card waits on the user, not the run, and answers by message. candidate.type !== "link_request" && + // The orchestrator queues a steer the provider never reported reading. + !( + candidate.type === "user_message" && + candidate.status === "pending" && + (candidate.inputIntent === "steer" || + candidate.inputIntent === "promoted_queued_to_steer") + ) && (candidate.status === "pending" || candidate.status === "running" || candidate.status === "waiting"), diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index 5d4295a942638..4842885d9aa3f 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -89,6 +89,15 @@ Claude Code holds the turn until that window reopens, so it can keep showing as working. Wait for the reset, or stop the turn and continue later. The warning's timestamp shows when the displayed wait started. +## Steering + +A steer waits until Claude finishes the tool calls it is running, then Claude reads it +in the same turn. The message shows as unread until then. If Claude drops it before +reading it, the message is sent as the next turn, after any messages queued before it. +If Claude exits or the server restarts first, the message waits in the queue in that +same place until you resume it. If you press Stop, T3 Code shows a notice with the text +of any steer Claude had not read. + ## Skills Claude skills come from the config directory's `skills` folder and the project's From 22a4d3c81f00a01773d693728fb51b608d5ef13b Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 07:53:27 +0000 Subject: [PATCH 6/7] test(server): drop a steer-priority test the existing assertions already cover Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 51 ------------------- 1 file changed, 51 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index db23684f54662..5db86b4635658 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -5756,57 +5756,6 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); - it.effect("steering does not hand Claude an input that cancels the running tool calls", () => - Effect.gen(function* () { - const harness = yield* makeWakeHarness; - const input = makeClaudeTestTurnInput({ - threadId: harness.threadId, - providerThread: harness.providerThread, - now: yield* DateTime.now, - attemptId: RunAttemptId.make("steer-priority"), - text: "Run the slow commands", - attachments: [], - }); - yield* harness.runtime.startTurn(input); - const idAllocator = yield* IdAllocator.IdAllocatorV2; - const providerTurnId = idAllocator.derive.providerTurn({ - driver: ClaudeAdapterV2.CLAUDE_PROVIDER, - nativeTurnId: `turn:${input.attemptId}`, - }); - for (const [createdBy, creationSource] of [ - ["user", "web"], - ["agent", "mcp"], - ] as const) { - yield* harness.runtime.steerTurn({ - threadId: harness.threadId, - runId: input.runId, - providerThread: harness.providerThread, - providerTurnId, - message: { - createdBy, - creationSource, - messageId: MessageId.make(`steer-priority-${createdBy}`), - text: "Progress note, nothing to change.", - attachments: [], - }, - }); - } - // Claude Code aborts in-flight and waiting tool calls for a "now" input and - // reports the waiting ones as "The user doesn't want to take this action". - assert.notEqual(harness.offeredMessages[1]?.priority, "now"); - assert.notEqual(harness.offeredMessages[2]?.priority, "now"); - }).pipe( - Effect.provide( - Layer.mergeAll( - IdAllocator.layer, - McpProviderSessions.layer, - NodeServices.layer, - NodeCrypto.layer, - ), - ), - ), - ); - // regression: #29750 Claude sets a goal only from a prompt that opens with /goal it("keeps a /goal that mentions a skill as one native goal command", () => { const message = ClaudeAdapterV2.makeClaudeUserMessage({ From a1eea3e7b58a9dced598e023d60fb5f19cafae36 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Thu, 19 Nov 2026 08:02:28 +0000 Subject: [PATCH 7/7] fix(server): a dropped Claude steer frees its files and notes, and keeps its queue place When Claude drops a steer unread, refund its PDF budget and restore the turn's delivered app notes, so the follow-up turn sends both again. Keep a held root result's result-only reply next to the steer's. Requeue several unread steers in queue-placement order. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/ClaudeAdapterV2.test.ts | 71 ++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 72 +++++++++++++++---- .../src/orchestration-v2/Orchestrator.ts | 51 +++++++------ 3 files changed, 157 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 5db86b4635658..fe7559f603aaa 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -6158,6 +6158,77 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect("keeps both result-only replies of a steered turn", () => + Effect.gen(function* () { + const harness = yield* makeWakeHarness; + const idAllocator = yield* IdAllocator.IdAllocatorV2; + const attemptId = RunAttemptId.make("attempt-steer-result-only"); + const input = makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId, + text: "Run the build.", + attachments: [], + }); + yield* harness.runtime.startTurn(input); + yield* harness.runtime.steerTurn({ + threadId: harness.threadId, + runId: input.runId, + providerThread: harness.providerThread, + providerTurnId: idAllocator.derive.providerTurn({ + driver: ClaudeAdapterV2.CLAUDE_PROVIDER, + nativeTurnId: `turn:${attemptId}`, + }), + message: { + createdBy: "user", + creationSource: "web", + messageId: MessageId.make("message-steer-result-only"), + text: "Steer", + attachments: [], + }, + }); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002510", result: "Built." }), + user_message_uuid: harness.promptUuid(0), + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + type: "command_lifecycle", + command_uuid: harness.promptUuid(1), + state: "started", + uuid: "00000000-0000-4000-8000-000000002511", + session_id: WAKE_NATIVE_SESSION, + }), + ); + yield* harness.offerAndWait( + claudeSdkFrame({ + ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002512", result: "Done." }), + user_message_uuid: harness.promptUuid(1), + }), + ); + yield* harness.awaitTerminal(1); + const replies = harness.events.flatMap((event) => + event.type === "message.updated" && event.message.role === "assistant" + ? [event.message.text] + : [], + ); + assert.equal(replies.at(-1), "Built.\n\nDone."); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // Claude can answer a steer while its offer is still being logged. it.effect("settles a turn whose result echoes only a steer before the offer returns", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index e5ae05796d27e..6f62baaa5083b 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -3020,6 +3020,9 @@ const makeClaudeAttachmentBudget = (used?: { pagesUsed: number; bytesUsed: numbe }, }); +const joinFallbackText = (earlier: string, current: string) => + earlier.length === 0 ? current : current.length === 0 ? earlier : `${earlier}\n\n${current}`; + const reserveClaudePdfBudget = ( budget: ReturnType, persist: Effect.Effect, @@ -3030,6 +3033,7 @@ const reserveClaudePdfBudget = ( pages: 0, bytes: 0, delivered: false, + refunded: false, commit() { if (this.delivered) return; this.delivered = true; @@ -3038,6 +3042,13 @@ const reserveClaudePdfBudget = ( budget.committed.pages += this.pages; budget.committed.bytes += this.bytes; }, + // Claude dropped the message unread, so its files never entered the session. + refund() { + if (!this.delivered || this.refunded) return; + this.refunded = true; + budget.committed.pages -= this.pages; + budget.committed.bytes -= this.bytes; + }, })), (reservation) => Effect.sync(() => { @@ -5022,6 +5033,8 @@ interface ActiveClaudeTurnContext { readonly itemOrdinals: Map; readonly assistant: { fallbackText: string; + // Result-only replies of steered segments that ended before the current one. + earlierFallbackText: string; fallbackNativeItemId: string; emittedNativeItemIds: Set; // Text blocks stream as `${message.id}:text:${n}`; the block's snapshot has its own uuid. @@ -5116,6 +5129,9 @@ interface ActiveClaudeTurnContext { readonly messageId: MessageId; readonly text: string; readonly liveQuery: ClaudeLiveQueryContext; + readonly pdfReservation: Effect.Success>; + readonly appContextOffered: ReadonlyMap | undefined; + readonly appContextBefore: ReadonlyMap | undefined; } >; // Claude may settle a turn with a result that echoes only a steer's uuid. @@ -9246,6 +9262,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( // A held result's usage joins the steered segments once another result settles the turn. const absorbHeldResult = (context: ActiveClaudeTurnContext) => { if (context.heldResult === undefined) return; + const { assistant } = context; + if (assistant.fallbackText.length > 0) { + assistant.earlierFallbackText = joinFallbackText( + assistant.earlierFallbackText, + assistant.fallbackText, + ); + assistant.fallbackText = ""; + } context.steeredSegmentUsage.push(context.heldResult.usage); context.steeredLedgerUsage = addClaudeLedgerUsage( context.steeredLedgerUsage, @@ -9277,15 +9301,27 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( } // Claude removed the steer before reading it. Its item stays pending, so the orchestrator // sends it as the next turn once this run ends. - if ( + const dropped = lifecycle !== null && (lifecycle.state === "cancelled" || lifecycle.state === "discarded" || - lifecycle.state === "refused") && - context.pendingSteers.delete(lifecycle.uuid) && - context.pendingSteers.size === 0 && - context.heldResult !== undefined + lifecycle.state === "refused") + ? context.pendingSteers.get(lifecycle.uuid) + : undefined; + if (dropped === undefined || lifecycle === null) return; + context.pendingSteers.delete(lifecycle.uuid); + // The follow-up turn sends the same files and notes again. + if ( + dropped.appContextOffered !== undefined && + context.appContextOffered === dropped.appContextOffered ) { + context.appContextOffered = dropped.appContextBefore; + } + if (dropped.pdfReservation.delivered && !dropped.pdfReservation.refunded) { + dropped.pdfReservation.refund(); + yield* persistAttachmentBudget(context.nativeThreadId); + } + if (context.pendingSteers.size === 0 && context.heldResult !== undefined) { yield* finalizeActiveTurn({ context, status: "completed", @@ -9403,10 +9439,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( subagentToolCalls.delete(toolCall.nativeItemId); } - if ( - input.context.assistant.emittedNativeItemIds.size === 0 && - input.context.assistant.fallbackText.length > 0 - ) { + const fallbackText = joinFallbackText( + input.context.assistant.earlierFallbackText, + input.context.assistant.fallbackText, + ); + if (input.context.assistant.emittedNativeItemIds.size === 0 && fallbackText.length > 0) { const ordinal = yield* resolveItemOrdinal( input.context, input.context.assistant.fallbackNativeItemId, @@ -9416,7 +9453,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( turnInput: input.context.input, providerTurnId: input.context.providerTurnId, nativeItemId: input.context.assistant.fallbackNativeItemId, - text: input.context.assistant.fallbackText, + text: fallbackText, ordinal, startedAt: input.context.startedAt, completedAt: input.completedAt, @@ -13363,6 +13400,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( itemOrdinals: new Map(), assistant: { fallbackText: "", + earlierFallbackText: "", fallbackNativeItemId: `assistant:${turnInput.runId}`, emittedNativeItemIds: new Set(), streamBlocks: new Map(), @@ -13906,14 +13944,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( ); // `offer` may call this twice; a second call must not restore notes compaction cleared. let offerCommitted = false; + const appContextBefore = currentTurn.appContextOffered; + const appContextOffered = + userMessage === steerMessage + ? undefined + : new Map(appContext.map((entry) => [entry.key, entry.text])); const commitOffer = () => { if (offerCommitted) return; offerCommitted = true; pdfReservation.commit(); - if (userMessage !== steerMessage) { - currentTurn.appContextOffered = new Map( - appContext.map((entry) => [entry.key, entry.text]), - ); + if (appContextOffered !== undefined) { + currentTurn.appContextOffered = appContextOffered; } }; yield* backgroundForegroundSubagents(existing, backgroundDeadline); @@ -13941,6 +13982,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( messageId, text: turnInput.message.text, liveQuery: existing, + pdfReservation, + appContextOffered, + appContextBefore, }); yield* Ref.update(steeredTurns, (current) => { const next = new Set(current); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 7df5fe03505a9..c71addfa57c07 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -3384,17 +3384,16 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio turnItemStatuses: ["pending"], ...(runIds === undefined ? {} : { turnItemRunIds: runIds }), }); - const unread = turnItems - .filter( - (item) => - item.type === "user_message" && - (item.inputIntent === "steer" || item.inputIntent === "promoted_queued_to_steer"), - ) - .toSorted((left, right) => left.ordinal - right.ordinal); + const unread = turnItems.filter( + (item) => + item.type === "user_message" && + (item.inputIntent === "steer" || item.inputIntent === "promoted_queued_to_steer"), + ); if (unread.length === 0) return; const projection = yield* projectionStore.getThreadRecords(threadId, ["runs", "messages"], { messageIds: unread.flatMap((item) => (item.type === "user_message" ? [item.messageId] : [])), }); + const placed = []; for (const item of unread) { const run = projection.runs.find((candidate) => candidate.id === item.runId); const message = projection.messages.find( @@ -3451,30 +3450,36 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } // The message's first steer effect recorded which runs were queued before it was sent; a // queued message that was promoted also stays behind only the runs queued before its own. - const steer = Option.getOrUndefined( + const firstSteer = Option.getOrUndefined( yield* effectOutbox.firstSteer(threadId, message.id), )?.request; - const steeredAfter = - steer?.type === "provider-turn.steer" ? steer.steerFollowUpAfterRunOrdinal : undefined; + const steer = firstSteer?.type === "provider-turn.steer" ? firstSteer : undefined; + const afterRunOrdinal = Math.max( + 0, + Math.min( + steer?.steerFollowUpAfterRunOrdinal ?? + Math.max(...projection.runs.map((candidate) => candidate.ordinal)), + ...projection.runs.flatMap((candidate) => + candidate.userMessageId === message.id ? [candidate.ordinal - 1] : [], + ), + ), + ); + placed.push({ item, run, message, steer, afterRunOrdinal }); + } + // Each requeue starts the queue once it commits, so earlier places go first. + placed.sort( + (left, right) => + left.afterRunOrdinal - right.afterRunOrdinal || left.item.ordinal - right.item.ordinal, + ); + for (const { run, message, steer, afterRunOrdinal } of placed) { yield* dispatchWithReceiptEffect({ type: "message.dispatch", commandId: CommandId.make(`command:unread-steer:${run.id}:${message.id}`), threadId, messageId: message.id, steerFollowUpOfRunId: run.id, - steerFollowUpAfterRunOrdinal: Math.max( - 0, - Math.min( - steeredAfter ?? Math.max(...projection.runs.map((candidate) => candidate.ordinal)), - ...projection.runs.flatMap((candidate) => - candidate.userMessageId === message.id ? [candidate.ordinal - 1] : [], - ), - ), - ), - modelSelection: - steer?.type === "provider-turn.steer" && steer.modelSelection !== undefined - ? steer.modelSelection - : run.modelSelection, + steerFollowUpAfterRunOrdinal: afterRunOrdinal, + modelSelection: steer?.modelSelection ?? run.modelSelection, text: message.text, ...(message.context ? { context: message.context } : {}), attachments: message.attachments,