Skip to content

Commit 3e7bd6b

Browse files
flambohclaude
andcommitted
fix(server,web,mobile): follow-ups sent during setup steer once the turn starts
Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent f6a9315 commit 3e7bd6b

11 files changed

Lines changed: 389 additions & 55 deletions

File tree

‎apps/mobile/src/state/use-thread-composer-state.ts‎

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -649,21 +649,18 @@ export function useThreadComposerState() {
649649
// Steering uses "auto" so an ended turn queues a run instead of restoring the draft.
650650
// An approval redirect must steer the waiting turn instead of queueing behind it.
651651
const activeTurnDefault = beforeDispatch !== undefined ? "steer" : followUpBehavior;
652+
// The server holds a steer sent during setup until the turn starts.
653+
const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
654+
(status) => status === "preparing" || status === "starting",
655+
);
652656
const followUpAction = resolveComposerDispatchMode({
653-
running: activeThreadBusy && canSteerActiveTurn,
657+
running: setupRunning || (activeThreadBusy && canSteerActiveTurn),
654658
alternateModifier: followUpOverride !== undefined && followUpOverride !== activeTurnDefault,
655659
activeTurnDefault,
660+
canSteer: !isCompacting,
656661
});
657-
const setupRunning = [selectedThreadActivityRun?.status, selectedThreadRuntime?.status].some(
658-
(status) => status === "preparing" || status === "starting",
659-
);
660-
const followUpDispatchMode = setupRunning
661-
? "queue"
662-
: followUpAction === "auto"
663-
? null
664-
: followUpAction === "queue"
665-
? "queue"
666-
: "auto";
662+
const followUpDispatchMode =
663+
followUpAction === "auto" ? null : followUpAction === "queue" ? "queue" : "auto";
667664

668665
const metadata = makeQueuedMessageMetadata();
669666
const messageId = MessageId.make(metadata.messageId);

‎apps/server/src/orchestration-v2/CommandPolicy.test.ts‎

Lines changed: 41 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -134,35 +134,51 @@ it.each(["preparing", "starting"] as const)(
134134
);
135135

136136
it.each([
137-
["has not started", []],
138-
["is pending", [{ runAttemptId: activeAttemptId, status: "pending" }]],
139-
["has completed", [{ runAttemptId: activeAttemptId, status: "completed" }]],
137+
["has not started", [], { type: "queue_after_active" }],
138+
[
139+
"is pending",
140+
[{ runAttemptId: activeAttemptId, status: "pending" }],
141+
{ type: "queue_after_active" },
142+
],
143+
[
144+
"has completed",
145+
[{ runAttemptId: activeAttemptId, status: "completed" }],
146+
{ type: "steer_active", targetRunId: activeRunId },
147+
],
140148
[
141149
"belongs to a previous attempt",
142150
[{ runAttemptId: RunAttemptId.make("previous-attempt"), status: "running" }],
143-
],
144-
])("queues only automatic delivery when the active run's provider turn %s", (_, providerTurns) => {
145-
const projection = {
146-
...dispatchProjection(baseCapabilities),
147-
providerTurns,
148-
} as unknown as OrchestrationV2ThreadProjection;
149-
assert.deepEqual(
150-
CommandPolicy.resolveMessageDispatchIntent(projection, { type: "start_immediately" }, "auto"),
151151
{ type: "queue_after_active" },
152-
);
153-
assert.deepEqual(
154-
CommandPolicy.resolveMessageDispatchIntent(projection, { type: "start_immediately" }, "steer"),
155-
{ type: "steer_active", targetRunId: activeRunId },
156-
);
157-
assert.deepEqual(
158-
CommandPolicy.resolveMessageDispatchIntent(
159-
projection,
160-
{ type: "start_immediately" },
161-
"restart",
162-
),
163-
{ type: "restart_active", targetRunId: activeRunId },
164-
);
165-
});
152+
],
153+
] as const)(
154+
"queues automatic delivery when the active run's provider turn %s",
155+
(_, providerTurns, steer) => {
156+
const projection = {
157+
...dispatchProjection(baseCapabilities),
158+
providerTurns,
159+
} as unknown as OrchestrationV2ThreadProjection;
160+
assert.deepEqual(
161+
CommandPolicy.resolveMessageDispatchIntent(projection, { type: "start_immediately" }, "auto"),
162+
{ type: "queue_after_active" },
163+
);
164+
assert.deepEqual(
165+
CommandPolicy.resolveMessageDispatchIntent(
166+
projection,
167+
{ type: "start_immediately" },
168+
"steer",
169+
),
170+
steer,
171+
);
172+
assert.deepEqual(
173+
CommandPolicy.resolveMessageDispatchIntent(
174+
projection,
175+
{ type: "start_immediately" },
176+
"restart",
177+
),
178+
{ type: "restart_active", targetRunId: activeRunId },
179+
);
180+
},
181+
);
166182

167183
it.each(["/compact", " /LOGOUT "])("queues a steer sent while %s runs", (text) => {
168184
const projection = dispatchProjection(baseCapabilities);

‎apps/server/src/orchestration-v2/CommandPolicy.ts‎

Lines changed: 27 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -150,8 +150,13 @@ export function goalCommandStopsActiveRun(
150150
}
151151
}
152152

153+
type DeliveryIntentProjection = Pick<
154+
OrchestrationV2ThreadProjection,
155+
"runs" | "messages" | "providerTurns" | "providerThreads" | "providerSessions"
156+
>;
157+
153158
export function resolveMessageDispatchIntent(
154-
projection: OrchestrationV2ThreadProjection,
159+
projection: DeliveryIntentProjection,
155160
requestedMode: MessageDispatchMode,
156161
deliveryIntent?: "auto" | "steer" | "restart",
157162
): MessageDispatchMode {
@@ -165,8 +170,22 @@ export function resolveMessageDispatchIntent(
165170
: mode;
166171
}
167172

173+
export function runAwaitsProviderTurn(
174+
projection: Pick<OrchestrationV2ThreadProjection, "providerTurns">,
175+
run: Pick<OrchestrationV2Run, "status" | "activeAttemptId">,
176+
): boolean {
177+
return (
178+
run.status === "preparing" ||
179+
run.status === "starting" ||
180+
(run.status === "running" &&
181+
!projection.providerTurns.some(
182+
(turn) => turn.runAttemptId === run.activeAttemptId && turn.status !== "pending",
183+
))
184+
);
185+
}
186+
168187
function resolveDeliveryIntent(
169-
projection: OrchestrationV2ThreadProjection,
188+
projection: DeliveryIntentProjection,
170189
requestedMode: MessageDispatchMode,
171190
deliveryIntent?: "auto" | "steer" | "restart",
172191
): MessageDispatchMode {
@@ -180,17 +199,16 @@ function resolveDeliveryIntent(
180199
run.status === "waiting",
181200
);
182201
if (activeRun === undefined) return { type: "start_immediately" };
183-
if (deliveryIntent === "steer") {
184-
return { type: "steer_active", targetRunId: activeRun.id };
185-
}
186202
if (deliveryIntent === "restart") {
187203
return { type: "restart_active", targetRunId: activeRun.id };
188204
}
189-
// A run can be active before its provider turn starts or after it finishes.
190-
// Queue automatic input in those gaps so steering cannot reject the message.
205+
if (runAwaitsProviderTurn(projection, activeRun)) return { type: "queue_after_active" };
206+
if (deliveryIntent === "steer") {
207+
return { type: "steer_active", targetRunId: activeRun.id };
208+
}
209+
// A run stays active after its provider turn finishes. Queue automatic input
210+
// in that gap so steering cannot reject the message.
191211
if (
192-
activeRun.status === "preparing" ||
193-
activeRun.status === "starting" ||
194212
!projection.providerTurns.some(
195213
(turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
196214
)

‎apps/server/src/orchestration-v2/Orchestrator.ts‎

Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ import {
9797
goalCommandStopsActiveRun,
9898
isNativeMaintenanceCommand,
9999
resolveMessageDispatchIntent,
100+
runAwaitsProviderTurn,
100101
} from "./CommandPolicy.ts";
101102
import { CommandReceiptStoreV2 } from "./CommandReceiptStore.ts";
102103
import { ContextHandoffServiceV2 } from "./ContextHandoffService.ts";
@@ -5496,6 +5497,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
54965497
payload: { ...held, queueHeld: false },
54975498
});
54985499
}
5500+
const activeRunMessage = projection.messages.find(
5501+
(message) => message.id === activeRun?.userMessageId,
5502+
);
5503+
const startupDeliveryIntent =
5504+
activeRun !== undefined &&
5505+
(command.deliveryIntent === "auto" || command.deliveryIntent === "steer") &&
5506+
goalCommand === null &&
5507+
delegatedCompletion === undefined &&
5508+
command.notification === undefined &&
5509+
!isNativeMaintenanceCommand(command) &&
5510+
(activeRunMessage === undefined || !isNativeMaintenanceCommand(activeRunMessage)) &&
5511+
runAwaitsProviderTurn(projection, activeRun)
5512+
? command.deliveryIntent
5513+
: undefined;
54995514
if (shouldQueue) {
55005515
if (pendingMergeBackTransfers.length > 0) {
55015516
return yield* new OrchestratorDispatchError({
@@ -5630,6 +5645,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
56305645
? {}
56315646
: { restartContinuationOfRunId: command.restartContinuationOfRunId }),
56325647
...(continuedTaskId === undefined ? {} : { delegatedTaskId: continuedTaskId }),
5648+
...(startupDeliveryIntent === undefined ? {} : { deliveryIntent: startupDeliveryIntent }),
56335649
};
56345650
const attempt: OrchestrationV2RunAttempt = {
56355651
id: attemptId,
@@ -12401,6 +12417,90 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1240112417
Effect.forkDetach,
1240212418
);
1240312419

12420+
const deliverStartupQueuedMessages = Effect.fn("Orchestrator.deliverStartupQueuedMessages")(
12421+
function* (stored: OrchestrationV2StoredEvent) {
12422+
if (stored.event.type !== "provider-turn.updated") return;
12423+
const threadId = stored.event.threadId;
12424+
// Under the lock so a send still committing its queued run is seen. Each promotion can
12425+
// restart the target, so the next one decides from fresh records.
12426+
yield* threadDispatch.withLock(
12427+
threadId,
12428+
Effect.gen(function* () {
12429+
const attempted = new Set<RunId>();
12430+
while (true) {
12431+
const projection = yield* projectionStore.getThreadRecords(
12432+
threadId,
12433+
["runs", "messages", "providerTurns", "providerThreads", "providerSessions"],
12434+
{ turnItemTypes: [], messageRoles: ["user"] },
12435+
);
12436+
const next = queuedRunsInDeliveryOrder(projection)
12437+
.filter((queued) => {
12438+
if (queued.deliveryIntent === undefined || queued.queueHeld === true) return false;
12439+
if (attempted.has(queued.id)) return false;
12440+
// The message may have been edited into a command that must run as its own turn.
12441+
const message = projection.messages.find((m) => m.id === queued.userMessageId);
12442+
return (
12443+
message !== undefined &&
12444+
parseGoalCommand(message) === null &&
12445+
!isNativeMaintenanceCommand(message)
12446+
);
12447+
})
12448+
.map((queued) => ({
12449+
queued,
12450+
mode: resolveMessageDispatchIntent(
12451+
projection,
12452+
{ type: "queue_after_active" },
12453+
queued.deliveryIntent,
12454+
),
12455+
}))
12456+
.find(
12457+
({ queued, mode }) =>
12458+
mode.type === "steer_active" &&
12459+
// A message for another model starts its own turn. Promotion steers with the
12460+
// thread's selection, so that must match too or the steer would restart the turn.
12461+
modelSelectionsEqual(queued.modelSelection, projection.thread.modelSelection) &&
12462+
projection.runs.some(
12463+
(run) =>
12464+
run.id === mode.targetRunId &&
12465+
modelSelectionsEqual(queued.modelSelection, run.modelSelection),
12466+
),
12467+
);
12468+
if (next?.mode.type !== "steer_active") return;
12469+
attempted.add(next.queued.id);
12470+
yield* dispatchWithReceiptEffect({
12471+
type: "queued-message.promote-to-steer",
12472+
commandId: CommandId.make(`command:system:startup-steer:${next.queued.id}`),
12473+
threadId,
12474+
queuedRunId: next.queued.id,
12475+
targetRunId: next.mode.targetRunId,
12476+
});
12477+
}
12478+
}),
12479+
);
12480+
},
12481+
(effect, stored) =>
12482+
effect.pipe(
12483+
Effect.catchCause((cause) =>
12484+
Effect.logWarning("Failed to steer messages queued before the turn started", {
12485+
threadId: stored.event.threadId,
12486+
sequence: stored.sequence,
12487+
cause,
12488+
}),
12489+
),
12490+
),
12491+
);
12492+
yield* eventSink
12493+
.stream({ afterSequence: terminalEventsAfterSequence, eventType: "provider-turn.updated" })
12494+
.pipe(
12495+
Stream.filter(
12496+
(stored) =>
12497+
stored.event.type === "provider-turn.updated" &&
12498+
stored.event.payload.status === "running",
12499+
),
12500+
Stream.runForEach(deliverStartupQueuedMessages),
12501+
Effect.forkDetach,
12502+
);
12503+
1240412504
// A child whose run ends while its background tasks or its own subagents still run has no
1240512505
// result yet. When that work settles there is no run update to finalize it, so these events
1240612506
// do it. A background roster counts once it empties after it was seen non-empty.

0 commit comments

Comments
 (0)