Skip to content

Commit ce78f5d

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 f434954 commit ce78f5d

14 files changed

Lines changed: 1890 additions & 4 deletions

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

Lines changed: 156 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,9 +179,12 @@ import {
179179
nextProjectScriptId,
180180
projectScriptIdFromCommand,
181181
} from "~/projectScripts";
182-
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
182+
import { newCommandId, newDraftId, newMessageId, newThreadId } from "~/lib/utils";
183183
import { useBrowserHistoryStore } from "~/browserHistoryStore";
184184
import { registerFaviconProjectForThread } from "~/browserFaviconStore";
185+
import { resolveComposerSendLabel } from "~/outbox/composerSendLabel.logic";
186+
import { enqueueThreadOutboxMessage, useThreadOutboxQueue } from "~/outbox/threadOutbox";
187+
import { ThreadOutboxQueueList } from "./chat/ThreadOutboxQueueList";
185188
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
186189
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
187190
import {
@@ -2319,6 +2322,21 @@ function ChatViewContent(props: ChatViewProps) {
23192322
threadError,
23202323
});
23212324
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
2325+
// Thread outbox ("queue"): submitting while the thread is busy/disconnected
2326+
// enqueues instead of erroring, and the drain sends the head once settled.
2327+
const outboxQueue = useThreadOutboxQueue(activeThread?.environmentId ?? null, activeThreadId);
2328+
const composerActiveThreadBusy = phase === "running" || isSendBusy || isRevertingCheckpoint;
2329+
const composerSendLabel = resolveComposerSendLabel({
2330+
connectionState: activeEnvironmentConnectionPhase,
2331+
activeThreadBusy: composerActiveThreadBusy,
2332+
queueCount: outboxQueue.length,
2333+
});
2334+
const composerQueueMode =
2335+
isServerThread &&
2336+
!isLocalDraftThread &&
2337+
!activePendingProgress &&
2338+
!showPlanFollowUpPrompt &&
2339+
composerSendLabel === "Queue";
23222340
const activeWorkStartedAt = deriveActiveWorkStartedAt(
23232341
activeLatestTurn,
23242342
activeThread?.session ?? null,
@@ -4906,6 +4924,127 @@ function ChatViewContent(props: ChatViewProps) {
49064924
],
49074925
);
49084926

4927+
// Enqueue the current composer content into the thread outbox. Text-only:
4928+
// terminal/element/preview/review contexts are folded into the prompt like a
4929+
// normal send, but image attachments cannot survive a reload through
4930+
// localStorage and are not carried on a queued message.
4931+
const handleQueueComposerSubmission = useCallback(async () => {
4932+
if (!activeThread || !activeProject) return;
4933+
const sendCtx = composerRef.current?.getSendContext();
4934+
if (!sendCtx?.providerAvailable) return;
4935+
const {
4936+
images: composerImages,
4937+
terminalContexts: composerTerminalContexts,
4938+
elementContexts: composerElementContexts,
4939+
previewAnnotations: composerPreviewAnnotations,
4940+
reviewComments: composerReviewComments,
4941+
selectedProvider: ctxSelectedProvider,
4942+
selectedModel: ctxSelectedModel,
4943+
selectedProviderModels: ctxSelectedProviderModels,
4944+
selectedPromptEffort: ctxSelectedPromptEffort,
4945+
selectedModelSelection: ctxSelectedModelSelection,
4946+
} = sendCtx;
4947+
const promptForSend = promptRef.current;
4948+
const { sendableTerminalContexts, hasSendableContent } = deriveComposerSendState({
4949+
prompt: promptForSend,
4950+
imageCount: composerImages.length,
4951+
terminalContexts: composerTerminalContexts,
4952+
elementContextCount:
4953+
composerElementContexts.length +
4954+
composerPreviewAnnotations.length +
4955+
composerReviewComments.length,
4956+
});
4957+
if (!hasSendableContent) return;
4958+
4959+
const messageTextWithContexts = appendElementContextsToPrompt(
4960+
appendTerminalContextsToPrompt(promptForSend, sendableTerminalContexts),
4961+
composerElementContexts,
4962+
);
4963+
const messageTextWithPreviewAnnotations = composerPreviewAnnotations.reduce(
4964+
(text, annotation) => appendPreviewAnnotationPrompt(text, annotation),
4965+
messageTextWithContexts,
4966+
);
4967+
const messageTextForSend = appendReviewCommentsToPrompt(
4968+
messageTextWithPreviewAnnotations,
4969+
composerReviewComments,
4970+
);
4971+
// The queue is text-only. If the composer holds nothing but image
4972+
// attachments (no text and no non-image context survived), there is nothing
4973+
// we can faithfully queue: enqueuing the image-only bootstrap prompt would
4974+
// deliver a message claiming images are attached while carrying none, and
4975+
// clearing the draft would destroy the image. Warn and leave the composer
4976+
// intact so the user can add text, or wait for the thread to idle and send.
4977+
if (messageTextForSend.trim().length === 0) {
4978+
if (composerImages.length > 0) {
4979+
toastManager.add(
4980+
stackedThreadToast({
4981+
type: "warning",
4982+
title: "Images can't be queued",
4983+
description:
4984+
"Queued messages are text-only. Add a message to queue, or wait until the chat is idle to send with the image.",
4985+
}),
4986+
);
4987+
}
4988+
return;
4989+
}
4990+
4991+
const queuedText = formatOutgoingPrompt({
4992+
provider: ctxSelectedProvider,
4993+
model: ctxSelectedModel,
4994+
models: ctxSelectedProviderModels,
4995+
effort: ctxSelectedPromptEffort,
4996+
text: messageTextForSend,
4997+
});
4998+
4999+
try {
5000+
await enqueueThreadOutboxMessage({
5001+
environmentId: activeThread.environmentId,
5002+
threadId: activeThread.id,
5003+
messageId: newMessageId(),
5004+
commandId: newCommandId(),
5005+
text: queuedText,
5006+
modelSelection: ctxSelectedModelSelection,
5007+
runtimeMode,
5008+
interactionMode,
5009+
createdAt: new Date().toISOString(),
5010+
});
5011+
} catch (error) {
5012+
setThreadError(
5013+
activeThread.id,
5014+
error instanceof Error ? error.message : "Failed to queue message.",
5015+
);
5016+
return;
5017+
}
5018+
5019+
// Warn about dropped images only after the text message actually entered the
5020+
// queue, so a failed enqueue never misinforms the user that images were
5021+
// "not added" when nothing was queued at all.
5022+
if (composerImages.length > 0) {
5023+
toastManager.add(
5024+
stackedThreadToast({
5025+
type: "warning",
5026+
title: "Images aren't queued",
5027+
description:
5028+
"Queued messages are text-only; attached images were not added to the queued message.",
5029+
}),
5030+
);
5031+
}
5032+
5033+
promptRef.current = "";
5034+
clearComposerDraftContent(composerDraftTarget);
5035+
composerRef.current?.resetCursorState();
5036+
}, [
5037+
activeProject,
5038+
activeThread,
5039+
clearComposerDraftContent,
5040+
composerDraftTarget,
5041+
composerRef,
5042+
interactionMode,
5043+
promptRef,
5044+
runtimeMode,
5045+
setThreadError,
5046+
]);
5047+
49095048
const onSend = async (
49105049
e?: { preventDefault: () => void },
49115050
directAnnotation?: {
@@ -4924,6 +5063,17 @@ function ChatViewContent(props: ChatViewProps) {
49245063
}),
49255064
);
49265065
};
5066+
// Queue mode routes the submit through the thread outbox instead of the
5067+
// immediate-send path (which is gated on an idle, connected thread).
5068+
//
5069+
// A direct annotation is deliberately excluded: queued messages are
5070+
// text-only, so enqueuing one would drop the annotation silently. Letting it
5071+
// fall through reaches upstream's gate below, which tells the user the
5072+
// annotation stayed on the draft.
5073+
if (composerQueueMode && !directAnnotation) {
5074+
await handleQueueComposerSubmission();
5075+
return;
5076+
}
49275077
if (
49285078
!activeThread ||
49295079
isSendBusy ||
@@ -6416,13 +6566,18 @@ function ChatViewContent(props: ChatViewProps) {
64166566
>
64176567
<div className="chat-composer-glass-host relative z-10 w-full rounded-[22px]">
64186568
<div ref={attachDraftHeroComposerAnchorRef} className="relative z-10">
6569+
<ThreadOutboxQueueList
6570+
environmentId={activeThread?.environmentId ?? null}
6571+
threadId={activeThreadId}
6572+
/>
64196573
<ChatComposer
64206574
composerRef={composerRef}
64216575
composerDraftTarget={composerDraftTarget}
64226576
environmentId={environmentId}
64236577
routeKind={routeKind}
64246578
routeThreadRef={routeThreadRef}
64256579
draftId={draftId}
6580+
sendLabel={composerSendLabel}
64266581
activeThreadId={activeThreadId}
64276582
activeThreadEnvironmentId={activeThread?.environmentId}
64286583
activeThread={activeThread}

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

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,8 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
411411
isConnecting: boolean;
412412
isEnvironmentUnavailable: boolean;
413413
hasSendableContent: boolean;
414+
sendLabel: "Send" | "Queue";
415+
canQueue: boolean;
414416
preserveComposerFocusOnPointerDown?: boolean;
415417
showSendWhileRunning?: boolean;
416418
onPreviousPendingQuestion: () => void;
@@ -440,6 +442,8 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
440442
isEnvironmentUnavailable={props.isEnvironmentUnavailable}
441443
isPreparingWorktree={props.isPreparingWorktree}
442444
hasSendableContent={props.hasSendableContent}
445+
sendLabel={props.sendLabel}
446+
canQueue={props.canQueue}
443447
preserveComposerFocusOnPointerDown={props.preserveComposerFocusOnPointerDown ?? false}
444448
showSendWhileRunning={props.showSendWhileRunning ?? false}
445449
onPreviousPendingQuestion={props.onPreviousPendingQuestion}
@@ -506,6 +510,8 @@ export interface ChatComposerProps {
506510
routeKind: "server" | "draft";
507511
routeThreadRef: ScopedThreadRef;
508512
draftId: DraftId | null;
513+
/** Primary-action label: "Queue" when a submit will enqueue, else "Send". */
514+
sendLabel: "Send" | "Queue";
509515

510516
// Thread context
511517
activeThreadId: ThreadId | null;
@@ -617,11 +623,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
617623
routeKind,
618624
routeThreadRef,
619625
draftId,
626+
sendLabel,
620627
activeThreadId,
621628
activeThreadEnvironmentId: _activeThreadEnvironmentId,
622629
activeThread,
623-
isServerThread: _isServerThread,
624-
isLocalDraftThread: _isLocalDraftThread,
630+
isServerThread,
631+
isLocalDraftThread,
625632
forceExpandedOnMobile,
626633
projectSelectionRequired,
627634
phase,
@@ -836,6 +843,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
836843
[providerInstanceEntries, selectedInstanceId],
837844
);
838845
const noProviderAvailable = selectedProviderEntry === undefined;
846+
// Queuing is only supported for existing server threads with a usable
847+
// provider and project; the primary action shows "Queue" and moves Stop to a
848+
// secondary control only under these conditions.
849+
const canQueueSubmit =
850+
isServerThread && !isLocalDraftThread && !noProviderAvailable && !projectSelectionRequired;
839851
// The driver kind follows the instance that will actually run the turn,
840852
// which can differ from the persisted selection when that selection is
841853
// disabled.
@@ -3229,6 +3241,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
32293241
}
32303242
isPreparingWorktree={isPreparingWorktree}
32313243
hasSendableContent={composerSendState.hasSendableContent}
3244+
sendLabel={canQueueSubmit ? sendLabel : "Send"}
3245+
canQueue={canQueueSubmit}
32323246
preserveComposerFocusOnPointerDown={isMobileViewport}
32333247
showSendWhileRunning={isMobileViewport}
32343248
onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}

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

Lines changed: 40 additions & 0 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
/** Enter-to-send is disabled on mobile viewports, where stop would otherwise
3240
* be the only primary action and a running turn could not be steered. */
@@ -70,6 +78,8 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
7078
isEnvironmentUnavailable,
7179
isPreparingWorktree,
7280
hasSendableContent,
81+
sendLabel = "Send",
82+
canQueue = false,
7383
preserveComposerFocusOnPointerDown = false,
7484
showSendWhileRunning = false,
7585
onPreviousPendingQuestion,
@@ -106,6 +116,18 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
106116
</button>
107117
);
108118

119+
const queueButton = (
120+
<Button
121+
type="submit"
122+
size="sm"
123+
className={cn("rounded-full", compact ? "px-3" : "px-4")}
124+
{...pointerFocusProps}
125+
disabled={!hasSendableContent}
126+
>
127+
Queue
128+
</Button>
129+
);
130+
109131
if (pendingAction) {
110132
return (
111133
<div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
@@ -271,9 +293,27 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
271293
);
272294

273295
if (!isRunning) {
296+
// Idle but the submit will still enqueue (outbox non-empty, or disconnected):
297+
// surface an explicit "Queue" control so Return/click reads as queuing.
298+
if (sendLabel === "Queue" && canQueue) {
299+
return queueButton;
300+
}
274301
return sendButton;
275302
}
276303

304+
// While the thread is busy, queuing (when available) becomes the primary action and
305+
// Stop moves beside it as a secondary control. This also satisfies upstream's
306+
// showSendWhileRunning intent (#4781) -- the running turn stays reachable on mobile,
307+
// and Queue *is* the send action here, so it stands in for the send button.
308+
if (canQueue) {
309+
return (
310+
<div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
311+
{renderStopGenerationButton(false)}
312+
{queueButton}
313+
</div>
314+
);
315+
}
316+
277317
return (
278318
<>
279319
{renderStopGenerationButton(false)}

0 commit comments

Comments
 (0)