Skip to content

Commit 55e5b10

Browse files
radroidclaude
authored 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 5f30391 commit 55e5b10

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";
@@ -2136,6 +2139,21 @@ function ChatViewContent(props: ChatViewProps) {
21362139
threadError,
21372140
});
21382141
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
2142+
// Thread outbox ("queue"): submitting while the thread is busy/disconnected
2143+
// enqueues instead of erroring, and the drain sends the head once settled.
2144+
const outboxQueue = useThreadOutboxQueue(activeThread?.environmentId ?? null, activeThreadId);
2145+
const composerActiveThreadBusy = phase === "running" || isSendBusy || isRevertingCheckpoint;
2146+
const composerSendLabel = resolveComposerSendLabel({
2147+
connectionState: activeEnvironmentConnectionPhase,
2148+
activeThreadBusy: composerActiveThreadBusy,
2149+
queueCount: outboxQueue.length,
2150+
});
2151+
const composerQueueMode =
2152+
isServerThread &&
2153+
!isLocalDraftThread &&
2154+
!activePendingProgress &&
2155+
!showPlanFollowUpPrompt &&
2156+
composerSendLabel === "Queue";
21392157
const activeWorkStartedAt = deriveActiveWorkStartedAt(
21402158
activeLatestTurn,
21412159
activeThread?.session ?? null,
@@ -4556,8 +4574,135 @@ function ChatViewContent(props: ChatViewProps) {
45564574
],
45574575
);
45584576

4577+
// Enqueue the current composer content into the thread outbox. Text-only:
4578+
// terminal/element/preview/review contexts are folded into the prompt like a
4579+
// normal send, but image attachments cannot survive a reload through
4580+
// localStorage and are not carried on a queued message.
4581+
const handleQueueComposerSubmission = useCallback(async () => {
4582+
if (!activeThread || !activeProject) return;
4583+
const sendCtx = composerRef.current?.getSendContext();
4584+
if (!sendCtx?.providerAvailable) return;
4585+
const {
4586+
images: composerImages,
4587+
terminalContexts: composerTerminalContexts,
4588+
elementContexts: composerElementContexts,
4589+
previewAnnotations: composerPreviewAnnotations,
4590+
reviewComments: composerReviewComments,
4591+
selectedProvider: ctxSelectedProvider,
4592+
selectedModel: ctxSelectedModel,
4593+
selectedProviderModels: ctxSelectedProviderModels,
4594+
selectedPromptEffort: ctxSelectedPromptEffort,
4595+
selectedModelSelection: ctxSelectedModelSelection,
4596+
} = sendCtx;
4597+
const promptForSend = promptRef.current;
4598+
const { sendableTerminalContexts, hasSendableContent } = deriveComposerSendState({
4599+
prompt: promptForSend,
4600+
imageCount: composerImages.length,
4601+
terminalContexts: composerTerminalContexts,
4602+
elementContextCount:
4603+
composerElementContexts.length +
4604+
composerPreviewAnnotations.length +
4605+
composerReviewComments.length,
4606+
});
4607+
if (!hasSendableContent) return;
4608+
4609+
const messageTextWithContexts = appendElementContextsToPrompt(
4610+
appendTerminalContextsToPrompt(promptForSend, sendableTerminalContexts),
4611+
composerElementContexts,
4612+
);
4613+
const messageTextWithPreviewAnnotations = composerPreviewAnnotations.reduce(
4614+
(text, annotation) => appendPreviewAnnotationPrompt(text, annotation),
4615+
messageTextWithContexts,
4616+
);
4617+
const messageTextForSend = appendReviewCommentsToPrompt(
4618+
messageTextWithPreviewAnnotations,
4619+
composerReviewComments,
4620+
);
4621+
// The queue is text-only. If the composer holds nothing but image
4622+
// attachments (no text and no non-image context survived), there is nothing
4623+
// we can faithfully queue: enqueuing the image-only bootstrap prompt would
4624+
// deliver a message claiming images are attached while carrying none, and
4625+
// clearing the draft would destroy the image. Warn and leave the composer
4626+
// intact so the user can add text, or wait for the thread to idle and send.
4627+
if (messageTextForSend.trim().length === 0) {
4628+
if (composerImages.length > 0) {
4629+
toastManager.add(
4630+
stackedThreadToast({
4631+
type: "warning",
4632+
title: "Images can't be queued",
4633+
description:
4634+
"Queued messages are text-only. Add a message to queue, or wait until the chat is idle to send with the image.",
4635+
}),
4636+
);
4637+
}
4638+
return;
4639+
}
4640+
4641+
const queuedText = formatOutgoingPrompt({
4642+
provider: ctxSelectedProvider,
4643+
model: ctxSelectedModel,
4644+
models: ctxSelectedProviderModels,
4645+
effort: ctxSelectedPromptEffort,
4646+
text: messageTextForSend,
4647+
});
4648+
4649+
try {
4650+
await enqueueThreadOutboxMessage({
4651+
environmentId: activeThread.environmentId,
4652+
threadId: activeThread.id,
4653+
messageId: newMessageId(),
4654+
commandId: newCommandId(),
4655+
text: queuedText,
4656+
modelSelection: ctxSelectedModelSelection,
4657+
runtimeMode,
4658+
interactionMode,
4659+
createdAt: new Date().toISOString(),
4660+
});
4661+
} catch (error) {
4662+
setThreadError(
4663+
activeThread.id,
4664+
error instanceof Error ? error.message : "Failed to queue message.",
4665+
);
4666+
return;
4667+
}
4668+
4669+
// Warn about dropped images only after the text message actually entered the
4670+
// queue, so a failed enqueue never misinforms the user that images were
4671+
// "not added" when nothing was queued at all.
4672+
if (composerImages.length > 0) {
4673+
toastManager.add(
4674+
stackedThreadToast({
4675+
type: "warning",
4676+
title: "Images aren't queued",
4677+
description:
4678+
"Queued messages are text-only; attached images were not added to the queued message.",
4679+
}),
4680+
);
4681+
}
4682+
4683+
promptRef.current = "";
4684+
clearComposerDraftContent(composerDraftTarget);
4685+
composerRef.current?.resetCursorState();
4686+
}, [
4687+
activeProject,
4688+
activeThread,
4689+
clearComposerDraftContent,
4690+
composerDraftTarget,
4691+
composerRef,
4692+
interactionMode,
4693+
promptRef,
4694+
runtimeMode,
4695+
setThreadError,
4696+
]);
4697+
45594698
const onSend = async (e?: { preventDefault: () => void }) => {
45604699
e?.preventDefault();
4700+
// Queue mode routes the submit through the thread outbox instead of the
4701+
// immediate-send path (which is gated on an idle, connected thread).
4702+
if (composerQueueMode) {
4703+
await handleQueueComposerSubmission();
4704+
return;
4705+
}
45614706
if (
45624707
!activeThread ||
45634708
isSendBusy ||
@@ -5909,13 +6054,18 @@ function ChatViewContent(props: ChatViewProps) {
59096054
>
59106055
<div className="chat-composer-glass-host relative z-10 w-full rounded-[22px]">
59116056
<div ref={attachDraftHeroComposerAnchorRef} className="relative z-10">
6057+
<ThreadOutboxQueueList
6058+
environmentId={activeThread?.environmentId ?? null}
6059+
threadId={activeThreadId}
6060+
/>
59126061
<ChatComposer
59136062
composerRef={composerRef}
59146063
composerDraftTarget={composerDraftTarget}
59156064
environmentId={environmentId}
59166065
routeKind={routeKind}
59176066
routeThreadRef={routeThreadRef}
59186067
draftId={draftId}
6068+
sendLabel={composerSendLabel}
59196069
activeThreadId={activeThreadId}
59206070
activeThreadEnvironmentId={activeThread?.environmentId}
59216071
activeThread={activeThread}

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

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,8 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
422422
isConnecting: boolean;
423423
isEnvironmentUnavailable: boolean;
424424
hasSendableContent: boolean;
425+
sendLabel: "Send" | "Queue";
426+
canQueue: boolean;
425427
preserveComposerFocusOnPointerDown?: boolean;
426428
onPreviousPendingQuestion: () => void;
427429
onInterrupt: () => void;
@@ -450,6 +452,8 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
450452
isEnvironmentUnavailable={props.isEnvironmentUnavailable}
451453
isPreparingWorktree={props.isPreparingWorktree}
452454
hasSendableContent={props.hasSendableContent}
455+
sendLabel={props.sendLabel}
456+
canQueue={props.canQueue}
453457
preserveComposerFocusOnPointerDown={props.preserveComposerFocusOnPointerDown ?? false}
454458
onPreviousPendingQuestion={props.onPreviousPendingQuestion}
455459
onInterrupt={props.onInterrupt}
@@ -512,6 +516,8 @@ export interface ChatComposerProps {
512516
routeKind: "server" | "draft";
513517
routeThreadRef: ScopedThreadRef;
514518
draftId: DraftId | null;
519+
/** Primary-action label: "Queue" when a submit will enqueue, else "Send". */
520+
sendLabel: "Send" | "Queue";
515521

516522
// Thread context
517523
activeThreadId: ThreadId | null;
@@ -628,11 +634,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
628634
routeKind,
629635
routeThreadRef,
630636
draftId,
637+
sendLabel,
631638
activeThreadId,
632639
activeThreadEnvironmentId: _activeThreadEnvironmentId,
633640
activeThread,
634-
isServerThread: _isServerThread,
635-
isLocalDraftThread: _isLocalDraftThread,
641+
isServerThread,
642+
isLocalDraftThread,
636643
forceExpandedOnMobile,
637644
projectSelectionRequired,
638645
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.
@@ -3223,6 +3235,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
32233235
}
32243236
isPreparingWorktree={isPreparingWorktree}
32253237
hasSendableContent={composerSendState.hasSendableContent}
3238+
sendLabel={canQueueSubmit ? sendLabel : "Send"}
3239+
canQueue={canQueueSubmit}
32263240
preserveComposerFocusOnPointerDown={isMobileViewport}
32273241
onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}
32283242
onInterrupt={handleInterruptPrimaryAction}

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

Lines changed: 53 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,14 @@ interface ComposerPrimaryActionsProps {
2727
isEnvironmentUnavailable: boolean;
2828
isPreparingWorktree: boolean;
2929
hasSendableContent: boolean;
30+
/** "Queue" when a submit will enqueue to the thread outbox, else "Send". */
31+
sendLabel?: "Send" | "Queue";
32+
/**
33+
* Whether queuing is available for this thread. When true and the thread is
34+
* running, the primary action becomes a "Queue" submit and Stop moves to a
35+
* secondary control instead of being the sole primary action.
36+
*/
37+
canQueue?: boolean;
3038
preserveComposerFocusOnPointerDown?: boolean;
3139
onPreviousPendingQuestion: () => void;
3240
onInterrupt: () => void;
@@ -67,6 +75,8 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
6775
isEnvironmentUnavailable,
6876
isPreparingWorktree,
6977
hasSendableContent,
78+
sendLabel = "Send",
79+
canQueue = false,
7080
preserveComposerFocusOnPointerDown = false,
7181
onPreviousPendingQuestion,
7282
onInterrupt,
@@ -81,6 +91,32 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
8191
environmentIdentificationMode === "artwork",
8292
);
8393

94+
const stopButton = (
95+
<button
96+
type="button"
97+
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"
98+
{...pointerFocusProps}
99+
onClick={onInterrupt}
100+
aria-label="Stop generation"
101+
>
102+
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true">
103+
<rect x="2" y="2" width="8" height="8" rx="1.5" />
104+
</svg>
105+
</button>
106+
);
107+
108+
const queueButton = (
109+
<Button
110+
type="submit"
111+
size="sm"
112+
className={cn("rounded-full", compact ? "px-3" : "px-4")}
113+
{...pointerFocusProps}
114+
disabled={!hasSendableContent}
115+
>
116+
Queue
117+
</Button>
118+
);
119+
84120
if (pendingAction) {
85121
return (
86122
<div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
@@ -133,19 +169,17 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
133169
}
134170

135171
if (isRunning) {
136-
return (
137-
<button
138-
type="button"
139-
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"
140-
{...pointerFocusProps}
141-
onClick={onInterrupt}
142-
aria-label="Stop generation"
143-
>
144-
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true">
145-
<rect x="2" y="2" width="8" height="8" rx="1.5" />
146-
</svg>
147-
</button>
148-
);
172+
// While the thread is busy, queuing (when available) becomes the primary
173+
// action and Stop moves beside it as a secondary control.
174+
if (canQueue) {
175+
return (
176+
<div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
177+
{stopButton}
178+
{queueButton}
179+
</div>
180+
);
181+
}
182+
return stopButton;
149183
}
150184

151185
if (showPlanFollowUpPrompt) {
@@ -202,6 +236,12 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
202236
);
203237
}
204238

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

0 commit comments

Comments
 (0)