Skip to content
TypeScript

fix(server,mobile): a message you send resumes a held queue, and mobile can resume one (#21473)

Julius Marminge62d98096ca0d
diff --git a/apps/mobile/src/features/threads/ThreadComposer.tsx b/apps/mobile/src/features/threads/ThreadComposer.tsx
index 2a95b632587..8aecb5b07e6 100644
--- a/apps/mobile/src/features/threads/ThreadComposer.tsx
+++ b/apps/mobile/src/features/threads/ThreadComposer.tsx
@@ -162,6 +162,8 @@ export interface ThreadComposerProps {
readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => void;
+ /** Present while the thread's queue is held. */
+ readonly onResumeQueue: (() => Promise<void>) | null;
readonly onSendMessage: (followUp?: ActiveTurnComposerAction) => Promise<MessageId | null>;
readonly onShowUsageLimits: (report: UsageLimitsReport | null) => void;
readonly canSwitchProvider: boolean;
@@ -357,6 +359,16 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
(queuedEdit?.existingAttachments.length ?? 0) > 0;
const stripAttachments = composerStripAttachments(draftAttachments);
const showStopAction = !hasContent && props.canStopThread && queuedEdit === null;
+ const onResumeQueue = props.onResumeQueue;
+ const [resumingQueue, setResumingQueue] = useState(false);
+ const showResumeAction =
+ !hasContent && !showStopAction && queuedEdit === null && onResumeQueue !== null;
+ const handleResumeQueue = async () => {
+ if (resumingQueue || onResumeQueue === null) return;
+ setResumingQueue(true);
+ await onResumeQueue();
+ setResumingQueue(false);
+ };
const uploadStates = useAtomValue(composerAttachmentUploadsAtom);
const attachmentsUploading =
@@ -955,6 +967,13 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
disabled={!props.canOperateThread}
onPress={props.onStopThread}
/>
+ ) : showResumeAction ? (
+ <ComposerActionButton
+ accessibilityLabel="Resume queue"
+ icon="play"
+ disabled={!props.canOperateThread || resumingQueue}
+ onPress={() => void handleResumeQueue()}
+ />
) : (
<SendActionButton
accessibilityLabel={sendBlockedReason ?? sendLabel}
@@ -1050,6 +1069,13 @@ export const ThreadComposer = function ThreadComposer(props: ThreadComposerProps
disabled={!props.canOperateThread}
onPress={props.onStopThread}
/>
+ ) : showResumeAction && voicePresentation.showsSend ? (
+ <ComposerActionButton
+ accessibilityLabel="Resume queue"
+ icon="play"
+ disabled={!props.canOperateThread || resumingQueue}
+ onPress={() => void handleResumeQueue()}
+ />
) : voicePresentation.showsSend ? (
<SendActionButton
accessibilityLabel={sendBlockedReason ?? sendLabel}
diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
index 681bd852934..3890578e968 100644
--- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx
@@ -217,6 +217,8 @@ export interface ThreadDetailScreenProps {
readonly onNativePasteText: (paste: ComposerTextPaste) => Promise<void>;
readonly onRemoveDraftImage: (imageId: string) => void;
readonly onStopThread: () => void;
+ /** Present while the thread's queue is held. */
+ readonly onResumeQueue: (() => Promise<void>) | null;
readonly onSendMessage: (followUp?: ActiveTurnComposerAction) => Promise<MessageId | null>;
readonly onReconnectEnvironment: () => void;
readonly canSwitchThreadProvider: boolean;
@@ -1343,6 +1345,7 @@ export const ThreadDetailScreen = function ThreadDetailScreen(props: ThreadDetai
onNativePasteText={props.onNativePasteText}
onRemoveDraftImage={props.onRemoveDraftImage}
onStopThread={props.onStopThread}
+ onResumeQueue={props.onResumeQueue}
onSendMessage={handleSendMessage}
onShowUsageLimits={showUsageLimits}
canSwitchProvider={props.canSwitchThreadProvider}
diff --git a/apps/mobile/src/features/threads/ThreadQueueControl.tsx b/apps/mobile/src/features/threads/ThreadQueueControl.tsx
index 20e5b2f2e9a..e5920b06ebe 100644
--- a/apps/mobile/src/features/threads/ThreadQueueControl.tsx
+++ b/apps/mobile/src/features/threads/ThreadQueueControl.tsx
@@ -189,7 +189,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
>
{workflow?.isHeld && queuedRuns.length > 0 ? (
<View className="gap-2 py-3">
- <Text className="text-sm text-foreground-muted">Queue held after restart</Text>
+ <Text className="text-sm text-foreground-muted">Queue paused</Text>
<Button
label="Resume queue"
disabled={resuming || busyRunId !== null}
diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
index de3c5999410..3908d7ad923 100644
--- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
+++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx
@@ -291,6 +291,7 @@ function ThreadRouteContent(
const gitActions = useSelectedThreadGitActions();
const requests = useSelectedThreadRequests();
const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, "thread interrupt");
+ const resumeThreadQueue = useAtomCommand(threadEnvironment.resumeThreadQueue, "resume queue");
const loadEarlierHistory = useAtomCommand(threadEnvironment.loadEarlierHistory, {
label: "load earlier thread history",
reportFailure: false,
@@ -564,6 +565,14 @@ function ThreadRouteContent(
});
};
+ const handleResumeQueue = async () => {
+ if (!selectedThread) return;
+ await resumeThreadQueue({
+ environmentId: selectedThread.environmentId,
+ input: { threadId: selectedThread.id },
+ });
+ };
+
const handleOpenTerminal = (nextTerminalId?: string | null) => {
terminalDebugLog("terminal-menu:open-existing", {
terminalId: nextTerminalId ?? null,
@@ -956,6 +965,7 @@ function ThreadRouteContent(
onRemoveDraftImage={composer.onRemoveDraftImage}
serverConfig={serverConfig}
onStopThread={awaitingBootstrapTurn ? handleCancelWorktreeSetup : handleStopThread}
+ onResumeQueue={composer.queueHeld ? handleResumeQueue : null}
onSendMessage={composer.onSendMessage}
onReconnectEnvironment={handleReconnectEnvironment}
canSwitchThreadProvider={composer.canSwitchThreadProvider}
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts
index 4129527668f..f99b071bf36 100644
--- a/apps/mobile/src/state/use-thread-composer-state.ts
+++ b/apps/mobile/src/state/use-thread-composer-state.ts
@@ -351,6 +351,9 @@ export function useThreadComposerState() {
})();
// A compacting turn cannot take steering input, so follow-ups queue meanwhile.
const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true && !isCompacting;
+ // A stop or a restart holds the queue, completion wakes included, until it
+ // is resumed; the queue sheet lists only the user's own messages.
+ const queueHeld = queueWorkflow?.isHeld === true;
const runlessWorkStartedAt = selectedThreadProjection
? deriveRunlessWorkStartedAt(selectedThreadProjection.projection)
@@ -966,6 +969,7 @@ export function useThreadComposerState() {
composerDraftKey,
followUpBehavior,
canSteerActiveTurn,
+ queueHeld,
queuedRunEdit,
isSavingQueuedEdit,
cancelQueuedRunEdit,
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 11689485e6e..4464d09916e 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -4999,11 +4999,48 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
: undefined;
const queueBehindRun = activeRun ?? worktreeMissingRun;
const pendingMergeBackTransfers = pendingMergeBackTransfersForThread(projection);
- const shouldQueue =
- queueBehindRun !== undefined &&
- (dispatchMode.type === "defer_start" ||
- dispatchMode.type === "start_immediately" ||
- dispatchMode.type === "queue_after_active");
+ const startsOrQueuesRun =
+ dispatchMode.type === "defer_start" ||
+ dispatchMode.type === "start_immediately" ||
+ dispatchMode.type === "queue_after_active";
+ const shouldQueue = queueBehindRun !== undefined && startsOrQueuesRun;
+ // A message the user sends from a client means they are back, so the
+ // queue a stop or a restart held runs again, in its order, rather than
+ // waiting for a Resume.
+ // Continuations and scheduled tasks the server sends for them are not
+ // them coming back. Starting the queue still re-holds it for a failed
+ // provider or a usage limit; a queue held after worktree setup failed
+ // keeps its hold until a worktree exists, even once later messages have
+ // run, since its messages would start in the project checkout.
+ const worktreeSetupUnresolved =
+ projection.thread.worktreePath === null &&
+ projection.runs.some(
+ (run) =>
+ (run.status === "failed" || run.status === "interrupted") &&
+ run.workspacePreparation?.type === "worktree",
+ );
+ const sentByUserFromClient =
+ command.createdBy === "user" &&
+ (command.creationSource === "web" || command.creationSource === "mobile") &&
+ command.scheduledTaskId === undefined;
+ const heldRunsToRelease =
+ sentByUserFromClient && startsOrQueuesRun && !worktreeSetupUnresolved
+ ? projection.runs.filter((run) => run.status === "queued" && run.queueHeld === true)
+ : [];
+ const releasedAt = yield* DateTime.now;
+ for (const held of heldRunsToRelease) {
+ yield* emit(
+ events,
+ command,
+ )({
+ type: "run.updated",
+ threadId: command.threadId,
+ runId: held.id,
+ providerInstanceId: held.providerInstanceId,
+ occurredAt: releasedAt,
+ payload: { ...held, queueHeld: false },
+ });
+ }
if (shouldQueue) {
if (pendingMergeBackTransfers.length > 0) {
return yield* new OrchestratorDispatchError({
@@ -5113,9 +5150,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
activeAttemptId: attemptId,
status: "queued",
...(worktreeMissingRun !== undefined ||
- projection.runs.some(
- (candidate) => candidate.status === "queued" && candidate.queueHeld === true,
- )
+ (heldRunsToRelease.length === 0 &&
+ projection.runs.some(
+ (candidate) => candidate.status === "queued" && candidate.queueHeld === true,
+ ))
? { queueHeld: true }
: {}),
queuePosition:
diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
index edf5c446288..8bdf7230fd0 100644
--- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts
@@ -1815,8 +1815,38 @@ it.effect.each(["failed", "interrupted"] as const)(
});
assert.equal(queued.delivery, "queued");
const projection = yield* threads.getThreadProjection(launched.threadId);
- assert.equal(projection.runs.at(-1)?.status, "queued");
- assert.equal(projection.runs.at(-1)?.queueHeld, true);
+ const held = projection.runs.at(-1)!;
+ assert.equal(held.status, "queued");
+ assert.equal(held.queueHeld, true);
+
+ // A message the user starts does not release it: the held message would
+ // run after it in the project checkout.
+ yield* threads.sendToThread({
+ projectId,
+ commandId: CommandId.make(`command:launch:late-queued-follow-up-${ending}:start`),
+ threadId: launched.threadId,
+ messageId: MessageId.make(`message:launch:late-queued-follow-up-${ending}:start`),
+ text: "Sent after setup",
+ attachments: [],
+ mode: "auto",
+ createdBy: "user",
+ creationSource: "web",
+ });
+ // Nor does the next one, though the run that message started is now the
+ // latest and carries no workspace preparation.
+ yield* threads.sendToThread({
+ projectId,
+ commandId: CommandId.make(`command:launch:late-queued-follow-up-${ending}:again`),
+ threadId: launched.threadId,
+ messageId: MessageId.make(`message:launch:late-queued-follow-up-${ending}:again`),
+ text: "Sent after that",
+ attachments: [],
+ mode: "auto",
+ createdBy: "user",
+ creationSource: "web",
+ });
+ const after = yield* threads.getThreadProjection(launched.threadId);
+ assert.isTrue(after.runs.find((run) => run.id === held.id)?.queueHeld);
}).pipe(Effect.provide(harness.layer));
},
);
diff --git a/apps/server/src/orchestration-v2/ThreadStop.test.ts b/apps/server/src/orchestration-v2/ThreadStop.test.ts
index 66f0d73c4a5..12db927d9c6 100644
--- a/apps/server/src/orchestration-v2/ThreadStop.test.ts
+++ b/apps/server/src/orchestration-v2/ThreadStop.test.ts
@@ -12,6 +12,7 @@ import {
ProviderSessionId,
ProviderTurnId,
RuntimeRequestId,
+ ScheduledTaskId,
ThreadId,
TurnItemId,
} from "@t3tools/contracts";
@@ -538,6 +539,95 @@ it.effect.each(["thread.stop", "run.interrupt"] as const)(
}).pipe(Effect.provide(layerTest)),
);
+it.effect("a message the user sends after Stop releases the held queue; an agent's does not", () =>
+ Effect.gen(function* () {
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const projections = yield* ProjectionStore.ProjectionStoreV2;
+ const threadId = ThreadId.make("thread:stop-release");
+ const agentSend = (text: string) =>
+ orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make(`agent-send:${text}`),
+ threadId,
+ messageId: MessageId.make(`message:${threadId}:${text}`),
+ text,
+ attachments: [],
+ dispatchMode: { type: "queue_after_active" },
+ createdBy: "agent",
+ creationSource: "mcp",
+ });
+ yield* createWatchingThread(threadId, 6);
+ yield* send(threadId, "active", "start_immediately");
+ yield* send(threadId, "queued before the stop", "queue_after_active");
+ yield* orchestrator.dispatch({
+ type: "thread.stop",
+ commandId: CommandId.make("stop-release"),
+ threadId,
+ });
+ assert.deepEqual((yield* threadState(threadId)).runs, ["interrupted", "queued:held"]);
+
+ // An agent's message starts on the idle thread, but the hold is the user's.
+ yield* agentSend("agent nudge");
+ assert.deepEqual((yield* threadState(threadId)).runs, [
+ "interrupted",
+ "queued:held",
+ "starting",
+ ]);
+ const nudge = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
+ const now = yield* DateTime.now;
+ yield* projections.apply({
+ id: EventId.make("event:stop-release:nudge-completed"),
+ type: "run.updated",
+ threadId,
+ runId: nudge.id,
+ occurredAt: now,
+ payload: { ...nudge, status: "completed", completedAt: now },
+ });
+
+ // A scheduled task the user created is not the user coming back.
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ commandId: CommandId.make("scheduled-send"),
+ threadId,
+ messageId: MessageId.make(`message:${threadId}:scheduled`),
+ text: "Nightly check",
+ attachments: [],
+ dispatchMode: { type: "queue_after_active" },
+ createdBy: "user",
+ creationSource: "web",
+ scheduledTaskId: ScheduledTaskId.make("scheduled:nightly"),
+ });
+ const scheduled = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
+ assert.deepEqual((yield* threadState(threadId)).runs, [
+ "interrupted",
+ "queued:held",
+ "completed",
+ "starting",
+ ]);
+ yield* projections.apply({
+ id: EventId.make("event:stop-release:scheduled-completed"),
+ type: "run.updated",
+ threadId,
+ runId: scheduled.id,
+ occurredAt: now,
+ payload: { ...scheduled, status: "completed", completedAt: now },
+ });
+
+ // The user is back: the held message follows their run, and a wake that
+ // queues behind it is not held by the old Stop.
+ yield* send(threadId, "back", "start_immediately");
+ yield* agentSend("task finished");
+ assert.deepEqual((yield* threadState(threadId)).runs, [
+ "interrupted",
+ "queued",
+ "completed",
+ "completed",
+ "starting",
+ "queued",
+ ]);
+ }).pipe(Effect.provide(layerTest)),
+);
+
it.effect(
"thread.stop ends an idle thread's watches and accepts a thread with nothing to stop",
() =>
diff --git a/docs/user/composer.md b/docs/user/composer.md
index 5c5335350e5..66be9fe4357 100644
--- a/docs/user/composer.md
+++ b/docs/user/composer.md
@@ -206,9 +206,10 @@ Queued messages appear above the composer. Rows show a thumbnail of any attached
the text. Drag a row by its handle to reorder it, use the handle's arrow keys, promote the message
to a steer, or remove it.
-If the server restarts, saved queued messages keep their order and are held. Press
-**Resume** in an empty composer on web or desktop, or **Resume queue** in the queue
-sheet on mobile, to continue. You can edit, reorder, or remove held messages without starting them.
+If you stop the agent or the server restarts, queued messages keep their order and are held.
+Press **Resume** in an empty composer on web and desktop, or **Resume queue** on mobile, to
+continue. Sending a new message also resumes the queue, unless it steers a turn that is already
+running. You can edit, reorder, or remove held messages without starting them.
The pencil on a queued row opens that message in the composer for editing. The original message
stays in the queue until you save, and its row is highlighted while you edit. The message's