Skip to content

Commit db28b33

Browse files
radroidclaude
andcommitted
feat(web): queue messages while a chat is running (thread outbox)
Port the mobile "thread outbox" to the web app: submitting while a thread is busy or disconnected enqueues the message instead of erroring, and a drain sends the queue FIFO once the thread is idle and connected. The composer's primary action becomes "Queue" (Stop demoted to a secondary control) while busy; queued messages are editable/removable above the composer and persist across reloads via localStorage. Scope matches mobile except: image attachments are not queued (blob previews can't survive a localStorage reload) and offline new-thread creation is out of scope for v1. Includes fixes from an adversarial pre-land review: - Purge an environment's queued messages when it is removed, so they can't resurrect and auto-send if the same server is re-added (ports clearEnvironment; wires it into EnvironmentOwnedDataCleanup). - Never queue an image-only submit (it would enqueue a prompt claiming images are attached while carrying none, and discard the image); warn and keep the composer intact instead. - Show the "images aren't queued" warning only after a successful enqueue so a failed enqueue can't misinform. - Heartbeat the drain while messages are queued so a head held back only by the time-based idle-gate is delivered promptly. Known v1 limitation: no cross-tab reconciliation — two open tabs run independent drains over the same localStorage queue. Closes #20 Co-Authored-By: Claude Opus 4.8 <[email protected]>
1 parent c72b71c commit db28b33

14 files changed

Lines changed: 1898 additions & 17 deletions

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 151 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,7 +163,10 @@ import {
163163
nextProjectScriptId,
164164
projectScriptIdFromCommand,
165165
} from "~/projectScripts";
166-
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
166+
import { newCommandId, newDraftId, newMessageId, newThreadId } from "~/lib/utils";
167+
import { resolveComposerSendLabel } from "~/outbox/composerSendLabel.logic";
168+
import { enqueueThreadOutboxMessage, useThreadOutboxQueue } from "~/outbox/threadOutbox";
169+
import { ThreadOutboxQueueList } from "./chat/ThreadOutboxQueueList";
167170
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
168171
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
169172
import { useClientSettings, useEnvironmentSettings } from "../hooks/useSettings";
@@ -2044,6 +2047,21 @@ function ChatViewContent(props: ChatViewProps) {
20442047
threadError,
20452048
});
20462049
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
2050+
// Thread outbox ("queue"): submitting while the thread is busy/disconnected
2051+
// enqueues instead of erroring, and the drain sends the head once settled.
2052+
const outboxQueue = useThreadOutboxQueue(activeThread?.environmentId ?? null, activeThreadId);
2053+
const composerActiveThreadBusy = phase === "running" || isSendBusy || isRevertingCheckpoint;
2054+
const composerSendLabel = resolveComposerSendLabel({
2055+
connectionState: activeEnvironmentConnectionPhase,
2056+
activeThreadBusy: composerActiveThreadBusy,
2057+
queueCount: outboxQueue.length,
2058+
});
2059+
const composerQueueMode =
2060+
isServerThread &&
2061+
!isLocalDraftThread &&
2062+
!activePendingProgress &&
2063+
!showPlanFollowUpPrompt &&
2064+
composerSendLabel === "Queue";
20472065
const activeWorkStartedAt = deriveActiveWorkStartedAt(
20482066
activeLatestTurn,
20492067
activeThread?.session ?? null,
@@ -4465,8 +4483,135 @@ function ChatViewContent(props: ChatViewProps) {
44654483
],
44664484
);
44674485

4486+
// Enqueue the current composer content into the thread outbox. Text-only:
4487+
// terminal/element/preview/review contexts are folded into the prompt like a
4488+
// normal send, but image attachments cannot survive a reload through
4489+
// localStorage and are not carried on a queued message.
4490+
const handleQueueComposerSubmission = useCallback(async () => {
4491+
if (!activeThread || !activeProject) return;
4492+
const sendCtx = composerRef.current?.getSendContext();
4493+
if (!sendCtx?.providerAvailable) return;
4494+
const {
4495+
images: composerImages,
4496+
terminalContexts: composerTerminalContexts,
4497+
elementContexts: composerElementContexts,
4498+
previewAnnotations: composerPreviewAnnotations,
4499+
reviewComments: composerReviewComments,
4500+
selectedProvider: ctxSelectedProvider,
4501+
selectedModel: ctxSelectedModel,
4502+
selectedProviderModels: ctxSelectedProviderModels,
4503+
selectedPromptEffort: ctxSelectedPromptEffort,
4504+
selectedModelSelection: ctxSelectedModelSelection,
4505+
} = sendCtx;
4506+
const promptForSend = promptRef.current;
4507+
const { sendableTerminalContexts, hasSendableContent } = deriveComposerSendState({
4508+
prompt: promptForSend,
4509+
imageCount: composerImages.length,
4510+
terminalContexts: composerTerminalContexts,
4511+
elementContextCount:
4512+
composerElementContexts.length +
4513+
composerPreviewAnnotations.length +
4514+
composerReviewComments.length,
4515+
});
4516+
if (!hasSendableContent) return;
4517+
4518+
const messageTextWithContexts = appendElementContextsToPrompt(
4519+
appendTerminalContextsToPrompt(promptForSend, sendableTerminalContexts),
4520+
composerElementContexts,
4521+
);
4522+
const messageTextWithPreviewAnnotations = composerPreviewAnnotations.reduce(
4523+
(text, annotation) => appendPreviewAnnotationPrompt(text, annotation),
4524+
messageTextWithContexts,
4525+
);
4526+
const messageTextForSend = appendReviewCommentsToPrompt(
4527+
messageTextWithPreviewAnnotations,
4528+
composerReviewComments,
4529+
);
4530+
// The queue is text-only. If the composer holds nothing but image
4531+
// attachments (no text and no non-image context survived), there is nothing
4532+
// we can faithfully queue: enqueuing the image-only bootstrap prompt would
4533+
// deliver a message claiming images are attached while carrying none, and
4534+
// clearing the draft would destroy the image. Warn and leave the composer
4535+
// intact so the user can add text, or wait for the thread to idle and send.
4536+
if (messageTextForSend.trim().length === 0) {
4537+
if (composerImages.length > 0) {
4538+
toastManager.add(
4539+
stackedThreadToast({
4540+
type: "warning",
4541+
title: "Images can't be queued",
4542+
description:
4543+
"Queued messages are text-only. Add a message to queue, or wait until the chat is idle to send with the image.",
4544+
}),
4545+
);
4546+
}
4547+
return;
4548+
}
4549+
4550+
const queuedText = formatOutgoingPrompt({
4551+
provider: ctxSelectedProvider,
4552+
model: ctxSelectedModel,
4553+
models: ctxSelectedProviderModels,
4554+
effort: ctxSelectedPromptEffort,
4555+
text: messageTextForSend,
4556+
});
4557+
4558+
try {
4559+
await enqueueThreadOutboxMessage({
4560+
environmentId: activeThread.environmentId,
4561+
threadId: activeThread.id,
4562+
messageId: newMessageId(),
4563+
commandId: newCommandId(),
4564+
text: queuedText,
4565+
modelSelection: ctxSelectedModelSelection,
4566+
runtimeMode,
4567+
interactionMode,
4568+
createdAt: new Date().toISOString(),
4569+
});
4570+
} catch (error) {
4571+
setThreadError(
4572+
activeThread.id,
4573+
error instanceof Error ? error.message : "Failed to queue message.",
4574+
);
4575+
return;
4576+
}
4577+
4578+
// Warn about dropped images only after the text message actually entered the
4579+
// queue, so a failed enqueue never misinforms the user that images were
4580+
// "not added" when nothing was queued at all.
4581+
if (composerImages.length > 0) {
4582+
toastManager.add(
4583+
stackedThreadToast({
4584+
type: "warning",
4585+
title: "Images aren't queued",
4586+
description:
4587+
"Queued messages are text-only; attached images were not added to the queued message.",
4588+
}),
4589+
);
4590+
}
4591+
4592+
promptRef.current = "";
4593+
clearComposerDraftContent(composerDraftTarget);
4594+
composerRef.current?.resetCursorState();
4595+
}, [
4596+
activeProject,
4597+
activeThread,
4598+
clearComposerDraftContent,
4599+
composerDraftTarget,
4600+
composerRef,
4601+
interactionMode,
4602+
promptRef,
4603+
runtimeMode,
4604+
setThreadError,
4605+
]);
4606+
44684607
const onSend = async (e?: { preventDefault: () => void }) => {
44694608
e?.preventDefault();
4609+
// Queue mode routes the submit through the thread outbox instead of the
4610+
// immediate-send path (which is gated on an idle, connected thread).
4611+
if (composerQueueMode) {
4612+
await handleQueueComposerSubmission();
4613+
return;
4614+
}
44704615
if (
44714616
!activeThread ||
44724617
isSendBusy ||
@@ -5814,13 +5959,18 @@ function ChatViewContent(props: ChatViewProps) {
58145959
>
58155960
<div className="chat-composer-glass-host relative z-10 w-full rounded-[22px]">
58165961
<div ref={attachDraftHeroComposerAnchorRef} className="relative z-10">
5962+
<ThreadOutboxQueueList
5963+
environmentId={activeThread?.environmentId ?? null}
5964+
threadId={activeThreadId}
5965+
/>
58175966
<ChatComposer
58185967
composerRef={composerRef}
58195968
composerDraftTarget={composerDraftTarget}
58205969
environmentId={environmentId}
58215970
routeKind={routeKind}
58225971
routeThreadRef={routeThreadRef}
58235972
draftId={draftId}
5973+
sendLabel={composerSendLabel}
58245974
activeThreadId={activeThreadId}
58255975
activeThreadEnvironmentId={activeThread?.environmentId}
58265976
activeThread={activeThread}

‎apps/web/src/components/chat/ChatComposer.tsx‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -425,6 +425,8 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
425425
isConnecting: boolean;
426426
isEnvironmentUnavailable: boolean;
427427
hasSendableContent: boolean;
428+
sendLabel: "Send" | "Queue";
429+
canQueue: boolean;
428430
preserveComposerFocusOnPointerDown?: boolean;
429431
onPreviousPendingQuestion: () => void;
430432
onInterrupt: () => void;
@@ -452,6 +454,8 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
452454
isEnvironmentUnavailable={props.isEnvironmentUnavailable}
453455
isPreparingWorktree={props.isPreparingWorktree}
454456
hasSendableContent={props.hasSendableContent}
457+
sendLabel={props.sendLabel}
458+
canQueue={props.canQueue}
455459
preserveComposerFocusOnPointerDown={props.preserveComposerFocusOnPointerDown ?? false}
456460
onPreviousPendingQuestion={props.onPreviousPendingQuestion}
457461
onInterrupt={props.onInterrupt}
@@ -514,6 +518,8 @@ export interface ChatComposerProps {
514518
routeKind: "server" | "draft";
515519
routeThreadRef: ScopedThreadRef;
516520
draftId: DraftId | null;
521+
/** Primary-action label: "Queue" when a submit will enqueue, else "Send". */
522+
sendLabel: "Send" | "Queue";
517523

518524
// Thread context
519525
activeThreadId: ThreadId | null;
@@ -629,11 +635,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
629635
routeKind,
630636
routeThreadRef,
631637
draftId,
638+
sendLabel,
632639
activeThreadId,
633640
activeThreadEnvironmentId: _activeThreadEnvironmentId,
634641
activeThread,
635-
isServerThread: _isServerThread,
636-
isLocalDraftThread: _isLocalDraftThread,
642+
isServerThread,
643+
isLocalDraftThread,
637644
forceExpandedOnMobile,
638645
projectSelectionRequired,
639646
phase,
@@ -852,6 +859,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
852859
[providerInstanceEntries, selectedInstanceId],
853860
);
854861
const noProviderAvailable = selectedProviderEntry === undefined;
862+
// Queuing is only supported for existing server threads with a usable
863+
// provider and project; the primary action shows "Queue" and moves Stop to a
864+
// secondary control only under these conditions.
865+
const canQueueSubmit =
866+
isServerThread && !isLocalDraftThread && !noProviderAvailable && !projectSelectionRequired;
855867
// The driver kind follows the instance that will actually run the turn,
856868
// which can differ from the persisted selection when that selection is
857869
// disabled.
@@ -3171,6 +3183,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
31713183
}
31723184
isPreparingWorktree={isPreparingWorktree}
31733185
hasSendableContent={composerSendState.hasSendableContent}
3186+
sendLabel={canQueueSubmit ? sendLabel : "Send"}
3187+
canQueue={canQueueSubmit}
31743188
preserveComposerFocusOnPointerDown={isMobileViewport}
31753189
onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}
31763190
onInterrupt={handleInterruptPrimaryAction}

‎apps/web/src/components/chat/ComposerPrimaryActions.tsx‎

Lines changed: 53 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,14 @@ interface ComposerPrimaryActionsProps {
2626
isEnvironmentUnavailable: boolean;
2727
isPreparingWorktree: boolean;
2828
hasSendableContent: boolean;
29+
/** "Queue" when a submit will enqueue to the thread outbox, else "Send". */
30+
sendLabel?: "Send" | "Queue";
31+
/**
32+
* Whether queuing is available for this thread. When true and the thread is
33+
* running, the primary action becomes a "Queue" submit and Stop moves to a
34+
* secondary control instead of being the sole primary action.
35+
*/
36+
canQueue?: boolean;
2937
preserveComposerFocusOnPointerDown?: boolean;
3038
onPreviousPendingQuestion: () => void;
3139
onInterrupt: () => void;
@@ -65,6 +73,8 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
6573
isEnvironmentUnavailable,
6674
isPreparingWorktree,
6775
hasSendableContent,
76+
sendLabel = "Send",
77+
canQueue = false,
6878
preserveComposerFocusOnPointerDown = false,
6979
onPreviousPendingQuestion,
7080
onInterrupt,
@@ -78,6 +88,32 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
7888
environmentIdentificationMode === "artwork",
7989
);
8090

91+
const stopButton = (
92+
<button
93+
type="button"
94+
className="flex size-8 cursor-pointer items-center justify-center rounded-full bg-destructive/90 text-white shadow-xs shadow-destructive/24 inset-shadow-[0_1px_--theme(--color-white/16%)] transition-all duration-150 hover:bg-destructive hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none sm:h-8 sm:w-8"
95+
{...pointerFocusProps}
96+
onClick={onInterrupt}
97+
aria-label="Stop generation"
98+
>
99+
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true">
100+
<rect x="2" y="2" width="8" height="8" rx="1.5" />
101+
</svg>
102+
</button>
103+
);
104+
105+
const queueButton = (
106+
<Button
107+
type="submit"
108+
size="sm"
109+
className={cn("rounded-full", compact ? "px-3" : "px-4")}
110+
{...pointerFocusProps}
111+
disabled={!hasSendableContent}
112+
>
113+
Queue
114+
</Button>
115+
);
116+
81117
if (pendingAction) {
82118
return (
83119
<div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
@@ -130,19 +166,17 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
130166
}
131167

132168
if (isRunning) {
133-
return (
134-
<button
135-
type="button"
136-
className="flex size-8 cursor-pointer items-center justify-center rounded-full bg-destructive/90 text-white shadow-xs shadow-destructive/24 inset-shadow-[0_1px_--theme(--color-white/16%)] transition-all duration-150 hover:bg-destructive hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none sm:h-8 sm:w-8"
137-
{...pointerFocusProps}
138-
onClick={onInterrupt}
139-
aria-label="Stop generation"
140-
>
141-
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true">
142-
<rect x="2" y="2" width="8" height="8" rx="1.5" />
143-
</svg>
144-
</button>
145-
);
169+
// While the thread is busy, queuing (when available) becomes the primary
170+
// action and Stop moves beside it as a secondary control.
171+
if (canQueue) {
172+
return (
173+
<div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
174+
{stopButton}
175+
{queueButton}
176+
</div>
177+
);
178+
}
179+
return stopButton;
146180
}
147181

148182
if (showPlanFollowUpPrompt) {
@@ -199,6 +233,12 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
199233
);
200234
}
201235

236+
// Idle but the submit will still enqueue (outbox non-empty, or disconnected):
237+
// surface an explicit "Queue" control so Return/click reads as queuing.
238+
if (sendLabel === "Queue" && canQueue) {
239+
return queueButton;
240+
}
241+
202242
return (
203243
<button
204244
type="submit"

0 commit comments

Comments
 (0)