Skip to content
TypeScript

fix(queue): send selected held messages when a thread is stopped (#22790)

Yash Singh96f09c6558b0
diff --git a/apps/mobile/src/features/threads/ThreadQueueControl.tsx b/apps/mobile/src/features/threads/ThreadQueueControl.tsx
index e5920b06ebe..11ac46da06d 100644
--- a/apps/mobile/src/features/threads/ThreadQueueControl.tsx
+++ b/apps/mobile/src/features/threads/ThreadQueueControl.tsx
@@ -149,6 +149,8 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
void Haptics.selectionAsync();
if (action === "remove") {
await cancel(buildCancelQueuedRunCommand({ ...target, runId }));
+ } else if (workflow?.canSendNow) {
+ await resume({ ...target, input: { threadId: target.threadId, runId } });
} else if (workflow?.activeRun && workflow.canPromoteToSteer) {
await promote({
...target,
@@ -221,6 +223,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
const controls = resolveThreadQueueRowControls({
busy: busyRunId !== null || draggedRunId !== null,
canPromoteToSteer: workflow?.canPromoteToSteer ?? false,
+ canSendNow: workflow?.canSendNow ?? false,
canReorder: workflow?.canReorder ?? false,
index,
isEditing: editing?.runId === run.id,
@@ -326,12 +329,12 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
accessibilityLabel={`Actions for queued message ${index + 1}`}
shouldOpenOnLongPress
actions={[
- ...(workflow?.canPromoteToSteer
+ ...(workflow?.canPromoteToSteer || workflow?.canSendNow
? [
{
id: "steer",
- title: "Steer now",
- attributes: { disabled: !controls.canSteer },
+ title: workflow?.canSendNow ? "Send now" : "Steer now",
+ attributes: { disabled: !controls.canSend },
image: Platform.OS === "ios" ? "arrow.turn.left.up" : "arrow_upward",
},
]
@@ -385,16 +388,20 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
Editing
</Text>
) : null}
- {workflow?.canPromoteToSteer ? (
+ {workflow?.canPromoteToSteer || workflow?.canSendNow ? (
<Pressable
accessibilityRole="button"
- accessibilityLabel={`Steer with message ${index + 1} now`}
- disabled={!controls.canSteer}
+ accessibilityLabel={
+ workflow?.canSendNow
+ ? `Send message ${index + 1} now`
+ : `Steer with message ${index + 1} now`
+ }
+ disabled={!controls.canSend}
onPress={() => void act(run.id, "steer")}
className="h-8 shrink-0 justify-center rounded-full bg-primary px-3 active:opacity-70 disabled:opacity-40"
>
<Text className="font-t3-medium text-xs text-primary-foreground">
- Steer
+ {workflow?.canSendNow ? "Send now" : "Steer"}
</Text>
</Pressable>
) : null}
diff --git a/apps/mobile/src/features/threads/threadQueueControlPresentation.test.ts b/apps/mobile/src/features/threads/threadQueueControlPresentation.test.ts
index 14751cedd40..60e37f9475d 100644
--- a/apps/mobile/src/features/threads/threadQueueControlPresentation.test.ts
+++ b/apps/mobile/src/features/threads/threadQueueControlPresentation.test.ts
@@ -7,6 +7,28 @@ import {
} from "./threadQueueControlPresentation";
describe("threadQueueControlPresentation", () => {
+ it.each([
+ { busy: false, isEditing: false, expected: true },
+ { busy: true, isEditing: false, expected: false },
+ { busy: false, isEditing: true, expected: false },
+ ])(
+ "gates sending a stopped thread's queued message with $busy busy and $isEditing editing",
+ ({ busy, isEditing, expected }) => {
+ const controls = resolveThreadQueueRowControls({
+ busy,
+ isEditing,
+ canPromoteToSteer: false,
+ canSendNow: true,
+ canReorder: false,
+ index: 0,
+ queuedCount: 1,
+ text: "Queued message",
+ });
+
+ expect(controls.canSend).toBe(expected);
+ },
+ );
+
it("shows an assistant quote as its quoted text", () => {
const href = formatAssistantCitationHref({
version: 1,
@@ -22,6 +44,7 @@ describe("threadQueueControlPresentation", () => {
const controls = resolveThreadQueueRowControls({
busy: false,
canPromoteToSteer: true,
+ canSendNow: false,
canReorder: true,
index: 0,
queuedCount: 1,
@@ -37,6 +60,7 @@ describe("threadQueueControlPresentation", () => {
const editing = resolveThreadQueueRowControls({
busy: false,
canPromoteToSteer: true,
+ canSendNow: false,
canReorder: true,
index: 1,
isEditing: true,
@@ -46,7 +70,7 @@ describe("threadQueueControlPresentation", () => {
expect(editing.isEditing).toBe(true);
expect(editing.canEdit).toBe(false);
- expect(editing.canSteer).toBe(false);
+ expect(editing.canSend).toBe(false);
expect(editing.canMoveUp).toBe(true);
expect(editing.canDismiss).toBe(true);
});
diff --git a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts b/apps/mobile/src/features/threads/threadQueueControlPresentation.ts
index 4128c874f94..14fa9e02841 100644
--- a/apps/mobile/src/features/threads/threadQueueControlPresentation.ts
+++ b/apps/mobile/src/features/threads/threadQueueControlPresentation.ts
@@ -8,7 +8,7 @@ export interface ThreadQueueRowControls {
readonly canEdit: boolean;
readonly canMoveDown: boolean;
readonly canMoveUp: boolean;
- readonly canSteer: boolean;
+ readonly canSend: boolean;
readonly dismissAccessibilityLabel: string;
readonly displayText: string;
readonly isEditing: boolean;
@@ -17,6 +17,7 @@ export interface ThreadQueueRowControls {
export function resolveThreadQueueRowControls(input: {
readonly busy: boolean;
readonly canPromoteToSteer: boolean;
+ readonly canSendNow: boolean;
readonly canReorder: boolean;
readonly index: number;
readonly isEditing?: boolean;
@@ -33,9 +34,9 @@ export function resolveThreadQueueRowControls(input: {
canEdit: mutationEnabled && !isEditing,
canMoveDown: mutationEnabled && input.canReorder && input.index < input.queuedCount - 1,
canMoveUp: mutationEnabled && input.canReorder && input.index > 0,
- canSteer: mutationEnabled && input.canPromoteToSteer && !isEditing,
+ canSend: mutationEnabled && (input.canPromoteToSteer || input.canSendNow) && !isEditing,
dismissAccessibilityLabel: REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL,
- // Edit and Steer keep the original text so quoted citations stay linked.
+ // Editing and sending keep the original text so quoted citations stay linked.
displayText: assistantCitationsToPlainText(input.text),
isEditing,
};
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 213a1a31ab7..8c8620088fa 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -477,6 +477,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
case "subagent.stop":
case "run.interrupt":
case "queued-message.promote-to-steer":
+ case "queued-run.start":
case "queue.resume":
case "queued-run.reorder":
case "queued-run.cancel":
@@ -1277,13 +1278,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const failQueuedRunStart = Effect.fn("Orchestrator.failQueuedRunStart")(function* (
threadId: ThreadId,
cause: unknown,
+ queuedRunId?: RunId,
) {
const projection = yield* projectionStore.getThreadRecords(
threadId,
["runs", "nodes", "attempts", "providerThreads", "turnItems", "messages"],
{ turnItemTypes: [], messageRoles: ["user"] },
);
- const queuedRun = nextQueuedRun(projection);
+ const queuedRun =
+ queuedRunId === undefined
+ ? nextQueuedRun(projection)
+ : projection.runs.find((run) => run.id === queuedRunId && run.status === "queued");
if (queuedRun === undefined) return;
const now = yield* DateTime.now;
const rootNode = projection.nodes.find((node) => node.id === queuedRun.rootNodeId);
@@ -1384,7 +1389,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const startNextQueuedRun = Effect.fn("Orchestrator.startNextQueuedRun")(
function* (
threadId: ThreadId,
- options?: { readonly failedRunId?: RunId; readonly endedRunId?: RunId },
+ options?: {
+ readonly failedRunId?: RunId;
+ readonly endedRunId?: RunId;
+ readonly queuedRunId?: RunId;
+ },
) {
if (!(yield* projectionStore.canStartQueuedRun(threadId))) return;
const projection = yield* readCommandProjection(threadId);
@@ -1397,7 +1406,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
return;
}
- const storedQueuedRun = nextQueuedRun(projection);
+ const storedQueuedRun =
+ options?.queuedRunId === undefined
+ ? nextQueuedRun(projection)
+ : projection.runs.find(
+ (run) => run.id === options.queuedRunId && run.status === "queued",
+ );
if (storedQueuedRun === undefined) {
return;
}
@@ -2087,8 +2101,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
],
);
},
- (effect, threadId, _options?) =>
- effect.pipe(Effect.catch((cause) => failQueuedRunStart(threadId, cause))),
+ (effect, threadId, options?) =>
+ effect.pipe(
+ Effect.catch((cause) => failQueuedRunStart(threadId, cause, options?.queuedRunId)),
+ ),
);
const resumeQueuedRuns = Effect.gen(function* () {
@@ -11423,6 +11439,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
case "queued-message.promote-to-steer":
yield* dispatchQueuedMessagePromoteToSteer(command, events, effects);
break;
+ case "queued-run.start":
case "queue.resume": {
const projection = yield* loadProjectionForCommand(
command,
@@ -11436,7 +11453,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
cause: `Thread ${command.threadId} is not active.`,
});
}
- const nextRun = nextQueuedRun(projection);
+ const selectedRunId = command.type === "queued-run.start" ? command.runId : undefined;
+ const selectedRun =
+ selectedRunId === undefined
+ ? undefined
+ : projection.runs.find((run) => run.id === selectedRunId && run.status === "queued");
+ if (selectedRunId !== undefined) {
+ const selectedMessage = projection.messages.find(
+ (message) => message.id === selectedRun?.userMessageId,
+ );
+ if (
+ selectedRun === undefined ||
+ selectedMessage === undefined ||
+ selectedMessage.delegatedCompletion !== undefined ||
+ selectedMessage.notification !== undefined ||
+ projection.runs.some(isBlockingRun)
+ ) {
+ return yield* new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: "A queued user message can only be sent now while the thread is stopped.",
+ });
+ }
+ }
+ const nextRun = selectedRun ?? nextQueuedRun(projection);
if (
usageLimitHoldsQueue(
projection,
@@ -11579,8 +11619,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
}),
),
);
- if (command.type === "queue.resume") {
- yield* mapDispatchError(command)(startNextQueuedRun(command.threadId));
+ if (command.type === "queue.resume" || command.type === "queued-run.start") {
+ yield* mapDispatchError(command)(
+ startNextQueuedRun(
+ command.threadId,
+ command.type === "queued-run.start" ? { queuedRunId: command.runId } : undefined,
+ ),
+ );
}
return {
sequence: receipt.resultSequence,
@@ -11712,8 +11757,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
detail: committed.receipt.error ?? "Previously rejected.",
});
}
- if (command.type === "queue.resume") {
- yield* mapDispatchError(command)(startNextQueuedRun(command.threadId));
+ if (command.type === "queue.resume" || command.type === "queued-run.start") {
+ yield* mapDispatchError(command)(
+ startNextQueuedRun(
+ command.threadId,
+ command.type === "queued-run.start" ? { queuedRunId: command.runId } : undefined,
+ ),
+ );
}
if (command.type === "notification.delivery.accept") {
yield* mapDispatchError(command)(offerDelegatedCompletionDeliveries(command.threadId));
diff --git a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
index 441cf0a6e90..208934624d9 100644
--- a/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
+++ b/apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
@@ -550,6 +550,139 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function*
return { events, started, steered, layer, startFirstTurn };
});
+it.effect("sends a selected held message once and preserves the remaining queue order", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const { started, steered, layer, startFirstTurn } =
+ yield* nextTurnSelectionHarness("send-held-message");
+ yield* Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ const threadId = yield* startFirstTurn;
+ yield* Effect.forEach(["queued-first", "selected", "queued-last"], (text) =>
+ orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make(text),
+ threadId,
+ messageId: MessageId.make(`message:${text}`),
+ text,
+ attachments: [],
+ modelSelection: runSelection,
+ dispatchMode: { type: "queue_after_active" },
+ createdBy: "user",
+ creationSource: "web",
+ }),
+ );
+ const before = yield* orchestrator.getThreadProjection(threadId);
+ const selected = before.runs.find(
+ (run) => run.userMessageId === MessageId.make("message:selected"),
+ )!;
+ const sink = yield* EventSink.EventSinkV2;
+ const now = yield* DateTime.now;
+ // Restart recovery cancels the active run and holds every queued message.
+ yield* sink.write({
+ events: [
+ ...before.runs.map((run) => ({
+ id: EventId.make(`restart:${run.id}`),
+ type: "run.updated" as const,
+ threadId,
+ runId: run.id,
+ occurredAt: now,
+ payload:
+ run.status === "queued"
+ ? { ...run, queueHeld: true }
+ : { ...run, status: "cancelled" as const, completedAt: now },
+ })),
+ ...before.providerTurns.map((turn) => ({
+ id: EventId.make(`restart:${turn.id}`),
+ type: "provider-turn.updated" as const,
+ threadId,
+ occurredAt: now,
+ payload: { ...turn, status: "cancelled" as const, completedAt: now },
+ })),
+ ],
+ });
+ const command = {
+ type: "queued-run.start" as const,
+ commandId: CommandId.make("send-selected"),
+ threadId,
+ runId: selected.id,
+ };
+ yield* orchestrator.dispatch(command);
+ yield* worker.drain();
+ yield* orchestrator.dispatch(command);
+ yield* worker.drain();
+ const after = yield* orchestrator.getThreadProjection(threadId);
+ assert.equal(after.runs.find((run) => run.id === selected.id)?.status, "running");
+ assert.deepEqual(
+ started.map((input) => input.message.text),
+ ["first", "selected"],
+ );
+ assert.equal(started[1]?.runId, selected.id);
+ assert.equal(started[1]?.message.messageId, selected.userMessageId);
+ assert.deepEqual(started[1]?.modelSelection, runSelection);
+ assert.deepEqual(steered, []);
+ assert.lengthOf(
+ after.messages.filter((message) => message.id === selected.userMessageId),
+ 1,
+ );
+ assert.deepEqual(
+ after.runs.filter((run) => run.status === "queued").map((run) => run.userMessageId),
+ [MessageId.make("message:queued-first"), MessageId.make("message:queued-last")],
+ );
+ assert.isFalse(after.runs.some((run) => run.status === "queued" && run.queueHeld));
+ const duplicate = yield* orchestrator
+ .dispatch({
+ ...command,
+ commandId: CommandId.make("send-selected-again"),
+ })
+ .pipe(Effect.flip);
+ assert.equal(duplicate._tag, "OrchestratorDispatchError");
+ }).pipe(Effect.provide(layer));
+ }),
+ ),
+);
+
+it.effect("keeps a message queued when send now races with a running turn", () =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const { started, layer, startFirstTurn } =
+ yield* nextTurnSelectionHarness("send-queued-race");
+ yield* Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
+ const threadId = yield* startFirstTurn;
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make("queue"),
+ threadId,
+ messageId: MessageId.make("message:queued"),
+ text: "queued",
+ attachments: [],
+ dispatchMode: { type: "queue_after_active" },
+ createdBy: "user",
+ creationSource: "web",
+ });
+ const before = yield* orchestrator.getThreadProjection(threadId);
+ const queued = before.runs.find((run) => run.status === "queued")!;
+ const error = yield* orchestrator
+ .dispatch({
+ type: "queued-run.start",
+ commandId: CommandId.make("send-now"),
+ threadId,
+ runId: queued.id,
+ })
+ .pipe(Effect.flip);
+ yield* worker.drain();
+ assert.equal(error._tag, "OrchestratorDispatchError");
+ assert.equal(started.length, 1);
+ const after = yield* orchestrator.getThreadProjection(threadId);
+ assert.deepEqual(after.runs, before.runs);
+ }).pipe(Effect.provide(layer));
+ }),
+ ),
+);
+
// regression: #19210 a provider that can restart the turn must still steer, since restarting ends its native subagents
it.effect(
"steers a changed turn-scoped selection into a running turn the provider could restart",
diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts
index b52639824d1..4e98e20949c 100644
--- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts
+++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts
@@ -167,6 +167,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
case "subagent.stop":
case "run.interrupt":
case "queued-message.promote-to-steer":
+ case "queued-run.start":
case "queue.resume":
case "queued-run.reorder":
case "queued-run.cancel":
diff --git a/apps/web/src/components/chat/QueuedRunsControl.tsx b/apps/web/src/components/chat/QueuedRunsControl.tsx
index 63d25f6bd77..15ea2318ba6 100644
--- a/apps/web/src/components/chat/QueuedRunsControl.tsx
+++ b/apps/web/src/components/chat/QueuedRunsControl.tsx
@@ -82,6 +82,7 @@ export function QueuedRunsControl({
)?.projection;
const reorder = useAtomCommand(threadEnvironment.reorderQueuedRun);
const promote = useAtomCommand(threadEnvironment.promoteQueuedRun);
+ const resume = useAtomCommand(threadEnvironment.resumeThreadQueue);
const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun);
const [expanded, setExpanded] = useState(true);
const queueListId = useId();
@@ -107,6 +108,7 @@ export function QueuedRunsControl({
const queued = workflow?.queuedRuns ?? [];
const activeRun = workflow?.activeRun ?? null;
const canReorder = workflow?.canReorder === true;
+ const canSend = workflow?.canSendNow === true || workflow?.canPromoteToSteer === true;
const queuedImageUrlById = new Map(
queuedImageAttachmentUrls.flatMap((url, index) => {
const resource = queuedImageAttachmentResources[index];
@@ -170,14 +172,21 @@ export function QueuedRunsControl({
void move(runId, queued[insertIndex]?.run.id ?? null);
};
- const steer = async (queuedRunId: RunId) => {
- if (activeRun === null || !workflow?.canPromoteToSteer || steerInFlightRef.current) return;
+ const sendQueuedMessage = async (queuedRunId: RunId) => {
+ if (!canSend || steerInFlightRef.current) return;
steerInFlightRef.current = true;
setBusyRunId(queuedRunId);
- await promote({
- environmentId: props.environmentId,
- input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id },
- });
+ if (workflow?.canSendNow) {
+ await resume({
+ environmentId: props.environmentId,
+ input: { threadId: props.threadId, runId: queuedRunId },
+ });
+ } else if (activeRun !== null) {
+ await promote({
+ environmentId: props.environmentId,
+ input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id },
+ });
+ }
steerInFlightRef.current = false;
setBusyRunId(null);
};
@@ -185,8 +194,8 @@ export function QueuedRunsControl({
useImperativeHandle(ref, () => ({
steerNext(repeat) {
const next = queued[0];
- if (!next || !workflow?.canPromoteToSteer) return false;
- if (!repeat && busyRunId === null) void steer(next.run.id);
+ if (!next || !canSend) return false;
+ if (!repeat && busyRunId === null) void sendQueuedMessage(next.run.id);
return true;
},
// Declines while a queued message is already being edited so the key keeps
@@ -424,25 +433,19 @@ export function QueuedRunsControl({
<Button
size="xs"
variant="ghost-muted"
- disabled={
- item.runId === null ||
- busyRunId !== null ||
- !workflow?.canPromoteToSteer
- }
+ disabled={item.runId === null || busyRunId !== null || !canSend}
onClick={() => {
if (item.runId !== null) {
- void steer(item.runId);
+ void sendQueuedMessage(item.runId);
}
}}
>
<CornerUpRightIcon />
- Steer
+ {workflow?.canSendNow ? "Send now" : "Steer"}
</Button>
</TooltipTrigger>
<TooltipPopup>
- {activeRun === null
- ? "There is no active run to steer"
- : `Send as a steer instead${item.serverIndex === 0 && props.steerShortcutLabel ? ` (${props.steerShortcutLabel})` : ""}`}
+ {`${workflow?.canSendNow ? "Start a turn with this message" : "Send as a steer instead"}${item.serverIndex === 0 && props.steerShortcutLabel ? ` (${props.steerShortcutLabel})` : ""}`}
</TooltipPopup>
</Tooltip>
<Tooltip>
diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.ts
index 0c9a5f32a8c..3ef6b6315ab 100644
--- a/apps/web/src/components/settings/KeybindingsSettings.logic.ts
+++ b/apps/web/src/components/settings/KeybindingsSettings.logic.ts
@@ -364,7 +364,7 @@ export function commandLabel(command: KeybindingCommand): string {
if (command === "composer.sendAlternate") return "Composer: Opposite Queue or Steer Action";
if (command === "composer.sendBackground") return "Composer: Start in Background";
if (command === "composer.sendAndNewThread") return "Composer: Send and Start New Thread";
- if (command === "thread.steerQueuedMessage") return "Queue: Send First Queued Message as Steer";
+ if (command === "thread.steerQueuedMessage") return "Queue: Send First Queued Message";
if (command === "thread.editQueuedMessage") return "Queue: Edit Last Queued Message";
if (command === "thread.copyReference") return "Pull Request: Copy Link or Thread ID";
const usageMetric = METRIC_OPTIONS.find((option) => option.command === command);
diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts
index d559e6216c3..bcfae194034 100644
--- a/packages/client-runtime/src/operations/commands.test.ts
+++ b/packages/client-runtime/src/operations/commands.test.ts
@@ -39,6 +39,7 @@ import {
archiveThread,
interruptThreadTurn,
revertThreadCheckpoint,
+ resumeThreadQueue,
startThreadTurn,
} from "./commands.ts";
@@ -136,6 +137,28 @@ const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(funct
});
describe("V2 environment commands", () => {
+ it.effect("distinguishes sending a selected queued message from resuming queue order", () =>
+ Effect.gen(function* () {
+ const commands: OrchestrationV2Command[] = [];
+ const supervisor = yield* makeSupervisor({ commands, projects: [] });
+ const threadId = ThreadId.make("thread-1");
+ yield* resumeThreadQueue({
+ commandId: CommandId.make("send-selected"),
+ threadId,
+ runId: RunId.make("selected"),
+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
+ yield* resumeThreadQueue({
+ commandId: CommandId.make("resume-queue"),
+ threadId,
+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
+
+ expect(commands).toEqual([
+ { type: "queued-run.start", commandId: "send-selected", threadId, runId: "selected" },
+ { type: "queue.resume", commandId: "resume-queue", threadId },
+ ]);
+ }).pipe(Effect.provide(layerTestCrypto)),
+ );
+
it.effect("preserves caller command ids for idempotent V2 commands", () =>
Effect.gen(function* () {
const commands: OrchestrationV2Command[] = [];
diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts
index e28df43e6a2..db343d2d0f8 100644
--- a/packages/client-runtime/src/operations/commands.ts
+++ b/packages/client-runtime/src/operations/commands.ts
@@ -219,6 +219,10 @@ export interface MergeThreadBackInput extends CommandMetadata {
readonly runId: RunId;
}
+export interface ResumeThreadQueueInput extends ThreadCommandInput {
+ readonly runId?: RunId;
+}
+
export interface ReorderQueuedRunInput extends ThreadCommandInput {
readonly runId: RunId;
readonly beforeRunId: RunId | null;
@@ -994,10 +998,12 @@ export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")(
});
export const resumeThreadQueue = Effect.fn("EnvironmentCommands.resumeThreadQueue")(function* (
- input: ThreadCommandInput,
+ input: ResumeThreadQueueInput,
) {
return yield* dispatch({
- type: "queue.resume",
+ ...(input.runId === undefined
+ ? { type: "queue.resume" as const }
+ : { type: "queued-run.start" as const, runId: input.runId }),
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
});
diff --git a/packages/client-runtime/src/state/threadCommands.ts b/packages/client-runtime/src/state/threadCommands.ts
index 73e46450cfa..0ef8d2d6e17 100644
--- a/packages/client-runtime/src/state/threadCommands.ts
+++ b/packages/client-runtime/src/state/threadCommands.ts
@@ -18,7 +18,6 @@ import {
createEnvironmentRpcCommand,
} from "./runtime.ts";
import {
- type ThreadCommandInput,
type ArchiveThreadInput,
type CancelQueuedRunInput,
type RetryWorkspacePreparationInput,
@@ -31,6 +30,7 @@ import {
type MergeThreadBackInput,
type PromoteQueuedRunInput,
type ReorderQueuedRunInput,
+ type ResumeThreadQueueInput,
type LinkThreadPullRequestInput,
type RespondToThreadApprovalInput,
type RespondToThreadUserInputInput,
@@ -356,7 +356,7 @@ export function createThreadEnvironmentAtoms<R, E>(
}),
resumeThreadQueue: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:resume-queue",
- execute: (input: ThreadCommandInput) => resumeThreadQueue(input),
+ execute: (input: ResumeThreadQueueInput) => resumeThreadQueue(input),
scheduler,
concurrency,
}),
diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts
index c07eb6493c7..e8e2c766b1e 100644
--- a/packages/client-runtime/src/state/threadWorkflows.test.ts
+++ b/packages/client-runtime/src/state/threadWorkflows.test.ts
@@ -135,8 +135,46 @@ describe("thread workflows", () => {
expect(state.activeRun?.id).toBe("active");
expect(state.canReorder).toBe(true);
expect(state.canPromoteToSteer).toBe(true);
+ expect(state.canSendNow).toBe(false);
});
+ it.each(["completed", "interrupted", "cancelled", "failed"])(
+ "allows sending a held message after a %s turn without a live session",
+ (status) => {
+ const state = deriveThreadQueueWorkflowState({
+ thread: { id: "thread", activeProviderThreadId: null },
+ runs: [
+ { id: "previous", status, ordinal: 1 },
+ { id: "queued", status: "queued", userMessageId: "message", ordinal: 2, queueHeld: true },
+ ],
+ messages: [{ id: "message", text: "Send this" }],
+ providerThreads: [],
+ providerTurns: [],
+ providerSessions: [],
+ } as never);
+
+ expect(state.canSendNow).toBe(true);
+ expect(state.canPromoteToSteer).toBe(false);
+ expect(state.isHeld).toBe(true);
+ },
+ );
+
+ it.each(["preparing", "starting", "running", "waiting"])(
+ "does not offer send now while a turn is %s",
+ (status) => {
+ const state = deriveThreadQueueWorkflowState({
+ thread: { id: "thread", activeProviderThreadId: null },
+ runs: [{ id: "active", status, ordinal: 1 }],
+ messages: [],
+ providerThreads: [],
+ providerTurns: [],
+ providerSessions: [],
+ } as never);
+
+ expect(state.canSendNow).toBe(false);
+ },
+ );
+
it("keeps held messages visible and clears the hold when they leave the queue", () => {
for (const status of ["queued", "cancelled", "starting"] as const) {
const state = deriveThreadQueueWorkflowState({
diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts
index 69e691840b8..5adec9e657e 100644
--- a/packages/client-runtime/src/state/threadWorkflows.ts
+++ b/packages/client-runtime/src/state/threadWorkflows.ts
@@ -33,6 +33,7 @@ export interface ThreadQueueWorkflowState {
readonly isHeld: boolean;
readonly canReorder: boolean;
readonly canPromoteToSteer: boolean;
+ readonly canSendNow: boolean;
}
export function resolveActiveThreadRun(projection: Pick<Projection, "runs">): Run | null {
@@ -153,6 +154,10 @@ export function deriveThreadQueueWorkflowState(projection: Projection): ThreadQu
queuedRuns,
isHeld: projection.runs.some((run) => run.status === "queued" && run.queueHeld === true),
canReorder: capabilities?.supportsQueuedMessages === true,
+ canSendNow:
+ activeRun === null &&
+ projection.thread.archivedAt == null &&
+ projection.thread.deletedAt == null,
canPromoteToSteer:
hasSteerableProviderTurn &&
(capabilities?.supportsActiveSteering === true ||
diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts
index eecc7110a1f..42483d96fee 100644
--- a/packages/contracts/src/orchestrationV2.ts
+++ b/packages/contracts/src/orchestrationV2.ts
@@ -2879,6 +2879,12 @@ export const OrchestrationV2Command = Schema.Union([
commandId: CommandId,
threadId: ThreadId,
}),
+ Schema.Struct({
+ type: Schema.Literal("queued-run.start"),
+ commandId: CommandId,
+ threadId: ThreadId,
+ runId: RunId,
+ }),
Schema.Struct({
type: Schema.Literal("queued-run.reorder"),
commandId: CommandId,