Skip to content

Commit 9057996

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 b0d0ba1 commit 9057996

14 files changed

Lines changed: 1888 additions & 4 deletions

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

Lines changed: 156 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -171,8 +171,11 @@ import {
171171
nextProjectScriptId,
172172
projectScriptIdFromCommand,
173173
} from "~/projectScripts";
174-
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
174+
import { newCommandId, newDraftId, newMessageId, newThreadId } from "~/lib/utils";
175175
import { useBrowserHistoryStore } from "~/browserHistoryStore";
176+
import { resolveComposerSendLabel } from "~/outbox/composerSendLabel.logic";
177+
import { enqueueThreadOutboxMessage, useThreadOutboxQueue } from "~/outbox/threadOutbox";
178+
import { ThreadOutboxQueueList } from "./chat/ThreadOutboxQueueList";
176179
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
177180
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
178181
import {
@@ -2239,6 +2242,21 @@ function ChatViewContent(props: ChatViewProps) {
22392242
threadError,
22402243
});
22412244
const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;
2245+
// Thread outbox ("queue"): submitting while the thread is busy/disconnected
2246+
// enqueues instead of erroring, and the drain sends the head once settled.
2247+
const outboxQueue = useThreadOutboxQueue(activeThread?.environmentId ?? null, activeThreadId);
2248+
const composerActiveThreadBusy = phase === "running" || isSendBusy || isRevertingCheckpoint;
2249+
const composerSendLabel = resolveComposerSendLabel({
2250+
connectionState: activeEnvironmentConnectionPhase,
2251+
activeThreadBusy: composerActiveThreadBusy,
2252+
queueCount: outboxQueue.length,
2253+
});
2254+
const composerQueueMode =
2255+
isServerThread &&
2256+
!isLocalDraftThread &&
2257+
!activePendingProgress &&
2258+
!showPlanFollowUpPrompt &&
2259+
composerSendLabel === "Queue";
22422260
const activeWorkStartedAt = deriveActiveWorkStartedAt(
22432261
activeLatestTurn,
22442262
activeThread?.session ?? null,
@@ -4783,6 +4801,127 @@ function ChatViewContent(props: ChatViewProps) {
47834801
],
47844802
);
47854803

4804+
// Enqueue the current composer content into the thread outbox. Text-only:
4805+
// terminal/element/preview/review contexts are folded into the prompt like a
4806+
// normal send, but image attachments cannot survive a reload through
4807+
// localStorage and are not carried on a queued message.
4808+
const handleQueueComposerSubmission = useCallback(async () => {
4809+
if (!activeThread || !activeProject) return;
4810+
const sendCtx = composerRef.current?.getSendContext();
4811+
if (!sendCtx?.providerAvailable) return;
4812+
const {
4813+
images: composerImages,
4814+
terminalContexts: composerTerminalContexts,
4815+
elementContexts: composerElementContexts,
4816+
previewAnnotations: composerPreviewAnnotations,
4817+
reviewComments: composerReviewComments,
4818+
selectedProvider: ctxSelectedProvider,
4819+
selectedModel: ctxSelectedModel,
4820+
selectedProviderModels: ctxSelectedProviderModels,
4821+
selectedPromptEffort: ctxSelectedPromptEffort,
4822+
selectedModelSelection: ctxSelectedModelSelection,
4823+
} = sendCtx;
4824+
const promptForSend = promptRef.current;
4825+
const { sendableTerminalContexts, hasSendableContent } = deriveComposerSendState({
4826+
prompt: promptForSend,
4827+
imageCount: composerImages.length,
4828+
terminalContexts: composerTerminalContexts,
4829+
elementContextCount:
4830+
composerElementContexts.length +
4831+
composerPreviewAnnotations.length +
4832+
composerReviewComments.length,
4833+
});
4834+
if (!hasSendableContent) return;
4835+
4836+
const messageTextWithContexts = appendElementContextsToPrompt(
4837+
appendTerminalContextsToPrompt(promptForSend, sendableTerminalContexts),
4838+
composerElementContexts,
4839+
);
4840+
const messageTextWithPreviewAnnotations = composerPreviewAnnotations.reduce(
4841+
(text, annotation) => appendPreviewAnnotationPrompt(text, annotation),
4842+
messageTextWithContexts,
4843+
);
4844+
const messageTextForSend = appendReviewCommentsToPrompt(
4845+
messageTextWithPreviewAnnotations,
4846+
composerReviewComments,
4847+
);
4848+
// The queue is text-only. If the composer holds nothing but image
4849+
// attachments (no text and no non-image context survived), there is nothing
4850+
// we can faithfully queue: enqueuing the image-only bootstrap prompt would
4851+
// deliver a message claiming images are attached while carrying none, and
4852+
// clearing the draft would destroy the image. Warn and leave the composer
4853+
// intact so the user can add text, or wait for the thread to idle and send.
4854+
if (messageTextForSend.trim().length === 0) {
4855+
if (composerImages.length > 0) {
4856+
toastManager.add(
4857+
stackedThreadToast({
4858+
type: "warning",
4859+
title: "Images can't be queued",
4860+
description:
4861+
"Queued messages are text-only. Add a message to queue, or wait until the chat is idle to send with the image.",
4862+
}),
4863+
);
4864+
}
4865+
return;
4866+
}
4867+
4868+
const queuedText = formatOutgoingPrompt({
4869+
provider: ctxSelectedProvider,
4870+
model: ctxSelectedModel,
4871+
models: ctxSelectedProviderModels,
4872+
effort: ctxSelectedPromptEffort,
4873+
text: messageTextForSend,
4874+
});
4875+
4876+
try {
4877+
await enqueueThreadOutboxMessage({
4878+
environmentId: activeThread.environmentId,
4879+
threadId: activeThread.id,
4880+
messageId: newMessageId(),
4881+
commandId: newCommandId(),
4882+
text: queuedText,
4883+
modelSelection: ctxSelectedModelSelection,
4884+
runtimeMode,
4885+
interactionMode,
4886+
createdAt: new Date().toISOString(),
4887+
});
4888+
} catch (error) {
4889+
setThreadError(
4890+
activeThread.id,
4891+
error instanceof Error ? error.message : "Failed to queue message.",
4892+
);
4893+
return;
4894+
}
4895+
4896+
// Warn about dropped images only after the text message actually entered the
4897+
// queue, so a failed enqueue never misinforms the user that images were
4898+
// "not added" when nothing was queued at all.
4899+
if (composerImages.length > 0) {
4900+
toastManager.add(
4901+
stackedThreadToast({
4902+
type: "warning",
4903+
title: "Images aren't queued",
4904+
description:
4905+
"Queued messages are text-only; attached images were not added to the queued message.",
4906+
}),
4907+
);
4908+
}
4909+
4910+
promptRef.current = "";
4911+
clearComposerDraftContent(composerDraftTarget);
4912+
composerRef.current?.resetCursorState();
4913+
}, [
4914+
activeProject,
4915+
activeThread,
4916+
clearComposerDraftContent,
4917+
composerDraftTarget,
4918+
composerRef,
4919+
interactionMode,
4920+
promptRef,
4921+
runtimeMode,
4922+
setThreadError,
4923+
]);
4924+
47864925
const onSend = async (
47874926
e?: { preventDefault: () => void },
47884927
directAnnotation?: {
@@ -4801,6 +4940,17 @@ function ChatViewContent(props: ChatViewProps) {
48014940
}),
48024941
);
48034942
};
4943+
// Queue mode routes the submit through the thread outbox instead of the
4944+
// immediate-send path (which is gated on an idle, connected thread).
4945+
//
4946+
// A direct annotation is deliberately excluded: queued messages are
4947+
// text-only, so enqueuing one would drop the annotation silently. Letting it
4948+
// fall through reaches upstream's gate below, which tells the user the
4949+
// annotation stayed on the draft.
4950+
if (composerQueueMode && !directAnnotation) {
4951+
await handleQueueComposerSubmission();
4952+
return;
4953+
}
48044954
if (
48054955
!activeThread ||
48064956
isSendBusy ||
@@ -6201,13 +6351,18 @@ function ChatViewContent(props: ChatViewProps) {
62016351
>
62026352
<div className="chat-composer-glass-host relative z-10 w-full rounded-[22px]">
62036353
<div ref={attachDraftHeroComposerAnchorRef} className="relative z-10">
6354+
<ThreadOutboxQueueList
6355+
environmentId={activeThread?.environmentId ?? null}
6356+
threadId={activeThreadId}
6357+
/>
62046358
<ChatComposer
62056359
composerRef={composerRef}
62066360
composerDraftTarget={composerDraftTarget}
62076361
environmentId={environmentId}
62086362
routeKind={routeKind}
62096363
routeThreadRef={routeThreadRef}
62106364
draftId={draftId}
6365+
sendLabel={composerSendLabel}
62116366
activeThreadId={activeThreadId}
62126367
activeThreadEnvironmentId={activeThread?.environmentId}
62136368
activeThread={activeThread}

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

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,8 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
406406
isConnecting: boolean;
407407
isEnvironmentUnavailable: boolean;
408408
hasSendableContent: boolean;
409+
sendLabel: "Send" | "Queue";
410+
canQueue: boolean;
409411
preserveComposerFocusOnPointerDown?: boolean;
410412
onPreviousPendingQuestion: () => void;
411413
onInterrupt: () => void;
@@ -434,6 +436,8 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
434436
isEnvironmentUnavailable={props.isEnvironmentUnavailable}
435437
isPreparingWorktree={props.isPreparingWorktree}
436438
hasSendableContent={props.hasSendableContent}
439+
sendLabel={props.sendLabel}
440+
canQueue={props.canQueue}
437441
preserveComposerFocusOnPointerDown={props.preserveComposerFocusOnPointerDown ?? false}
438442
onPreviousPendingQuestion={props.onPreviousPendingQuestion}
439443
onInterrupt={props.onInterrupt}
@@ -496,6 +500,8 @@ export interface ChatComposerProps {
496500
routeKind: "server" | "draft";
497501
routeThreadRef: ScopedThreadRef;
498502
draftId: DraftId | null;
503+
/** Primary-action label: "Queue" when a submit will enqueue, else "Send". */
504+
sendLabel: "Send" | "Queue";
499505

500506
// Thread context
501507
activeThreadId: ThreadId | null;
@@ -607,11 +613,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
607613
routeKind,
608614
routeThreadRef,
609615
draftId,
616+
sendLabel,
610617
activeThreadId,
611618
activeThreadEnvironmentId: _activeThreadEnvironmentId,
612619
activeThread,
613-
isServerThread: _isServerThread,
614-
isLocalDraftThread: _isLocalDraftThread,
620+
isServerThread,
621+
isLocalDraftThread,
615622
forceExpandedOnMobile,
616623
projectSelectionRequired,
617624
phase,
@@ -826,6 +833,11 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
826833
[providerInstanceEntries, selectedInstanceId],
827834
);
828835
const noProviderAvailable = selectedProviderEntry === undefined;
836+
// Queuing is only supported for existing server threads with a usable
837+
// provider and project; the primary action shows "Queue" and moves Stop to a
838+
// secondary control only under these conditions.
839+
const canQueueSubmit =
840+
isServerThread && !isLocalDraftThread && !noProviderAvailable && !projectSelectionRequired;
829841
// The driver kind follows the instance that will actually run the turn,
830842
// which can differ from the persisted selection when that selection is
831843
// disabled.
@@ -3200,6 +3212,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
32003212
}
32013213
isPreparingWorktree={isPreparingWorktree}
32023214
hasSendableContent={composerSendState.hasSendableContent}
3215+
sendLabel={canQueueSubmit ? sendLabel : "Send"}
3216+
canQueue={canQueueSubmit}
32033217
preserveComposerFocusOnPointerDown={isMobileViewport}
32043218
onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion}
32053219
onInterrupt={handleInterruptPrimaryAction}

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

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,14 @@ interface ComposerPrimaryActionsProps {
2525
isEnvironmentUnavailable: boolean;
2626
isPreparingWorktree: boolean;
2727
hasSendableContent: boolean;
28+
/** "Queue" when a submit will enqueue to the thread outbox, else "Send". */
29+
sendLabel?: "Send" | "Queue";
30+
/**
31+
* Whether queuing is available for this thread. When true and the thread is
32+
* running, the primary action becomes a "Queue" submit and Stop moves to a
33+
* secondary control instead of being the sole primary action.
34+
*/
35+
canQueue?: boolean;
2836
preserveComposerFocusOnPointerDown?: boolean;
2937
onPreviousPendingQuestion: () => void;
3038
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,
@@ -92,6 +102,18 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
92102
</button>
93103
);
94104

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+
95117
if (pendingAction) {
96118
return (
97119
<div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
@@ -148,6 +170,16 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
148170
}
149171

150172
if (isRunning) {
173+
// While the thread is busy, queuing (when available) becomes the primary
174+
// action and Stop moves beside it as a secondary control.
175+
if (canQueue) {
176+
return (
177+
<div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
178+
{renderStopGenerationButton(false)}
179+
{queueButton}
180+
</div>
181+
);
182+
}
151183
return renderStopGenerationButton(false);
152184
}
153185

@@ -208,6 +240,12 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
208240
);
209241
}
210242

243+
// Idle but the submit will still enqueue (outbox non-empty, or disconnected):
244+
// surface an explicit "Queue" control so Return/click reads as queuing.
245+
if (sendLabel === "Queue" && canQueue) {
246+
return queueButton;
247+
}
248+
211249
return (
212250
<button
213251
type="submit"

0 commit comments

Comments
 (0)