@devries-cameron20 / t3code-1 / commits / e8c4824b70
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): an unread Claude steer no longer hangs the turn or gets lost (#39018)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Alb11747 committed Nov 19, 2026 at 03:37 UTC e8c4824b70f3ea89b4dfb6cd98b6e17adade50cf
10 files changed +886 -41
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+208 -5
@@ -2636,7 +2636,7 @@ describe("ClaudeAdapterV2 attachments", () => {
2636 },
2637 });
2638
2639 - assert.equal(offeredMessages[1]?.priority, "now");
2639 + assert.equal(offeredMessages[1]?.priority, "next");
2640 assert.deepEqual(offeredMessages[1]?.message.content, expectedContent);
2641 const documentPath = path.join(attachmentsDir, attachmentRelativePath(document)!);
2642 for (const scenario of [
@@ -5739,7 +5739,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
5739 },
5740 });
5741 const attachmentNote = `\n\n[Attached file "requirements.pdf" is saved at: ${path.join(harness.attachmentsDir, attachmentRelativePath(attachment)!)}]`;
5742 - assert.equal(harness.offeredMessages[1]?.priority, "now");
5742 + assert.equal(harness.offeredMessages[1]?.priority, "next");
5743 assert.deepEqual(harness.offeredMessages[1]?.message.content, [
5744 { type: "text", text: `${leadingText}${attachmentNote}` },
5745 { type: "text", text: `/implement the fixes${attachmentNote}` },
@@ -5830,7 +5830,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
5830 },
5831 }),
5832 );
5833 - // Past task_started the CLI queues a "now" steer until the call returns.
5833 + // Past task_started the CLI queues a steer until the call returns.
5834 yield* harness.offerAndWait(
5835 claudeSdkFrame({
5836 type: "system",
@@ -6008,7 +6008,47 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6008 user_message_uuid: harness.promptUuid(0),
6009 }),
6010 );
6011 + // Claude answers the unread steer as its next native turn, which belongs to this turn.
6012 + assert.equal(harness.terminalEvents().length, 0);
6013 + yield* expectSteers({
6014 + "message-steer-read": "completed",
6015 + "message-steer-unread": "pending",
6016 + });
6017 + const decision = yield* Effect.promise(() =>
6018 + harness.getOpenedOptions()!.canUseTool!(
6019 + "Read",
6020 + { file_path: "README.md" },
6021 + {
6022 + signal: new AbortController().signal,
6023 + toolUseID: "steer-read",
6024 + requestId: "request-steer-read",
6025 + },
6026 + ),
6027 + ).pipe(Effect.forkScoped);
6028 + const first = yield* Effect.raceFirst(
6029 + Queue.take(harness.runtimeRequestReceipts).pipe(Effect.as("request")),
6030 + Fiber.join(decision).pipe(Effect.map((result) => result?.behavior)),
6031 + );
6032 + assert.notEqual(first, "deny");
6033 + yield* harness.offerAndWait(
6034 + makeAssistantTextFrame({
6035 + uuid: "00000000-0000-4000-8000-000000002397",
6036 + text: "Steer reply.",
6037 + }),
6038 + );
6039 + yield* harness.offerAndWait(
6040 + claudeSdkFrame({
6041 + ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002398", result: "Done." }),
6042 + user_message_uuid: harness.promptUuid(2),
6043 + }),
6044 + );
6045 yield* harness.awaitTerminal(1);
6046 + assert.equal(harness.terminalEvents()[0]?.status, "completed");
6047 + assert.ok(
6048 + harness.events.some(
6049 + (event) => event.type === "message.updated" && event.message.text === "Steer reply.",
6050 + ),
6051 + );
6052 yield* expectSteers({
6053 "message-steer-read": "completed",
6054 "message-steer-unread": "completed",
@@ -6026,13 +6066,176 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6066 ),
6067 );
6068
6069 + // A steer Claude starts after holding the result answers in this turn, so dropping another
6070 + // steer then must not end the turn under it.
6071 + it.effect("keeps the turn open for a started steer when Claude drops another", () =>
6072 + Effect.gen(function* () {
6073 + const harness = yield* makeWakeHarness;
6074 + const idAllocator = yield* IdAllocator.IdAllocatorV2;
6075 + const attemptId = RunAttemptId.make("attempt-steer-dropped");
6076 + const input = makeClaudeTestTurnInput({
6077 + threadId: harness.threadId,
6078 + providerThread: harness.providerThread,
6079 + now: yield* DateTime.now,
6080 + attemptId,
6081 + text: "Run the build.",
6082 + attachments: [],
6083 + });
6084 + yield* harness.runtime.startTurn(input);
6085 + for (const id of ["message-steer-started", "message-steer-dropped"]) {
6086 + yield* harness.runtime.steerTurn({
6087 + threadId: harness.threadId,
6088 + runId: input.runId,
6089 + providerThread: harness.providerThread,
6090 + providerTurnId: idAllocator.derive.providerTurn({
6091 + driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
6092 + nativeTurnId: `turn:${attemptId}`,
6093 + }),
6094 + message: {
6095 + createdBy: "user",
6096 + creationSource: "web",
6097 + messageId: MessageId.make(id),
6098 + text: `Steer ${id}`,
6099 + attachments: [],
6100 + },
6101 + });
6102 + }
6103 + const lifecycle = (index: number, state: string, uuid: string) =>
6104 + harness.offerAndWait(
6105 + claudeSdkFrame({
6106 + type: "command_lifecycle",
6107 + command_uuid: harness.promptUuid(index),
6108 + state,
6109 + uuid,
6110 + session_id: WAKE_NATIVE_SESSION,
6111 + }),
6112 + );
6113 + yield* harness.offerAndWait(
6114 + claudeSdkFrame({
6115 + ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002500", result: "Built." }),
6116 + user_message_uuid: harness.promptUuid(0),
6117 + }),
6118 + );
6119 + yield* lifecycle(1, "started", "00000000-0000-4000-8000-000000002501");
6120 + yield* lifecycle(2, "cancelled", "00000000-0000-4000-8000-000000002502");
6121 + yield* harness.offerAndWait(
6122 + makeAssistantTextFrame({
6123 + uuid: "00000000-0000-4000-8000-000000002503",
6124 + text: "Steer reply.",
6125 + }),
6126 + );
6127 + yield* harness.offerAndWait(
6128 + claudeSdkFrame({
6129 + ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002504", result: "Done." }),
6130 + user_message_uuid: harness.promptUuid(1),
6131 + }),
6132 + );
6133 + yield* harness.awaitTerminal(1);
6134 + const reply = harness.events.find(
6135 + (event) => event.type === "message.updated" && event.message.text === "Steer reply.",
6136 + );
6137 + assert.equal(reply?.type === "message.updated" ? reply.message.runId : null, input.runId);
6138 + assert.deepEqual(
6139 + harness.events.flatMap((event) =>
6140 + event.type === "steer.updated" ? [[event.messageId, event.status]] : [],
6141 + ),
6142 + [
6143 + ["message-steer-started", "pending"],
6144 + ["message-steer-dropped", "pending"],
6145 + ["message-steer-started", "completed"],
6146 + ],
6147 + );
6148 + }).pipe(
6149 + Effect.scoped,
6150 + Effect.provide(
6151 + Layer.mergeAll(
6152 + IdAllocator.layer,
6153 + McpProviderSessions.layer,
6154 + NodeServices.layer,
6155 + NodeCrypto.layer,
6156 + ),
6157 + ),
6158 + ),
6159 + );
6160 +
6161 + it.effect("keeps both result-only replies of a steered turn", () =>
6162 + Effect.gen(function* () {
6163 + const harness = yield* makeWakeHarness;
6164 + const idAllocator = yield* IdAllocator.IdAllocatorV2;
6165 + const attemptId = RunAttemptId.make("attempt-steer-result-only");
6166 + const input = makeClaudeTestTurnInput({
6167 + threadId: harness.threadId,
6168 + providerThread: harness.providerThread,
6169 + now: yield* DateTime.now,
6170 + attemptId,
6171 + text: "Run the build.",
6172 + attachments: [],
6173 + });
6174 + yield* harness.runtime.startTurn(input);
6175 + yield* harness.runtime.steerTurn({
6176 + threadId: harness.threadId,
6177 + runId: input.runId,
6178 + providerThread: harness.providerThread,
6179 + providerTurnId: idAllocator.derive.providerTurn({
6180 + driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
6181 + nativeTurnId: `turn:${attemptId}`,
6182 + }),
6183 + message: {
6184 + createdBy: "user",
6185 + creationSource: "web",
6186 + messageId: MessageId.make("message-steer-result-only"),
6187 + text: "Steer",
6188 + attachments: [],
6189 + },
6190 + });
6191 + yield* harness.offerAndWait(
6192 + claudeSdkFrame({
6193 + ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002510", result: "Built." }),
6194 + user_message_uuid: harness.promptUuid(0),
6195 + }),
6196 + );
6197 + yield* harness.offerAndWait(
6198 + claudeSdkFrame({
6199 + type: "command_lifecycle",
6200 + command_uuid: harness.promptUuid(1),
6201 + state: "started",
6202 + uuid: "00000000-0000-4000-8000-000000002511",
6203 + session_id: WAKE_NATIVE_SESSION,
6204 + }),
6205 + );
6206 + yield* harness.offerAndWait(
6207 + claudeSdkFrame({
6208 + ...makeResultFrame({ uuid: "00000000-0000-4000-8000-000000002512", result: "Done." }),
6209 + user_message_uuid: harness.promptUuid(1),
6210 + }),
6211 + );
6212 + yield* harness.awaitTerminal(1);
6213 + const replies = harness.events.flatMap((event) =>
6214 + event.type === "message.updated" && event.message.role === "assistant"
6215 + ? [event.message.text]
6216 + : [],
6217 + );
6218 + assert.equal(replies.at(-1), "Built.\n\nDone.");
6219 + }).pipe(
6220 + Effect.scoped,
6221 + Effect.provide(
6222 + Layer.mergeAll(
6223 + IdAllocator.layer,
6224 + McpProviderSessions.layer,
6225 + NodeServices.layer,
6226 + NodeCrypto.layer,
6227 + ),
6228 + ),
6229 + ),
6230 + );
6231 +
6232 // Claude can answer a steer while its offer is still being logged.
6233 it.effect("settles a turn whose result echoes only a steer before the offer returns", () =>
6234 Effect.gen(function* () {
6235 let settleDuringOffer: (message: SDKUserMessage) => Effect.Effect<void> = () => Effect.void;
6236 const harness = yield* makeWakeHarnessWithOptions({
6237 offer: (message) =>
6035 - message.priority === "now"
6238 + message.priority === "next"
6239 ? Effect.suspend(() => settleDuringOffer(message))
6240 : Effect.void,
6241 });
@@ -8187,7 +8390,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
8390 attachments: [],
8391 },
8392 });
8190 - assert.equal(harness.offeredMessages[1]?.priority, "now");
8393 + assert.equal(harness.offeredMessages[1]?.priority, "next");
8394 }
8395 const partialText = "The audit covers the `integ";
8396 if (!queryExits)
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+115 -18
@@ -3020,6 +3020,9 @@ const makeClaudeAttachmentBudget = (used?: { pagesUsed: number; bytesUsed: numbe
3020 },
3021 });
3022
3023 +const joinFallbackText = (earlier: string, current: string) =>
3024 + earlier.length === 0 ? current : current.length === 0 ? earlier : `${earlier}\n\n${current}`;
3025 +
3026 const reserveClaudePdfBudget = (
3027 budget: ReturnType<typeof makeClaudeAttachmentBudget>,
3028 persist: Effect.Effect<void>,
@@ -3030,6 +3033,7 @@ const reserveClaudePdfBudget = (
3033 pages: 0,
3034 bytes: 0,
3035 delivered: false,
3036 + refunded: false,
3037 commit() {
3038 if (this.delivered) return;
3039 this.delivered = true;
@@ -3038,6 +3042,13 @@ const reserveClaudePdfBudget = (
3042 budget.committed.pages += this.pages;
3043 budget.committed.bytes += this.bytes;
3044 },
3045 + // Claude dropped the message unread, so its files never entered the session.
3046 + refund() {
3047 + if (!this.delivered || this.refunded) return;
3048 + this.refunded = true;
3049 + budget.committed.pages -= this.pages;
3050 + budget.committed.bytes -= this.bytes;
3051 + },
3052 })),
3053 (reservation) =>
3054 Effect.sync(() => {
@@ -5022,6 +5033,8 @@ interface ActiveClaudeTurnContext {
5033 readonly itemOrdinals: Map<string, number>;
5034 readonly assistant: {
5035 fallbackText: string;
5036 + // Result-only replies of steered segments that ended before the current one.
5037 + earlierFallbackText: string;
5038 fallbackNativeItemId: string;
5039 emittedNativeItemIds: Set<string>;
5040 // Text blocks stream as `${message.id}:text:${n}`; the block's snapshot has its own uuid.
@@ -5116,10 +5129,16 @@ interface ActiveClaudeTurnContext {
5129 readonly messageId: MessageId;
5130 readonly text: string;
5131 readonly liveQuery: ClaudeLiveQueryContext;
5132 + readonly pdfReservation: Effect.Success<ReturnType<typeof reserveClaudePdfBudget>>;
5133 + readonly appContextOffered: ReadonlyMap<string, string> | undefined;
5134 + readonly appContextBefore: ReadonlyMap<string, string> | undefined;
5135 }
5136 >;
5137 // Claude may settle a turn with a result that echoes only a steer's uuid.
5138 readonly steerUuids: Set<string>;
5139 + // A completed result whose turn stays open while Claude still holds a steer; it settles the
5140 + // turn if Claude drops that steer instead of starting it.
5141 + heldResult: SDKResultMessage | undefined;
5142 // Claude can run another model than requested, such as when an organization disallows it.
5143 executedModel: string | undefined;
5144 }
@@ -9240,6 +9259,25 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9259 status,
9260 });
9261
9262 + // A held result's usage joins the steered segments once another result settles the turn.
9263 + const absorbHeldResult = (context: ActiveClaudeTurnContext) => {
9264 + if (context.heldResult === undefined) return;
9265 + const { assistant } = context;
9266 + if (assistant.fallbackText.length > 0) {
9267 + assistant.earlierFallbackText = joinFallbackText(
9268 + assistant.earlierFallbackText,
9269 + assistant.fallbackText,
9270 + );
9271 + assistant.fallbackText = "";
9272 + }
9273 + context.steeredSegmentUsage.push(context.heldResult.usage);
9274 + context.steeredLedgerUsage = addClaudeLedgerUsage(
9275 + context.steeredLedgerUsage,
9276 + resultLedgerUsage.get(context.heldResult),
9277 + );
9278 + context.heldResult = undefined;
9279 + };
9280 +
9281 const markSteersAccepted = Effect.fnUntraced(function* (
9282 context: ActiveClaudeTurnContext,
9283 message: SDKMessage,
@@ -9257,8 +9295,40 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9295 const steer = context.pendingSteers.get(uuid);
9296 if (steer === undefined) continue;
9297 context.pendingSteers.delete(uuid);
9298 + // Claude now answers this steer, and that answer's result ends the turn.
9299 + absorbHeldResult(context);
9300 yield* emitSteerStatus(context, steer.messageId, "completed");
9301 }
9302 + // Claude removed the steer before reading it. Its item stays pending, so the orchestrator
9303 + // sends it as the next turn once this run ends.
9304 + const dropped =
9305 + lifecycle !== null &&
9306 + (lifecycle.state === "cancelled" ||
9307 + lifecycle.state === "discarded" ||
9308 + lifecycle.state === "refused")
9309 + ? context.pendingSteers.get(lifecycle.uuid)
9310 + : undefined;
9311 + if (dropped === undefined || lifecycle === null) return;
9312 + context.pendingSteers.delete(lifecycle.uuid);
9313 + // The follow-up turn sends the same files and notes again.
9314 + if (
9315 + dropped.appContextOffered !== undefined &&
9316 + context.appContextOffered === dropped.appContextOffered
9317 + ) {
9318 + context.appContextOffered = dropped.appContextBefore;
9319 + }
9320 + if (dropped.pdfReservation.delivered && !dropped.pdfReservation.refunded) {
9321 + dropped.pdfReservation.refund();
9322 + yield* persistAttachmentBudget(context.nativeThreadId);
9323 + }
9324 + if (context.pendingSteers.size === 0 && context.heldResult !== undefined) {
9325 + yield* finalizeActiveTurn({
9326 + context,
9327 + status: "completed",
9328 + completedAt: yield* DateTime.now,
9329 + result: context.heldResult,
9330 + });
9331 + }
9332 });
9333
9334 const finalizeActiveTurn = Effect.fnUntraced(function* (requested: {
@@ -9288,10 +9358,14 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9358 if (input.status === "completed" && input.context.appContextOffered !== undefined) {
9359 deliveredAppContext.set(input.context.nativeThreadId, input.context.appContextOffered);
9360 }
9291 - // A turn that completes has taken in every steer; one that stops drops them unread.
9361 + // A live Claude still runs a steer queued at a completed result, and Stop drops them unread
9362 + // with a notice below. A steer whose process exited stays pending: nothing can read it now,
9363 + // so the orchestrator sends it as the next turn.
9364 const droppedSteers = [...input.context.pendingSteers];
9365 input.context.pendingSteers.clear();
9294 - for (const [, { messageId }] of droppedSteers) {
9366 + const currentQuery = yield* Ref.get(queryContext);
9367 + for (const [, { messageId, liveQuery }] of droppedSteers) {
9368 + if (input.status !== "interrupted" && liveQuery !== currentQuery) continue;
9369 yield* emitSteerStatus(
9370 input.context,
9371 messageId,
@@ -9365,10 +9439,11 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9439 subagentToolCalls.delete(toolCall.nativeItemId);
9440 }
9441
9368 - if (
9369 - input.context.assistant.emittedNativeItemIds.size === 0 &&
9370 - input.context.assistant.fallbackText.length > 0
9371 - ) {
9442 + const fallbackText = joinFallbackText(
9443 + input.context.assistant.earlierFallbackText,
9444 + input.context.assistant.fallbackText,
9445 + );
9446 + if (input.context.assistant.emittedNativeItemIds.size === 0 && fallbackText.length > 0) {
9447 const ordinal = yield* resolveItemOrdinal(
9448 input.context,
9449 input.context.assistant.fallbackNativeItemId,
@@ -9378,7 +9453,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
9453 turnInput: input.context.input,
9454 providerTurnId: input.context.providerTurnId,
9455 nativeItemId: input.context.assistant.fallbackNativeItemId,
9381 - text: input.context.assistant.fallbackText,
9456 + text: fallbackText,
9457 ordinal,
9458 startedAt: input.context.startedAt,
9459 completedAt: input.completedAt,
@@ -11887,6 +11962,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
11962 const completedAt = yield* DateTime.now;
11963 const interrupted = (yield* Ref.get(interruptedTurns)).has(context.providerTurnId);
11964 const wasSteered = (yield* Ref.get(steeredTurns)).has(context.providerTurnId);
11965 + absorbHeldResult(context);
11966 if (!interrupted && wasSteered && isClaudeActiveSteeringAbortResult(message)) {
11967 const cutOffReply = context.assistant.lastReply;
11968 context.assistant.lastReply = null;
@@ -12001,13 +12077,25 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12077 resultFailure?.class === "usage_limit"
12078 ? { ...resultFailure, resetAt }
12079 : resultFailure;
12080 + const status = interrupted
12081 + ? "interrupted"
12082 + : limitedCompaction !== null
12083 + ? "failed"
12084 + : terminalStatusFromResult(message, failureHint);
12085 + // Claude answers a steer it has not read yet as the next native turn, which echoes
12086 + // the steer. A result without echoes cannot prove that turn will come.
12087 + if (
12088 + status === "completed" &&
12089 + terminalFailure === null &&
12090 + context.pendingSteers.size > 0 &&
12091 + claudeEchoedPromptUuids(message).length > 0
12092 + ) {
12093 + context.heldResult = message;
12094 + return;
12095 + }
12096 yield* finalizeActiveTurn({
12097 context,
12006 - status: interrupted
12007 - ? "interrupted"
12008 - : limitedCompaction !== null
12009 - ? "failed"
12010 - : terminalStatusFromResult(message, failureHint),
12098 + status,
12099 completedAt,
12100 result: message,
12101 ...(terminalFailure === null ? {} : { failure: terminalFailure }),
@@ -13312,6 +13400,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13400 itemOrdinals: new Map(),
13401 assistant: {
13402 fallbackText: "",
13403 + earlierFallbackText: "",
13404 fallbackNativeItemId: `assistant:${turnInput.runId}`,
13405 emittedNativeItemIds: new Set(),
13406 streamBlocks: new Map(),
@@ -13359,6 +13448,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13448 heldRootFrames: [],
13449 pendingSteers: new Map(),
13450 steerUuids: new Set(),
13451 + heldResult: undefined,
13452 executedModel: undefined,
13453 };
13454 const attachTurn = Effect.gen(function* () {
@@ -13702,7 +13792,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13792 ),
13793 );
13794
13705 - // Move subagents to the background before priority "now" steers cancel foreground tools.
13795 + // Move subagents to the background so a steer reaches Claude without waiting for them to finish.
13796 const backgroundForegroundSubagents = Effect.fnUntraced(function* (
13797 live: ClaudeLiveQueryContext,
13798 deadline: number,
@@ -13832,7 +13922,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13922 ).promptEffort,
13923 ),
13924 attachments: turnInput.message.attachments,
13835 - priority: "now",
13925 + // "now" makes Claude Code cancel the tool calls in flight and report them as a user refusal.
13926 + priority: "next",
13927 uuid: steerUuid,
13928 attachmentsDir,
13929 fileSystem,
@@ -13853,14 +13944,17 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13944 );
13945 // `offer` may call this twice; a second call must not restore notes compaction cleared.
13946 let offerCommitted = false;
13947 + const appContextBefore = currentTurn.appContextOffered;
13948 + const appContextOffered =
13949 + userMessage === steerMessage
13950 + ? undefined
13951 + : new Map(appContext.map((entry) => [entry.key, entry.text]));
13952 const commitOffer = () => {
13953 if (offerCommitted) return;
13954 offerCommitted = true;
13955 pdfReservation.commit();
13860 - if (userMessage !== steerMessage) {
13861 - currentTurn.appContextOffered = new Map(
13862 - appContext.map((entry) => [entry.key, entry.text]),
13863 - );
13956 + if (appContextOffered !== undefined) {
13957 + currentTurn.appContextOffered = appContextOffered;
13958 }
13959 };
13960 yield* backgroundForegroundSubagents(existing, backgroundDeadline);
@@ -13888,6 +13982,9 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13982 messageId,
13983 text: turnInput.message.text,
13984 liveQuery: existing,
13985 + pdfReservation,
13986 + appContextOffered,
13987 + appContextBefore,
13988 });
13989 yield* Ref.update(steeredTurns, (current) => {
13990 const next = new Set(current);
apps/server/src/orchestration-v2/ClaudeAutomaticDelivery.integration.test.ts
+311 -10
@@ -10,6 +10,7 @@ import {
10 NodeId,
11 ProjectId,
12 ProviderInstanceId,
13 + type RunId,
14 ScheduledTaskUpsertInput,
15 ThreadId,
16 type OrchestrationV2DomainEvent,
@@ -134,7 +135,7 @@ const deliveries = [
135 ] as const;
136
137 it.effect.each(deliveries)(
137 - "delivers %s with Claude's native pending-tool cancellation behavior",
138 + "delivers %s without Claude cancelling the pending tool calls in its batch",
139 (delivery) =>
140 Effect.gen(function* () {
141 const cwd = yield* checkpointWorkspace("claude-automatic-delivery");
@@ -403,7 +404,7 @@ it.effect.each(deliveries)(
404 yield* worker.drain();
405 const explicitSteer =
406 delivery === "user steering" || delivery === "promoted queued message";
406 - assert.equal(batchAbort.signal.aborted, explicitSteer);
407 + assert.equal(batchAbort.signal.aborted, false);
408 assert.equal(offers.length, explicitSteer ? 2 : 1);
409 const finished = yield* watch(
410 (event) =>
@@ -414,7 +415,6 @@ it.effect.each(deliveries)(
415 yield* Queue.offer(sdkMessages, toolResult("build", false));
416 for (const id of statusIds)
417 yield* Queue.offer(sdkMessages, toolResult(id, batchAbort.signal.aborted));
417 - if (explicitSteer) yield* Queue.offer(sdkMessages, result("aborted", true));
418 yield* Queue.offer(sdkMessages, result("completed", false));
419 yield* Fiber.join(finished);
420 yield* worker.drain();
@@ -447,15 +447,12 @@ it.effect.each(deliveries)(
447 );
448 assert.equal(reads.length, 4);
449 for (const read of reads) {
450 - assert.equal(read.status, explicitSteer ? "cancelled" : "completed");
451 - assert.equal(read.toolNonExecutionKind, explicitSteer ? "cancelled" : undefined);
452 - assert.equal(read.type === "dynamic_tool" && read.output === refusal, explicitSteer);
450 + assert.equal(read.status, "completed");
451 + assert.equal(read.toolNonExecutionKind, undefined);
452 + assert.equal(read.type === "dynamic_tool" && read.output === refusal, false);
453 }
454 assert.equal(offers.length, 2);
455 - assert.equal(
456 - offers.filter((offer) => offer.priority === "now").length,
457 - explicitSteer ? 1 : 0,
458 - );
455 + assert.equal(offers.filter((offer) => offer.priority === "now").length, 0);
456 if (!explicitSteer) {
457 assert.equal(after.runs.length, 2);
458 if (delivery === "child completion") {
@@ -1034,3 +1031,307 @@ it.effect("offers a continuation for a later wake after a queued continuation is
1031 ),
1032 ),
1033 );
1034 +
1035 +// A steer Claude never read runs as the next turn, between the messages sent before and after
1036 +// it, even when they share a millisecond and the later one picks another model.
1037 +it.effect.each([
1038 + "Claude cancels it twice",
1039 + "the Claude process exits",
1040 + "the server restarts",
1041 + "Claude cancels it and the user stops",
1042 +] as const)("handles an unread steer when %s", (outcome) =>
1043 + Effect.gen(function* () {
1044 + const cwd = yield* checkpointWorkspace("claude-unread-steer");
1045 + const sdkMessages = yield* Queue.unbounded<SDKMessage>();
1046 + const offers: SDKUserMessage[] = [];
1047 + const adapter = yield* ClaudeAdapterV2.makeClaudeAdapterV2({
1048 + instanceId: modelSelection.instanceId,
1049 + settings,
1050 + environment: {},
1051 + attachmentsDir: cwd,
1052 + fileSystem: yield* FileSystem.FileSystem,
1053 + path: yield* Path.Path,
1054 + random: yield* SecureRandom.SecureRandom,
1055 + idAllocator: yield* IdAllocator.IdAllocatorV2,
1056 + queryRunner: {
1057 + allocateSessionId: Effect.succeed(sessionId),
1058 + open: () =>
1059 + Effect.succeed({
1060 + messages: Stream.fromQueue(sdkMessages),
1061 + offer: (message) => Effect.sync(() => void offers.push(message)),
1062 + setModel: () => Effect.void,
1063 + applyFlagSettings: () => Effect.void,
1064 + setPermissionMode: () => Effect.void,
1065 + renameSession: () => Effect.void,
1066 + backgroundTasks: () => Effect.succeed(false),
1067 + mcpServerStatus: Effect.succeed([]),
1068 + readMcpResource: () => Effect.die("unexpected MCP resource read"),
1069 + callMcpTool: () => Effect.die("unexpected MCP tool call"),
1070 + listPermissionRules: Effect.die("unexpected permission rules read"),
1071 + stopTask: () => Effect.void,
1072 + interrupt: Queue.shutdown(sdkMessages),
1073 + close: Effect.void,
1074 + }),
1075 + forkSession: () => Effect.die("unused"),
1076 + subagentLaunchToolUseId: () => Effect.succeed(null),
1077 + subagentModel: () => Effect.succeed(null),
1078 + assertComplete: Effect.void,
1079 + },
1080 + });
1081 + yield* Effect.gen(function* () {
1082 + const orchestrator = yield* Orchestrator.OrchestratorV2;
1083 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1084 + const threadId = ThreadId.make("thread:unread-steer");
1085 + const steerId = MessageId.make("steer");
1086 + const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
1087 + orchestrator.streamDomainEvents.pipe(
1088 + Stream.filter(predicate),
1089 + Stream.take(1),
1090 + Stream.runDrain,
1091 + Effect.forkScoped,
1092 + );
1093 + const settled = (runId: RunId, status: "waiting") =>
1094 + watch(
1095 + (event) =>
1096 + event.type === "run.updated" &&
1097 + event.payload.id === runId &&
1098 + event.payload.status === status,
1099 + );
1100 + const pending = () =>
1101 + watch(
1102 + (event) =>
1103 + event.type === "turn-item.updated" &&
1104 + event.payload.type === "user_message" &&
1105 + event.payload.messageId === steerId &&
1106 + event.payload.status === "pending",
1107 + );
1108 + const answer = (offer: SDKUserMessage) =>
1109 + Queue.offer(
1110 + sdkMessages,
1111 + frame({
1112 + ...(result(`result-${offer.uuid}`, false) as object),
1113 + user_message_uuid: offer.uuid,
1114 + }),
1115 + );
1116 + const cancel = (offer: SDKUserMessage) =>
1117 + Queue.offer(
1118 + sdkMessages,
1119 + frame({
1120 + type: "command_lifecycle",
1121 + command_uuid: offer.uuid,
1122 + state: "cancelled",
1123 + uuid: `cancelled-${offer.uuid}`,
1124 + session_id: sessionId,
1125 + }),
1126 + );
1127 + const offeredText = (offer: SDKUserMessage | undefined) =>
1128 + JSON.stringify(offer?.message.content ?? null);
1129 + const queued = Effect.map(orchestrator.getThreadProjection(threadId), (projection) =>
1130 + projection.runs
1131 + .filter((run) => run.status === "queued")
1132 + .toSorted(
1133 + (left, right) =>
1134 + (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal),
1135 + ),
1136 + );
1137 + const queuedOrder = Effect.map(queued, (runs) =>
1138 + runs.map((run) => [run.userMessageId, run.queueHeld === true]),
1139 + );
1140 + yield* orchestrator.dispatch({
1141 + type: "thread.create",
1142 + commandId: CommandId.make("create"),
1143 + threadId,
1144 + projectId: ProjectId.make("project:unread-steer"),
1145 + title: "Unread steer",
1146 + modelSelection,
1147 + runtimeMode: "full-access",
1148 + interactionMode: "default",
1149 + branch: null,
1150 + worktreePath: cwd,
1151 + createdBy: "user",
1152 + creationSource: "web",
1153 + });
1154 + const running = yield* watch(
1155 + (event) => event.type === "provider-turn.updated" && event.payload.status === "running",
1156 + );
1157 + const send = (
1158 + id: string,
1159 + dispatchMode:
1160 + | { readonly type: "start_immediately" | "queue_after_active" }
1161 + | { readonly type: "steer_active"; readonly targetRunId: RunId },
1162 + model?: string,
1163 + ) =>
1164 + orchestrator.dispatch({
1165 + type: "message.dispatch",
1166 + commandId: CommandId.make(id),
1167 + threadId,
1168 + messageId: MessageId.make(id),
1169 + text: `Message ${id}`,
1170 + attachments: [],
1171 + ...(model === undefined ? {} : { modelSelection: { ...modelSelection, model } }),
1172 + dispatchMode,
1173 + createdBy: "user",
1174 + creationSource: "web",
1175 + });
1176 + yield* send("first", { type: "start_immediately" });
1177 + yield* worker.drain();
1178 + yield* Fiber.join(running);
1179 + const parent = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
1180 + yield* send("before", { type: "queue_after_active" });
1181 + const unread = yield* pending();
1182 + yield* send("steer", { type: "steer_active", targetRunId: parent.id });
1183 + yield* worker.drain();
1184 + yield* Fiber.join(unread);
1185 + yield* send("after", { type: "queue_after_active" }, "claude-opus-4-1");
1186 + assert.deepEqual(
1187 + offers.map((offer) => offer.priority),
1188 + [undefined, "next"],
1189 + );
1190 +
1191 + if (outcome === "Claude cancels it twice") {
1192 + const ended = yield* settled(parent.id, "waiting");
1193 + const nextRunning = yield* watch(
1194 + (event) =>
1195 + event.type === "provider-turn.updated" &&
1196 + event.payload.status === "running" &&
1197 + event.payload.runAttemptId !== parent.activeAttemptId,
1198 + );
1199 + yield* answer(offers[0]!);
1200 + yield* cancel(offers[1]!);
1201 + yield* Fiber.join(ended);
1202 + yield* worker.drain();
1203 + yield* Fiber.join(nextRunning);
1204 + // The older message runs first; the steer waits right behind it on its own model.
1205 + const behind = yield* queued;
1206 + assert.deepEqual(
1207 + behind.map((run) => run.userMessageId),
1208 + [steerId, MessageId.make("after")],
1209 + );
1210 + assert.deepEqual(behind[0]?.modelSelection, modelSelection);
1211 + assert.include(offeredText(offers[2]), "Message before");
1212 + // Promoted into that run, Claude drops it again; it is queued again, then reaches Claude.
1213 + const before = (yield* orchestrator.getThreadProjection(threadId)).runs.find(
1214 + (run) => run.userMessageId === MessageId.make("before"),
1215 + )!;
1216 + yield* orchestrator.dispatch({
1217 + type: "queued-message.promote-to-steer",
1218 + commandId: CommandId.make("promote"),
1219 + threadId,
1220 + queuedRunId: behind[0]!.id,
1221 + targetRunId: before.id,
1222 + });
1223 + yield* worker.drain();
1224 + assert.equal(offers[3]?.priority, "next");
1225 + const beforeEnded = yield* settled(before.id, "waiting");
1226 + yield* answer(offers[2]!);
1227 + yield* cancel(offers[3]!);
1228 + yield* Fiber.join(beforeEnded);
1229 + yield* worker.drain();
1230 + assert.deepEqual(yield* queuedOrder, [[MessageId.make("after"), false]]);
1231 + assert.equal(offers.length, 5);
1232 + assert.equal(offers[4]?.priority, undefined);
1233 + assert.include(offeredText(offers[4]), "Message steer");
1234 + return;
1235 + }
1236 +
1237 + if (outcome === "the Claude process exits") {
1238 + const requeued = yield* watch(
1239 + (event) =>
1240 + event.type === "run.updated" &&
1241 + event.payload.userMessageId === steerId &&
1242 + event.payload.status === "queued",
1243 + );
1244 + yield* Queue.shutdown(sdkMessages);
1245 + yield* Fiber.join(requeued);
1246 + yield* worker.drain();
1247 + // The provider failure holds the queue, the follow-up included, until someone resumes it.
1248 + assert.deepEqual(yield* queuedOrder, [
1249 + [MessageId.make("before"), true],
1250 + [steerId, true],
1251 + [MessageId.make("after"), true],
1252 + ]);
1253 + assert.equal(offers.length, 2);
1254 + return;
1255 + }
1256 +
1257 + if (outcome === "Claude cancels it and the user stops") {
1258 + yield* cancel(offers[1]!);
1259 + const dropped = yield* watch(
1260 + (event) =>
1261 + event.type === "turn-item.updated" &&
1262 + event.payload.type === "user_message" &&
1263 + event.payload.messageId === steerId &&
1264 + event.payload.status === "cancelled",
1265 + );
1266 + yield* orchestrator.dispatch({
1267 + type: "run.interrupt",
1268 + commandId: CommandId.make("stop"),
1269 + threadId,
1270 + runId: parent.id,
1271 + holdQueue: true,
1272 + });
1273 + yield* worker.drain();
1274 + yield* Fiber.join(dropped);
1275 + const after = yield* orchestrator.getThreadProjection(threadId);
1276 + assert.equal(
1277 + after.turnItems.find((item) => item.type === "user_message" && item.messageId === steerId)
1278 + ?.status,
1279 + "cancelled",
1280 + );
1281 + assert.isTrue(
1282 + after.turnItems.some(
1283 + (item) => item.type === "system_notice" && item.message?.includes("Message steer"),
1284 + ),
1285 + );
1286 + assert.deepEqual(yield* queuedOrder, [
1287 + [MessageId.make("before"), true],
1288 + [MessageId.make("after"), true],
1289 + ]);
1290 + return;
1291 + }
1292 +
1293 + // Recovery cancels the run, holds the queue and leaves the unread steer pending.
1294 + const projection = yield* orchestrator.getThreadProjection(threadId);
1295 + const now = yield* DateTime.now;
1296 + yield* (yield* EventSink.EventSinkV2).write({
1297 + commandId: CommandId.make("command:runtime-reconcile:startup:unread-steer"),
1298 + events: projection.runs.map((run, index) => ({
1299 + id: EventId.make(`recovered-run-${index}`),
1300 + type: "run.updated" as const,
1301 + threadId,
1302 + runId: run.id,
1303 + occurredAt: now,
1304 + payload:
1305 + run.id === parent.id
1306 + ? { ...run, status: "cancelled" as const, completedAt: now }
1307 + : { ...run, queueHeld: true },
1308 + })),
1309 + });
1310 + yield* orchestrator.recoverDelegatedTasks;
1311 + yield* worker.drain();
1312 + assert.deepEqual(yield* queuedOrder, [
1313 + [MessageId.make("before"), true],
1314 + [steerId, true],
1315 + [MessageId.make("after"), true],
1316 + ]);
1317 + assert.equal(offers.length, 2);
1318 + }).pipe(
1319 + Effect.provide(
1320 + ProviderReplayHarness.layerWithRegistry(
1321 + { name: "claude-unread-steer" },
1322 + ProviderAdapterRegistry.layerSingle(adapter),
1323 + { runEffectWorker: false },
1324 + ),
1325 + ),
1326 + );
1327 + }).pipe(
1328 + Effect.provide(
1329 + Layer.mergeAll(
1330 + IdAllocator.layer,
1331 + McpProviderSessions.layer,
1332 + NodeServices.layer,
1333 + NodeCrypto.layer,
1334 + ),
1335 + ),
1336 + ),
1337 +);
apps/server/src/orchestration-v2/EffectOutbox.ts
+24
@@ -226,6 +226,11 @@ export interface EffectOutboxV2Shape {
226 readonly listByCommandId: (
227 commandId: CommandId,
228 ) => Effect.Effect<ReadonlyArray<OrchestrationEffectV2>, EffectOutboxError>;
229 + /** A message's first steer effect: it records which runs were queued before the message. */
230 + readonly firstSteer: (
231 + threadId: ThreadId,
232 + messageId: MessageId,
233 + ) => Effect.Effect<Option.Option<OrchestrationEffectV2>, EffectOutboxError>;
234 readonly cancelUnsettled: (input: {
235 readonly threadId: ThreadId;
236 readonly effectTypes: ReadonlyArray<OrchestrationEffectRequestV2["type"]>;
@@ -472,6 +477,25 @@ export const layer: Layer.Layer<EffectOutboxV2, never, SqlClient.SqlClient> = La
477 : new EffectOutboxError({ operation: "list", cause }),
478 ),
479 ),
480 + firstSteer: (threadId, messageId) =>
481 + sql<EffectRow>`
482 + SELECT *
483 + FROM orchestration_v2_effect_outbox
484 + WHERE thread_id = ${threadId}
485 + AND effect_type = 'provider-turn.steer'
486 + AND json_extract(payload_json, '$.messageId') = ${messageId}
487 + ORDER BY rowid ASC
488 + LIMIT 1
489 + `.pipe(
490 + NodeSqliteClient.readOnly,
491 + Effect.flatMap((rows) => decodeRows("first-steer", rows)),
492 + Effect.map((effects) => Option.fromNullishOr(effects[0])),
493 + Effect.mapError((cause) =>
494 + isEffectOutboxError(cause)
495 + ? cause
496 + : new EffectOutboxError({ operation: "first-steer", cause }),
497 + ),
498 + ),
499 cancelUnsettled: Effect.fn("EffectOutbox.cancelUnsettled")(
500 function* ({ threadId, effectTypes, reason }) {
501 if (effectTypes.length === 0) return [];
apps/server/src/orchestration-v2/Orchestrator.ts
+184 -2
@@ -3373,6 +3373,140 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
3373 );
3374 });
3375
3376 + // A steer still pending after its run ended was never read: the provider marks one it read
3377 + // completed, and one Stop dropped cancelled. It runs next, in its place among waiting messages.
3378 + const requeueUnreadSteers = Effect.fn("Orchestrator.requeueUnreadSteers")(function* (
3379 + threadId: ThreadId,
3380 + runIds?: ReadonlyArray<RunId>,
3381 + ) {
3382 + const { turnItems } = yield* projectionStore.getThreadRecords(threadId, ["turnItems"], {
3383 + turnItemTypes: ["user_message"],
3384 + turnItemStatuses: ["pending"],
3385 + ...(runIds === undefined ? {} : { turnItemRunIds: runIds }),
3386 + });
3387 + const unread = turnItems.filter(
3388 + (item) =>
3389 + item.type === "user_message" &&
3390 + (item.inputIntent === "steer" || item.inputIntent === "promoted_queued_to_steer"),
3391 + );
3392 + if (unread.length === 0) return;
3393 + const projection = yield* projectionStore.getThreadRecords(threadId, ["runs", "messages"], {
3394 + messageIds: unread.flatMap((item) => (item.type === "user_message" ? [item.messageId] : [])),
3395 + });
3396 + const placed = [];
3397 + for (const item of unread) {
3398 + const run = projection.runs.find((candidate) => candidate.id === item.runId);
3399 + const message = projection.messages.find(
3400 + (candidate) =>
3401 + item.type === "user_message" &&
3402 + candidate.id === item.messageId &&
3403 + candidate.runId === item.runId,
3404 + );
3405 + if (run === undefined || message === undefined || isActiveRun(run)) continue;
3406 + // Stop drops a steer it reached; say so, as the adapter does for steers it still held.
3407 + if (yield* projectionStore.hasRunInterruptRequest(threadId, run.id)) {
3408 + const now = yield* DateTime.now;
3409 + yield* writeSystemEvents([
3410 + {
3411 + type: "turn-item.updated",
3412 + threadId,
3413 + runId: run.id,
3414 + ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
3415 + providerInstanceId: run.providerInstanceId,
3416 + occurredAt: now,
3417 + payload: { ...item, status: "cancelled" as const, completedAt: now, updatedAt: now },
3418 + },
3419 + {
3420 + type: "turn-item.updated",
3421 + threadId,
3422 + runId: run.id,
3423 + ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
3424 + providerInstanceId: run.providerInstanceId,
3425 + occurredAt: now,
3426 + payload: {
3427 + id: idAllocator.derive.runSignalTurnItem({
3428 + runId: run.id,
3429 + signal: `unread-steer:${message.id}`,
3430 + }),
3431 + threadId,
3432 + runId: run.id,
3433 + nodeId: item.nodeId,
3434 + providerThreadId: item.providerThreadId ?? null,
3435 + providerTurnId: item.providerTurnId ?? null,
3436 + nativeItemRef: null,
3437 + parentItemId: null,
3438 + ordinal: item.ordinal,
3439 + type: "system_notice" as const,
3440 + status: "completed" as const,
3441 + title: "Steer delivery not confirmed",
3442 + message: `The agent did not confirm reading your steer before Stop. It may not have been delivered. Resend it if needed: "${message.text}"`,
3443 + startedAt: now,
3444 + completedAt: now,
3445 + updatedAt: now,
3446 + },
3447 + },
3448 + ]);
3449 + continue;
3450 + }
3451 + // The message's first steer effect recorded which runs were queued before it was sent; a
3452 + // queued message that was promoted also stays behind only the runs queued before its own.
3453 + const firstSteer = Option.getOrUndefined(
3454 + yield* effectOutbox.firstSteer(threadId, message.id),
3455 + )?.request;
3456 + const steer = firstSteer?.type === "provider-turn.steer" ? firstSteer : undefined;
3457 + const afterRunOrdinal = Math.max(
3458 + 0,
3459 + Math.min(
3460 + steer?.steerFollowUpAfterRunOrdinal ??
3461 + Math.max(...projection.runs.map((candidate) => candidate.ordinal)),
3462 + ...projection.runs.flatMap((candidate) =>
3463 + candidate.userMessageId === message.id ? [candidate.ordinal - 1] : [],
3464 + ),
3465 + ),
3466 + );
3467 + placed.push({ item, run, message, steer, afterRunOrdinal });
3468 + }
3469 + // Each requeue starts the queue once it commits, so earlier places go first.
3470 + placed.sort(
3471 + (left, right) =>
3472 + left.afterRunOrdinal - right.afterRunOrdinal || left.item.ordinal - right.item.ordinal,
3473 + );
3474 + for (const { run, message, steer, afterRunOrdinal } of placed) {
3475 + yield* dispatchWithReceiptEffect({
3476 + type: "message.dispatch",
3477 + commandId: CommandId.make(`command:unread-steer:${run.id}:${message.id}`),
3478 + threadId,
3479 + messageId: message.id,
3480 + steerFollowUpOfRunId: run.id,
3481 + steerFollowUpAfterRunOrdinal: afterRunOrdinal,
3482 + modelSelection: steer?.modelSelection ?? run.modelSelection,
3483 + text: message.text,
3484 + ...(message.context ? { context: message.context } : {}),
3485 + attachments: message.attachments,
3486 + ...(message.delegatedCompletion === undefined
3487 + ? {}
3488 + : { delegatedCompletion: message.delegatedCompletion }),
3489 + ...(message.notification === undefined ? {} : { notification: message.notification }),
3490 + dispatchMode: { type: "queue_after_active" },
3491 + createdBy: message.createdBy,
3492 + creationSource: message.creationSource,
3493 + ...(message.scheduledTaskId === undefined
3494 + ? {}
3495 + : { scheduledTaskId: message.scheduledTaskId }),
3496 + ...(message.senderThreadId === undefined ? {} : { senderThreadId: message.senderThreadId }),
3497 + ...(message.linkedSender === undefined ? {} : { linkedSender: message.linkedSender }),
3498 + }).pipe(
3499 + Effect.catchCause((cause) =>
3500 + Effect.logWarning("Failed to requeue an unread steer", {
3501 + threadId,
3502 + messageId: message.id,
3503 + cause,
3504 + }),
3505 + ),
3506 + );
3507 + }
3508 + });
3509 +
3510 const resumeQueuedRuns = Effect.gen(function* () {
3511 const threadIds = yield* projectionStore.getRecoveryThreadIds("queued-runs");
3512 let resumed = 0;
@@ -7576,7 +7710,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7710 projection.thread.worktreePath === null
7711 ? latestRun
7712 : undefined;
7579 - const queueBehindRun = activeRun ?? worktreeMissingRun;
7713 + // A steer whose run already ended still keeps its place in the queue.
7714 + const steerFollowUpSource =
7715 + command.steerFollowUpOfRunId === undefined
7716 + ? undefined
7717 + : projection.runs.find((run) => run.id === command.steerFollowUpOfRunId);
7718 + const queueBehindRun = activeRun ?? worktreeMissingRun ?? steerFollowUpSource;
7719 const pendingMergeBackTransfers = pendingMergeBackTransfersForThread(projection);
7720 const startsOrQueuesRun =
7721 dispatchMode.type === "defer_start" ||
@@ -7589,6 +7728,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7728 const incomingMessage = { ...command, delegatedCompletion };
7729 if (
7730 shouldQueue &&
7731 + // A steer whose run ended keeps the thread's selection, as it did before it queued.
7732 + queueBehindRun !== steerFollowUpSource &&
7733 steerWhenReadyRunId === undefined &&
7734 command.modelSelection === undefined &&
7735 queuedRunStop === undefined &&
@@ -7775,7 +7916,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
7916 activeAttemptId: attemptId,
7917 status: "queued",
7918 ...(steerWhenReadyRunId === undefined ? {} : { steerWhenReadyRunId }),
7919 + // A restart cancels its run; nobody knows whether the provider read the steer, so a person decides.
7920 ...(worktreeMissingRun !== undefined ||
7921 + steerFollowUpSource?.status === "cancelled" ||
7922 (heldRunsToRelease.length === 0 &&
7923 queueIsHeld &&
7924 !wakeSkipsHold &&
@@ -15625,15 +15768,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
15768
15769 // The run-end release can lag behind a new send; start the queue first so the send waits behind it.
15770 // A restart continuation resumes the ended run, so it must not be overtaken by the queue.
15771 + // A steer follow-up takes its place first and starts the queue after it commits. A send that
15772 + // beats the run-end reaction places the ended run's unread steers before it starts anything.
15773 if (
15774 command.type === "message.dispatch" &&
15775 command.restartContinuationOfRunId === undefined &&
15776 + command.steerFollowUpOfRunId === undefined &&
15777 (command.dispatchMode.type === "start_immediately" ||
15778 command.dispatchMode.type === "queue_after_active" ||
15779 command.dispatchMode.type === "defer_start")
15780 ) {
15781 yield* mapDispatchError(command)(
15636 - startNextQueuedRun(command.threadId, { latestRunEnded: true }),
15782 + requeueUnreadSteers(command.threadId).pipe(
15783 + Effect.andThen(startNextQueuedRun(command.threadId, { latestRunEnded: true })),
15784 + ),
15785 );
15786 }
15787
@@ -15850,6 +15998,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
15998 yield* mapDispatchError(command)(offerDelegatedCompletionDeliveries(command.parentThreadId));
15999 }
16000
16001 + if (command.type === "message.dispatch" && command.steerFollowUpOfRunId !== undefined) {
16002 + yield* mapDispatchError(command)(
16003 + startNextQueuedRun(command.threadId, { latestRunEnded: true }),
16004 + );
16005 + }
16006 +
16007 return {
16008 sequence: committed.receipt.resultSequence,
16009 storedEvents: committed.storedEvents,
@@ -15955,6 +16109,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
16109 ? releaseUnattendedHolds(threadId, run.id)
16110 : Effect.void
16111 ).pipe(
16112 + Effect.andThen(
16113 + requeueUnreadSteers(threadId, [run.id]).pipe(
16114 + Effect.catchCause((cause) =>
16115 + Effect.logWarning("Failed to read unread steers", { threadId, cause }),
16116 + ),
16117 + ),
16118 + ),
16119 Effect.andThen(
16120 startNextQueuedRun(threadId, {
16121 endedRunId: run.id,
@@ -16224,6 +16385,27 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
16385 }),
16386 ),
16387 );
16388 + // Recovery leaves a steer the provider had not read pending, and no run update follows it.
16389 + yield* projectionStore.getRecoveryThreadIds("unread-steers").pipe(
16390 + Effect.flatMap((threadIds) =>
16391 + Effect.forEach(
16392 + threadIds,
16393 + (threadId) =>
16394 + threadDispatch.withLock(threadId, requeueUnreadSteers(threadId)).pipe(
16395 + Effect.catchCause((cause) =>
16396 + Effect.logWarning("Failed to requeue an unread steer during recovery", {
16397 + threadId,
16398 + cause,
16399 + }),
16400 + ),
16401 + ),
16402 + { discard: true },
16403 + ),
16404 + ),
16405 + Effect.catchCause((cause) =>
16406 + Effect.logWarning("Failed to inspect unread steers during recovery", { cause }),
16407 + ),
16408 + );
16409 });
16410
16411 const delegatedTaskResultPending = Effect.fn("Orchestrator.delegatedTaskResultPending")(
apps/server/src/orchestration-v2/ProjectionStore.ts
+12 -1
@@ -185,7 +185,8 @@ export type ProjectionRecoveryKind =
185 | "runtime"
186 | "restart-continuations"
187 | "subagent-results"
188 - | "delegated-completions";
188 + | "delegated-completions"
189 + | "unread-steers";
190
191 export type ProjectionLimitRecoveryCandidate = Pick<
192 OrchestrationV2ThreadShell,
@@ -5055,6 +5056,16 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5056 AND active.status IN ('preparing', 'starting', 'running', 'waiting')
5057 )
5058 `;
5059 + case "unread-steers":
5060 + return sql`
5061 + SELECT item.thread_id FROM orchestration_v2_projection_turn_items AS item
5062 + JOIN orchestration_v2_projection_runs AS run ON run.run_id = item.run_id
5063 + WHERE item.type = 'user_message' AND item.status = 'pending'
5064 + AND run.status IN ('completed', 'interrupted', 'failed', 'cancelled')
5065 + AND CASE WHEN json_valid(item.payload_json)
5066 + THEN json_extract(item.payload_json, '$.inputIntent') IN ('steer', 'promoted_queued_to_steer')
5067 + ELSE 0 END
5068 + `;
5069 case "delegated-completions":
5070 return sql`
5071 SELECT thread_id FROM orchestration_v2_projection_runs
apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.test.ts
+15 -4
@@ -419,7 +419,7 @@ it.effect("cancels a stale waiting run when no checkpoint capture can finish it"
419 }).pipe(Effect.provide(layer));
420 });
421
422 -it.effect("recovery closes a secret card's form but leaves a link card open", () => {
422 +it.effect("recovery closes a secret card but leaves a link card and an unread steer open", () => {
423 const threadId = ThreadId.make("thread_secret_recovery");
424 const runId = RunId.make("run_secret_recovery");
425 let committedInput: Parameters<EventSink.EventSinkV2["Service"]["commitCommand"]>[0] | null =
@@ -467,6 +467,16 @@ it.effect("recovery closes a secret card's form but leaves a link card open", ()
467 url: "https://box.example.ts.net",
468 reason: "Run the suite there.",
469 },
470 + {
471 + id: "turn-item:steer:recovery",
472 + threadId,
473 + runId,
474 + nodeId: null,
475 + type: "user_message",
476 + status: "pending",
477 + inputIntent: "steer",
478 + messageId: "message:steer:recovery",
479 + },
480 ],
481 } as unknown as OrchestrationV2ThreadProjection;
482 const layer = ProviderRuntimeRecovery.layer.pipe(
@@ -504,9 +514,10 @@ it.effect("recovery closes a secret card's form but leaves a link card open", ()
514 assert.equal(secret?.status, "cancelled");
515 assert.equal(secret?.type === "secret_request" ? secret.secretStatus : null, "cancelled");
516 // Nothing in memory waits on a link card; the user can still answer it.
507 - assert.equal(
508 - cards.some((card) => card.type === "link_request"),
509 - false,
517 + // Claude never reported reading the steer, so the orchestrator queues it.
518 + assert.deepEqual(
519 + cards.filter((card) => card.type === "link_request" || card.type === "user_message"),
520 + [],
521 );
522 }).pipe(Effect.provide(layer));
523 });
apps/server/src/orchestration-v2/ProviderRuntimeRecoveryService.ts
+7
@@ -778,6 +778,13 @@ export const make = Effect.gen(function* () {
778 !isAppOwnedDelegationItem(candidate) &&
779 // A link card waits on the user, not the run, and answers by message.
780 candidate.type !== "link_request" &&
781 + // The orchestrator queues a steer the provider never reported reading.
782 + !(
783 + candidate.type === "user_message" &&
784 + candidate.status === "pending" &&
785 + (candidate.inputIntent === "steer" ||
786 + candidate.inputIntent === "promoted_queued_to_steer")
787 + ) &&
788 (candidate.status === "pending" ||
789 candidate.status === "running" ||
790 candidate.status === "waiting"),
apps/server/src/orchestration-v2/testkit/fixtures/message_steering/claude_transcript.ndjson
+1 -1
@@ -1,7 +1,7 @@
1 {"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"}}
2 {"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}}}}
3 {"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}}}
4 -{"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"}}}
4 +{"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"}}}
5 {"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"}}
6 {"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"}}
7 {"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"}}
docs/user/providers-claude.md
+9
@@ -89,6 +89,15 @@ Claude Code holds the turn until that window reopens, so it can keep showing as
89 working. Wait for the reset, or stop the turn and continue later. The warning's
90 timestamp shows when the displayed wait started.
91
92 +## Steering
93 +
94 +A steer waits until Claude finishes the tool calls it is running, then Claude reads it
95 +in the same turn. The message shows as unread until then. If Claude drops it before
96 +reading it, the message is sent as the next turn, after any messages queued before it.
97 +If Claude exits or the server restarts first, the message waits in the queue in that
98 +same place until you resume it. If you press Stop, T3 Code shows a notice with the text
99 +of any steer Claude had not read.
100 +
101 ## Skills
102
103 Claude skills come from the config directory's `skills` folder and the project's