The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 20:45 UTC
fix(queue): send selected held messages when a thread is stopped (#22790)
Yash Singh committed
Oct 21, 2026 at 06:21 UTC
96f09c6558b098f05ad0c027afa3846209c03d4f
14 files changed
+341
-44
apps/mobile/src/features/threads/ThreadQueueControl.tsx
+14
-7
@@ -149,6 +149,8 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
149
void Haptics.selectionAsync();
150
if (action === "remove") {
151
await cancel(buildCancelQueuedRunCommand({ ...target, runId }));
152
+ } else if (workflow?.canSendNow) {
153
+ await resume({ ...target, input: { threadId: target.threadId, runId } });
154
} else if (workflow?.activeRun && workflow.canPromoteToSteer) {
155
await promote({
156
...target,
@@ -221,6 +223,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
223
const controls = resolveThreadQueueRowControls({
224
busy: busyRunId !== null || draggedRunId !== null,
225
canPromoteToSteer: workflow?.canPromoteToSteer ?? false,
226
+ canSendNow: workflow?.canSendNow ?? false,
227
canReorder: workflow?.canReorder ?? false,
228
index,
229
isEditing: editing?.runId === run.id,
@@ -326,12 +329,12 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
329
accessibilityLabel={`Actions for queued message ${index + 1}`}
330
shouldOpenOnLongPress
331
actions={[
329
- ...(workflow?.canPromoteToSteer
332
+ ...(workflow?.canPromoteToSteer || workflow?.canSendNow
333
? [
334
{
335
id: "steer",
333
- title: "Steer now",
334
- attributes: { disabled: !controls.canSteer },
336
+ title: workflow?.canSendNow ? "Send now" : "Steer now",
337
+ attributes: { disabled: !controls.canSend },
338
image: Platform.OS === "ios" ? "arrow.turn.left.up" : "arrow_upward",
339
},
340
]
@@ -385,16 +388,20 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
388
Editing
389
</Text>
390
) : null}
388
- {workflow?.canPromoteToSteer ? (
391
+ {workflow?.canPromoteToSteer || workflow?.canSendNow ? (
392
<Pressable
393
accessibilityRole="button"
391
- accessibilityLabel={`Steer with message ${index + 1} now`}
392
- disabled={!controls.canSteer}
394
+ accessibilityLabel={
395
+ workflow?.canSendNow
396
+ ? `Send message ${index + 1} now`
397
+ : `Steer with message ${index + 1} now`
398
+ }
399
+ disabled={!controls.canSend}
400
onPress={() => void act(run.id, "steer")}
401
className="h-8 shrink-0 justify-center rounded-full bg-primary px-3 active:opacity-70 disabled:opacity-40"
402
>
403
<Text className="font-t3-medium text-xs text-primary-foreground">
397
- Steer
404
+ {workflow?.canSendNow ? "Send now" : "Steer"}
405
</Text>
406
</Pressable>
407
) : null}
apps/mobile/src/features/threads/threadQueueControlPresentation.test.ts
+25
-1
@@ -7,6 +7,28 @@ import {
7
} from "./threadQueueControlPresentation";
8
9
describe("threadQueueControlPresentation", () => {
10
+ it.each([
11
+ { busy: false, isEditing: false, expected: true },
12
+ { busy: true, isEditing: false, expected: false },
13
+ { busy: false, isEditing: true, expected: false },
14
+ ])(
15
+ "gates sending a stopped thread's queued message with $busy busy and $isEditing editing",
16
+ ({ busy, isEditing, expected }) => {
17
+ const controls = resolveThreadQueueRowControls({
18
+ busy,
19
+ isEditing,
20
+ canPromoteToSteer: false,
21
+ canSendNow: true,
22
+ canReorder: false,
23
+ index: 0,
24
+ queuedCount: 1,
25
+ text: "Queued message",
26
+ });
27
+
28
+ expect(controls.canSend).toBe(expected);
29
+ },
30
+ );
31
+
32
it("shows an assistant quote as its quoted text", () => {
33
const href = formatAssistantCitationHref({
34
version: 1,
@@ -22,6 +44,7 @@ describe("threadQueueControlPresentation", () => {
44
const controls = resolveThreadQueueRowControls({
45
busy: false,
46
canPromoteToSteer: true,
47
+ canSendNow: false,
48
canReorder: true,
49
index: 0,
50
queuedCount: 1,
@@ -37,6 +60,7 @@ describe("threadQueueControlPresentation", () => {
60
const editing = resolveThreadQueueRowControls({
61
busy: false,
62
canPromoteToSteer: true,
63
+ canSendNow: false,
64
canReorder: true,
65
index: 1,
66
isEditing: true,
@@ -46,7 +70,7 @@ describe("threadQueueControlPresentation", () => {
70
71
expect(editing.isEditing).toBe(true);
72
expect(editing.canEdit).toBe(false);
49
- expect(editing.canSteer).toBe(false);
73
+ expect(editing.canSend).toBe(false);
74
expect(editing.canMoveUp).toBe(true);
75
expect(editing.canDismiss).toBe(true);
76
});
apps/mobile/src/features/threads/threadQueueControlPresentation.ts
+4
-3
@@ -8,7 +8,7 @@ export interface ThreadQueueRowControls {
8
readonly canEdit: boolean;
9
readonly canMoveDown: boolean;
10
readonly canMoveUp: boolean;
11
- readonly canSteer: boolean;
11
+ readonly canSend: boolean;
12
readonly dismissAccessibilityLabel: string;
13
readonly displayText: string;
14
readonly isEditing: boolean;
@@ -17,6 +17,7 @@ export interface ThreadQueueRowControls {
17
export function resolveThreadQueueRowControls(input: {
18
readonly busy: boolean;
19
readonly canPromoteToSteer: boolean;
20
+ readonly canSendNow: boolean;
21
readonly canReorder: boolean;
22
readonly index: number;
23
readonly isEditing?: boolean;
@@ -33,9 +34,9 @@ export function resolveThreadQueueRowControls(input: {
34
canEdit: mutationEnabled && !isEditing,
35
canMoveDown: mutationEnabled && input.canReorder && input.index < input.queuedCount - 1,
36
canMoveUp: mutationEnabled && input.canReorder && input.index > 0,
36
- canSteer: mutationEnabled && input.canPromoteToSteer && !isEditing,
37
+ canSend: mutationEnabled && (input.canPromoteToSteer || input.canSendNow) && !isEditing,
38
dismissAccessibilityLabel: REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL,
38
- // Edit and Steer keep the original text so quoted citations stay linked.
39
+ // Editing and sending keep the original text so quoted citations stay linked.
40
displayText: assistantCitationsToPlainText(input.text),
41
isEditing,
42
};
apps/server/src/orchestration-v2/Orchestrator.ts
+60
-10
@@ -477,6 +477,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
477
case "subagent.stop":
478
case "run.interrupt":
479
case "queued-message.promote-to-steer":
480
+ case "queued-run.start":
481
case "queue.resume":
482
case "queued-run.reorder":
483
case "queued-run.cancel":
@@ -1277,13 +1278,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1278
const failQueuedRunStart = Effect.fn("Orchestrator.failQueuedRunStart")(function* (
1279
threadId: ThreadId,
1280
cause: unknown,
1281
+ queuedRunId?: RunId,
1282
) {
1283
const projection = yield* projectionStore.getThreadRecords(
1284
threadId,
1285
["runs", "nodes", "attempts", "providerThreads", "turnItems", "messages"],
1286
{ turnItemTypes: [], messageRoles: ["user"] },
1287
);
1286
- const queuedRun = nextQueuedRun(projection);
1288
+ const queuedRun =
1289
+ queuedRunId === undefined
1290
+ ? nextQueuedRun(projection)
1291
+ : projection.runs.find((run) => run.id === queuedRunId && run.status === "queued");
1292
if (queuedRun === undefined) return;
1293
const now = yield* DateTime.now;
1294
const rootNode = projection.nodes.find((node) => node.id === queuedRun.rootNodeId);
@@ -1384,7 +1389,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1389
const startNextQueuedRun = Effect.fn("Orchestrator.startNextQueuedRun")(
1390
function* (
1391
threadId: ThreadId,
1387
- options?: { readonly failedRunId?: RunId; readonly endedRunId?: RunId },
1392
+ options?: {
1393
+ readonly failedRunId?: RunId;
1394
+ readonly endedRunId?: RunId;
1395
+ readonly queuedRunId?: RunId;
1396
+ },
1397
) {
1398
if (!(yield* projectionStore.canStartQueuedRun(threadId))) return;
1399
const projection = yield* readCommandProjection(threadId);
@@ -1397,7 +1406,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
1406
return;
1407
}
1408
1400
- const storedQueuedRun = nextQueuedRun(projection);
1409
+ const storedQueuedRun =
1410
+ options?.queuedRunId === undefined
1411
+ ? nextQueuedRun(projection)
1412
+ : projection.runs.find(
1413
+ (run) => run.id === options.queuedRunId && run.status === "queued",
1414
+ );
1415
if (storedQueuedRun === undefined) {
1416
return;
1417
}
@@ -2087,8 +2101,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
2101
],
2102
);
2103
},
2090
- (effect, threadId, _options?) =>
2091
- effect.pipe(Effect.catch((cause) => failQueuedRunStart(threadId, cause))),
2104
+ (effect, threadId, options?) =>
2105
+ effect.pipe(
2106
+ Effect.catch((cause) => failQueuedRunStart(threadId, cause, options?.queuedRunId)),
2107
+ ),
2108
);
2109
2110
const resumeQueuedRuns = Effect.gen(function* () {
@@ -11423,6 +11439,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11439
case "queued-message.promote-to-steer":
11440
yield* dispatchQueuedMessagePromoteToSteer(command, events, effects);
11441
break;
11442
+ case "queued-run.start":
11443
case "queue.resume": {
11444
const projection = yield* loadProjectionForCommand(
11445
command,
@@ -11436,7 +11453,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11453
cause: `Thread ${command.threadId} is not active.`,
11454
});
11455
}
11439
- const nextRun = nextQueuedRun(projection);
11456
+ const selectedRunId = command.type === "queued-run.start" ? command.runId : undefined;
11457
+ const selectedRun =
11458
+ selectedRunId === undefined
11459
+ ? undefined
11460
+ : projection.runs.find((run) => run.id === selectedRunId && run.status === "queued");
11461
+ if (selectedRunId !== undefined) {
11462
+ const selectedMessage = projection.messages.find(
11463
+ (message) => message.id === selectedRun?.userMessageId,
11464
+ );
11465
+ if (
11466
+ selectedRun === undefined ||
11467
+ selectedMessage === undefined ||
11468
+ selectedMessage.delegatedCompletion !== undefined ||
11469
+ selectedMessage.notification !== undefined ||
11470
+ projection.runs.some(isBlockingRun)
11471
+ ) {
11472
+ return yield* new OrchestratorDispatchError({
11473
+ commandId: command.commandId,
11474
+ commandType: command.type,
11475
+ cause: "A queued user message can only be sent now while the thread is stopped.",
11476
+ });
11477
+ }
11478
+ }
11479
+ const nextRun = selectedRun ?? nextQueuedRun(projection);
11480
if (
11481
usageLimitHoldsQueue(
11482
projection,
@@ -11579,8 +11619,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11619
}),
11620
),
11621
);
11582
- if (command.type === "queue.resume") {
11583
- yield* mapDispatchError(command)(startNextQueuedRun(command.threadId));
11622
+ if (command.type === "queue.resume" || command.type === "queued-run.start") {
11623
+ yield* mapDispatchError(command)(
11624
+ startNextQueuedRun(
11625
+ command.threadId,
11626
+ command.type === "queued-run.start" ? { queuedRunId: command.runId } : undefined,
11627
+ ),
11628
+ );
11629
}
11630
return {
11631
sequence: receipt.resultSequence,
@@ -11712,8 +11757,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11757
detail: committed.receipt.error ?? "Previously rejected.",
11758
});
11759
}
11715
- if (command.type === "queue.resume") {
11716
- yield* mapDispatchError(command)(startNextQueuedRun(command.threadId));
11760
+ if (command.type === "queue.resume" || command.type === "queued-run.start") {
11761
+ yield* mapDispatchError(command)(
11762
+ startNextQueuedRun(
11763
+ command.threadId,
11764
+ command.type === "queued-run.start" ? { queuedRunId: command.runId } : undefined,
11765
+ ),
11766
+ );
11767
}
11768
if (command.type === "notification.delivery.accept") {
11769
yield* mapDispatchError(command)(offerDelegatedCompletionDeliveries(command.threadId));
apps/server/src/orchestration-v2/SteeringCompletion.integration.test.ts
+133
@@ -550,6 +550,139 @@ const nextTurnSelectionHarness = Effect.fn("nextTurnSelectionHarness")(function*
550
return { events, started, steered, layer, startFirstTurn };
551
});
552
553
+it.effect("sends a selected held message once and preserves the remaining queue order", () =>
554
+ Effect.scoped(
555
+ Effect.gen(function* () {
556
+ const { started, steered, layer, startFirstTurn } =
557
+ yield* nextTurnSelectionHarness("send-held-message");
558
+ yield* Effect.gen(function* () {
559
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
560
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
561
+ const threadId = yield* startFirstTurn;
562
+ yield* Effect.forEach(["queued-first", "selected", "queued-last"], (text) =>
563
+ orchestrator.dispatch({
564
+ type: "message.dispatch",
565
+ commandId: CommandId.make(text),
566
+ threadId,
567
+ messageId: MessageId.make(`message:${text}`),
568
+ text,
569
+ attachments: [],
570
+ modelSelection: runSelection,
571
+ dispatchMode: { type: "queue_after_active" },
572
+ createdBy: "user",
573
+ creationSource: "web",
574
+ }),
575
+ );
576
+ const before = yield* orchestrator.getThreadProjection(threadId);
577
+ const selected = before.runs.find(
578
+ (run) => run.userMessageId === MessageId.make("message:selected"),
579
+ )!;
580
+ const sink = yield* EventSink.EventSinkV2;
581
+ const now = yield* DateTime.now;
582
+ // Restart recovery cancels the active run and holds every queued message.
583
+ yield* sink.write({
584
+ events: [
585
+ ...before.runs.map((run) => ({
586
+ id: EventId.make(`restart:${run.id}`),
587
+ type: "run.updated" as const,
588
+ threadId,
589
+ runId: run.id,
590
+ occurredAt: now,
591
+ payload:
592
+ run.status === "queued"
593
+ ? { ...run, queueHeld: true }
594
+ : { ...run, status: "cancelled" as const, completedAt: now },
595
+ })),
596
+ ...before.providerTurns.map((turn) => ({
597
+ id: EventId.make(`restart:${turn.id}`),
598
+ type: "provider-turn.updated" as const,
599
+ threadId,
600
+ occurredAt: now,
601
+ payload: { ...turn, status: "cancelled" as const, completedAt: now },
602
+ })),
603
+ ],
604
+ });
605
+ const command = {
606
+ type: "queued-run.start" as const,
607
+ commandId: CommandId.make("send-selected"),
608
+ threadId,
609
+ runId: selected.id,
610
+ };
611
+ yield* orchestrator.dispatch(command);
612
+ yield* worker.drain();
613
+ yield* orchestrator.dispatch(command);
614
+ yield* worker.drain();
615
+ const after = yield* orchestrator.getThreadProjection(threadId);
616
+ assert.equal(after.runs.find((run) => run.id === selected.id)?.status, "running");
617
+ assert.deepEqual(
618
+ started.map((input) => input.message.text),
619
+ ["first", "selected"],
620
+ );
621
+ assert.equal(started[1]?.runId, selected.id);
622
+ assert.equal(started[1]?.message.messageId, selected.userMessageId);
623
+ assert.deepEqual(started[1]?.modelSelection, runSelection);
624
+ assert.deepEqual(steered, []);
625
+ assert.lengthOf(
626
+ after.messages.filter((message) => message.id === selected.userMessageId),
627
+ 1,
628
+ );
629
+ assert.deepEqual(
630
+ after.runs.filter((run) => run.status === "queued").map((run) => run.userMessageId),
631
+ [MessageId.make("message:queued-first"), MessageId.make("message:queued-last")],
632
+ );
633
+ assert.isFalse(after.runs.some((run) => run.status === "queued" && run.queueHeld));
634
+ const duplicate = yield* orchestrator
635
+ .dispatch({
636
+ ...command,
637
+ commandId: CommandId.make("send-selected-again"),
638
+ })
639
+ .pipe(Effect.flip);
640
+ assert.equal(duplicate._tag, "OrchestratorDispatchError");
641
+ }).pipe(Effect.provide(layer));
642
+ }),
643
+ ),
644
+);
645
+
646
+it.effect("keeps a message queued when send now races with a running turn", () =>
647
+ Effect.scoped(
648
+ Effect.gen(function* () {
649
+ const { started, layer, startFirstTurn } =
650
+ yield* nextTurnSelectionHarness("send-queued-race");
651
+ yield* Effect.gen(function* () {
652
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
653
+ const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
654
+ const threadId = yield* startFirstTurn;
655
+ yield* orchestrator.dispatch({
656
+ type: "message.dispatch",
657
+ commandId: CommandId.make("queue"),
658
+ threadId,
659
+ messageId: MessageId.make("message:queued"),
660
+ text: "queued",
661
+ attachments: [],
662
+ dispatchMode: { type: "queue_after_active" },
663
+ createdBy: "user",
664
+ creationSource: "web",
665
+ });
666
+ const before = yield* orchestrator.getThreadProjection(threadId);
667
+ const queued = before.runs.find((run) => run.status === "queued")!;
668
+ const error = yield* orchestrator
669
+ .dispatch({
670
+ type: "queued-run.start",
671
+ commandId: CommandId.make("send-now"),
672
+ threadId,
673
+ runId: queued.id,
674
+ })
675
+ .pipe(Effect.flip);
676
+ yield* worker.drain();
677
+ assert.equal(error._tag, "OrchestratorDispatchError");
678
+ assert.equal(started.length, 1);
679
+ const after = yield* orchestrator.getThreadProjection(threadId);
680
+ assert.deepEqual(after.runs, before.runs);
681
+ }).pipe(Effect.provide(layer));
682
+ }),
683
+ ),
684
+);
685
+
686
// regression: #19210 a provider that can restart the turn must still steer, since restarting ends its native subagents
687
it.effect(
688
"steers a changed turn-scoped selection into a running turn the provider could restart",
apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts
+1
@@ -167,6 +167,7 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
167
case "subagent.stop":
168
case "run.interrupt":
169
case "queued-message.promote-to-steer":
170
+ case "queued-run.start":
171
case "queue.resume":
172
case "queued-run.reorder":
173
case "queued-run.cancel":
apps/web/src/components/chat/QueuedRunsControl.tsx
+21
-18
@@ -82,6 +82,7 @@ export function QueuedRunsControl({
82
)?.projection;
83
const reorder = useAtomCommand(threadEnvironment.reorderQueuedRun);
84
const promote = useAtomCommand(threadEnvironment.promoteQueuedRun);
85
+ const resume = useAtomCommand(threadEnvironment.resumeThreadQueue);
86
const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun);
87
const [expanded, setExpanded] = useState(true);
88
const queueListId = useId();
@@ -107,6 +108,7 @@ export function QueuedRunsControl({
108
const queued = workflow?.queuedRuns ?? [];
109
const activeRun = workflow?.activeRun ?? null;
110
const canReorder = workflow?.canReorder === true;
111
+ const canSend = workflow?.canSendNow === true || workflow?.canPromoteToSteer === true;
112
const queuedImageUrlById = new Map(
113
queuedImageAttachmentUrls.flatMap((url, index) => {
114
const resource = queuedImageAttachmentResources[index];
@@ -170,14 +172,21 @@ export function QueuedRunsControl({
172
void move(runId, queued[insertIndex]?.run.id ?? null);
173
};
174
173
- const steer = async (queuedRunId: RunId) => {
174
- if (activeRun === null || !workflow?.canPromoteToSteer || steerInFlightRef.current) return;
175
+ const sendQueuedMessage = async (queuedRunId: RunId) => {
176
+ if (!canSend || steerInFlightRef.current) return;
177
steerInFlightRef.current = true;
178
setBusyRunId(queuedRunId);
177
- await promote({
178
- environmentId: props.environmentId,
179
- input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id },
180
- });
179
+ if (workflow?.canSendNow) {
180
+ await resume({
181
+ environmentId: props.environmentId,
182
+ input: { threadId: props.threadId, runId: queuedRunId },
183
+ });
184
+ } else if (activeRun !== null) {
185
+ await promote({
186
+ environmentId: props.environmentId,
187
+ input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id },
188
+ });
189
+ }
190
steerInFlightRef.current = false;
191
setBusyRunId(null);
192
};
@@ -185,8 +194,8 @@ export function QueuedRunsControl({
194
useImperativeHandle(ref, () => ({
195
steerNext(repeat) {
196
const next = queued[0];
188
- if (!next || !workflow?.canPromoteToSteer) return false;
189
- if (!repeat && busyRunId === null) void steer(next.run.id);
197
+ if (!next || !canSend) return false;
198
+ if (!repeat && busyRunId === null) void sendQueuedMessage(next.run.id);
199
return true;
200
},
201
// Declines while a queued message is already being edited so the key keeps
@@ -424,25 +433,19 @@ export function QueuedRunsControl({
433
<Button
434
size="xs"
435
variant="ghost-muted"
427
- disabled={
428
- item.runId === null ||
429
- busyRunId !== null ||
430
- !workflow?.canPromoteToSteer
431
- }
436
+ disabled={item.runId === null || busyRunId !== null || !canSend}
437
onClick={() => {
438
if (item.runId !== null) {
434
- void steer(item.runId);
439
+ void sendQueuedMessage(item.runId);
440
}
441
}}
442
>
443
<CornerUpRightIcon />
439
- Steer
444
+ {workflow?.canSendNow ? "Send now" : "Steer"}
445
</Button>
446
</TooltipTrigger>
447
<TooltipPopup>
443
- {activeRun === null
444
- ? "There is no active run to steer"
445
- : `Send as a steer instead${item.serverIndex === 0 && props.steerShortcutLabel ? ` (${props.steerShortcutLabel})` : ""}`}
448
+ {`${workflow?.canSendNow ? "Start a turn with this message" : "Send as a steer instead"}${item.serverIndex === 0 && props.steerShortcutLabel ? ` (${props.steerShortcutLabel})` : ""}`}
449
</TooltipPopup>
450
</Tooltip>
451
<Tooltip>
apps/web/src/components/settings/KeybindingsSettings.logic.ts
+1
-1
@@ -364,7 +364,7 @@ export function commandLabel(command: KeybindingCommand): string {
364
if (command === "composer.sendAlternate") return "Composer: Opposite Queue or Steer Action";
365
if (command === "composer.sendBackground") return "Composer: Start in Background";
366
if (command === "composer.sendAndNewThread") return "Composer: Send and Start New Thread";
367
- if (command === "thread.steerQueuedMessage") return "Queue: Send First Queued Message as Steer";
367
+ if (command === "thread.steerQueuedMessage") return "Queue: Send First Queued Message";
368
if (command === "thread.editQueuedMessage") return "Queue: Edit Last Queued Message";
369
if (command === "thread.copyReference") return "Pull Request: Copy Link or Thread ID";
370
const usageMetric = METRIC_OPTIONS.find((option) => option.command === command);
packages/client-runtime/src/operations/commands.test.ts
+23
@@ -39,6 +39,7 @@ import {
39
archiveThread,
40
interruptThreadTurn,
41
revertThreadCheckpoint,
42
+ resumeThreadQueue,
43
startThreadTurn,
44
} from "./commands.ts";
45
@@ -136,6 +137,28 @@ const makeSupervisor = Effect.fn("TestEnvironmentCommands.makeSupervisor")(funct
137
});
138
139
describe("V2 environment commands", () => {
140
+ it.effect("distinguishes sending a selected queued message from resuming queue order", () =>
141
+ Effect.gen(function* () {
142
+ const commands: OrchestrationV2Command[] = [];
143
+ const supervisor = yield* makeSupervisor({ commands, projects: [] });
144
+ const threadId = ThreadId.make("thread-1");
145
+ yield* resumeThreadQueue({
146
+ commandId: CommandId.make("send-selected"),
147
+ threadId,
148
+ runId: RunId.make("selected"),
149
+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
150
+ yield* resumeThreadQueue({
151
+ commandId: CommandId.make("resume-queue"),
152
+ threadId,
153
+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));
154
+
155
+ expect(commands).toEqual([
156
+ { type: "queued-run.start", commandId: "send-selected", threadId, runId: "selected" },
157
+ { type: "queue.resume", commandId: "resume-queue", threadId },
158
+ ]);
159
+ }).pipe(Effect.provide(layerTestCrypto)),
160
+ );
161
+
162
it.effect("preserves caller command ids for idempotent V2 commands", () =>
163
Effect.gen(function* () {
164
const commands: OrchestrationV2Command[] = [];
packages/client-runtime/src/operations/commands.ts
+8
-2
@@ -219,6 +219,10 @@ export interface MergeThreadBackInput extends CommandMetadata {
219
readonly runId: RunId;
220
}
221
222
+export interface ResumeThreadQueueInput extends ThreadCommandInput {
223
+ readonly runId?: RunId;
224
+}
225
+
226
export interface ReorderQueuedRunInput extends ThreadCommandInput {
227
readonly runId: RunId;
228
readonly beforeRunId: RunId | null;
@@ -994,10 +998,12 @@ export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")(
998
});
999
1000
export const resumeThreadQueue = Effect.fn("EnvironmentCommands.resumeThreadQueue")(function* (
997
- input: ThreadCommandInput,
1001
+ input: ResumeThreadQueueInput,
1002
) {
1003
return yield* dispatch({
1000
- type: "queue.resume",
1004
+ ...(input.runId === undefined
1005
+ ? { type: "queue.resume" as const }
1006
+ : { type: "queued-run.start" as const, runId: input.runId }),
1007
commandId: yield* allocateCommandId(input),
1008
threadId: input.threadId,
1009
});
packages/client-runtime/src/state/threadCommands.ts
+2
-2
@@ -18,7 +18,6 @@ import {
18
createEnvironmentRpcCommand,
19
} from "./runtime.ts";
20
import {
21
- type ThreadCommandInput,
21
type ArchiveThreadInput,
22
type CancelQueuedRunInput,
23
type RetryWorkspacePreparationInput,
@@ -31,6 +30,7 @@ import {
30
type MergeThreadBackInput,
31
type PromoteQueuedRunInput,
32
type ReorderQueuedRunInput,
33
+ type ResumeThreadQueueInput,
34
type LinkThreadPullRequestInput,
35
type RespondToThreadApprovalInput,
36
type RespondToThreadUserInputInput,
@@ -356,7 +356,7 @@ export function createThreadEnvironmentAtoms<R, E>(
356
}),
357
resumeThreadQueue: createEnvironmentCommand(runtime, {
358
label: "environment-data:commands:thread:resume-queue",
359
- execute: (input: ThreadCommandInput) => resumeThreadQueue(input),
359
+ execute: (input: ResumeThreadQueueInput) => resumeThreadQueue(input),
360
scheduler,
361
concurrency,
362
}),
packages/client-runtime/src/state/threadWorkflows.test.ts
+38
@@ -135,8 +135,46 @@ describe("thread workflows", () => {
135
expect(state.activeRun?.id).toBe("active");
136
expect(state.canReorder).toBe(true);
137
expect(state.canPromoteToSteer).toBe(true);
138
+ expect(state.canSendNow).toBe(false);
139
});
140
141
+ it.each(["completed", "interrupted", "cancelled", "failed"])(
142
+ "allows sending a held message after a %s turn without a live session",
143
+ (status) => {
144
+ const state = deriveThreadQueueWorkflowState({
145
+ thread: { id: "thread", activeProviderThreadId: null },
146
+ runs: [
147
+ { id: "previous", status, ordinal: 1 },
148
+ { id: "queued", status: "queued", userMessageId: "message", ordinal: 2, queueHeld: true },
149
+ ],
150
+ messages: [{ id: "message", text: "Send this" }],
151
+ providerThreads: [],
152
+ providerTurns: [],
153
+ providerSessions: [],
154
+ } as never);
155
+
156
+ expect(state.canSendNow).toBe(true);
157
+ expect(state.canPromoteToSteer).toBe(false);
158
+ expect(state.isHeld).toBe(true);
159
+ },
160
+ );
161
+
162
+ it.each(["preparing", "starting", "running", "waiting"])(
163
+ "does not offer send now while a turn is %s",
164
+ (status) => {
165
+ const state = deriveThreadQueueWorkflowState({
166
+ thread: { id: "thread", activeProviderThreadId: null },
167
+ runs: [{ id: "active", status, ordinal: 1 }],
168
+ messages: [],
169
+ providerThreads: [],
170
+ providerTurns: [],
171
+ providerSessions: [],
172
+ } as never);
173
+
174
+ expect(state.canSendNow).toBe(false);
175
+ },
176
+ );
177
+
178
it("keeps held messages visible and clears the hold when they leave the queue", () => {
179
for (const status of ["queued", "cancelled", "starting"] as const) {
180
const state = deriveThreadQueueWorkflowState({
packages/client-runtime/src/state/threadWorkflows.ts
+5
@@ -33,6 +33,7 @@ export interface ThreadQueueWorkflowState {
33
readonly isHeld: boolean;
34
readonly canReorder: boolean;
35
readonly canPromoteToSteer: boolean;
36
+ readonly canSendNow: boolean;
37
}
38
39
export function resolveActiveThreadRun(projection: Pick<Projection, "runs">): Run | null {
@@ -153,6 +154,10 @@ export function deriveThreadQueueWorkflowState(projection: Projection): ThreadQu
154
queuedRuns,
155
isHeld: projection.runs.some((run) => run.status === "queued" && run.queueHeld === true),
156
canReorder: capabilities?.supportsQueuedMessages === true,
157
+ canSendNow:
158
+ activeRun === null &&
159
+ projection.thread.archivedAt == null &&
160
+ projection.thread.deletedAt == null,
161
canPromoteToSteer:
162
hasSteerableProviderTurn &&
163
(capabilities?.supportsActiveSteering === true ||
packages/contracts/src/orchestrationV2.ts
+6
@@ -2879,6 +2879,12 @@ export const OrchestrationV2Command = Schema.Union([
2879
commandId: CommandId,
2880
threadId: ThreadId,
2881
}),
2882
+ Schema.Struct({
2883
+ type: Schema.Literal("queued-run.start"),
2884
+ commandId: CommandId,
2885
+ threadId: ThreadId,
2886
+ runId: RunId,
2887
+ }),
2888
Schema.Struct({
2889
type: Schema.Literal("queued-run.reorder"),
2890
commandId: CommandId,