diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index ec2873f387fe..92d5adb89bcf 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -2477,7 +2477,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 [ @@ -5093,7 +5093,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}` }, @@ -5110,6 +5110,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({ @@ -5184,7 +5235,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", @@ -5362,7 +5413,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", @@ -5386,7 +5477,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, }); @@ -7023,7 +7114,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 afa0925fbb4c..9961abd557fb 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -10899,6 +10899,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); @@ -12529,7 +12544,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, @@ -12656,7 +12671,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 faa8d8b8b3cb..09d2b4bad68c 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.scoped( Effect.gen(function* () { @@ -407,7 +407,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) => @@ -418,7 +418,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(); @@ -451,15 +450,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 a1cacf97d800..157d98d0162d 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"}}