diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index c73956d3aa74f..fe7559f603aaa 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}` }, @@ -5830,7 +5830,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", @@ -6008,7 +6008,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", @@ -6026,13 +6066,176 @@ 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, + ), + ), + ), + ); + + 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* () { 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, }); @@ -8187,7 +8390,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 26e9b9fadd2cd..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,10 +5129,16 @@ 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. 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; } @@ -9240,6 +9259,25 @@ 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; + 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, + resultLedgerUsage.get(context.heldResult), + ); + context.heldResult = undefined; + }; + const markSteersAccepted = Effect.fnUntraced(function* ( context: ActiveClaudeTurnContext, message: SDKMessage, @@ -9257,8 +9295,40 @@ 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. + const dropped = + lifecycle !== null && + (lifecycle.state === "cancelled" || + lifecycle.state === "discarded" || + 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", + completedAt: yield* DateTime.now, + result: context.heldResult, + }); + } }); const finalizeActiveTurn = Effect.fnUntraced(function* (requested: { @@ -9288,10 +9358,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, @@ -9365,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, @@ -9378,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, @@ -11887,6 +11962,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; @@ -12001,13 +12077,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 }), @@ -13312,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(), @@ -13359,6 +13448,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* ( heldRootFrames: [], pendingSteers: new Map(), steerUuids: new Set(), + heldResult: undefined, executedModel: undefined, }; const attachTurn = Effect.gen(function* () { @@ -13702,7 +13792,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, @@ -13832,7 +13922,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, @@ -13853,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); @@ -13888,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/ClaudeAutomaticDelivery.integration.test.ts b/apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts index 1fa7047aff428..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, @@ -134,7 +135,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 +404,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 +415,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 +447,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") { @@ -1034,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/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 4342ba684b5c7..c71addfa57c07 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -3373,6 +3373,140 @@ 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"), + ); + 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( + (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 firstSteer = Option.getOrUndefined( + yield* effectOutbox.firstSteer(threadId, message.id), + )?.request; + 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: afterRunOrdinal, + modelSelection: 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; @@ -7576,7 +7710,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" || @@ -7589,6 +7728,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 && @@ -7775,7 +7916,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 && @@ -15625,15 +15768,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 })), + ), ); } @@ -15850,6 +15998,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, @@ -15955,6 +16109,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, @@ -16224,6 +16385,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 94cd70fd05fd3..f945d82b75105 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -185,7 +185,8 @@ export type ProjectionRecoveryKind = | "runtime" | "restart-continuations" | "subagent-results" - | "delegated-completions"; + | "delegated-completions" + | "unread-steers"; export type ProjectionLimitRecoveryCandidate = Pick< OrchestrationV2ThreadShell, @@ -5055,6 +5056,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.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)); }); 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/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"}} 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