Skip to content
TypeScript

fix(web): queued messages send while their thread is not open (#13764)

Theo Browne295d7cba09bb
diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx
index b08bf12176a..3262ff9cc4a 100644
--- a/apps/web/src/components/ChatView.tsx
+++ b/apps/web/src/components/ChatView.tsx
@@ -324,12 +324,13 @@ import {
terminalContextReference,
} from "../lib/composerContextRecords";
import {
- isQueuedMessageDue,
latestCompletedToolActivityId,
type QueuedComposerMessage,
+ type QueuedMessageSendSettings,
useQueuedMessages,
useQueuedMessageStore,
} from "../queuedMessageStore";
+import { sendQueuedMessage } from "./chat/sendQueuedMessage";
import { type ReviewCommentContext } from "../reviewCommentContext";
import { environmentCatalog } from "../connection/catalog";
import { isDesktopLocalConnectionTarget } from "../connection/desktopLocal";
@@ -7248,10 +7249,27 @@ export default function ChatView(props: ChatViewProps) {
};
const queuedMessages = useQueuedMessages(activeThreadKey ?? "");
- // Puts queued messages back into the composer, e.g. after Stop or a failed
- // send. Prompts join with blank lines; attachments and contexts are added.
+ // The composer's model and modes, as a queued message keeps them for its send.
+ const readComposerSendSettings = (
+ sendCtx: ReturnType<ChatComposerHandle["getSendContext"]>,
+ ): QueuedMessageSendSettings => ({
+ modelSelection: sendCtx.selectedModelSelection,
+ runtimeMode,
+ interactionMode: sendCtx.interactionMode,
+ promptEffort: resolvePromptInjectedEffort(
+ getProviderModelCapabilities(
+ sendCtx.selectedProviderModels,
+ sendCtx.selectedModel,
+ sendCtx.selectedProvider,
+ ),
+ sendCtx.selectedPromptEffort,
+ ),
+ });
+ // Puts queued messages back into the composer after Stop or Cancel. Prompts
+ // join with blank lines; attachments and contexts are added.
const restoreQueuedMessagesToComposer = (messages: ReadonlyArray<QueuedComposerMessage>) => {
- if (messages.length === 0) return;
+ const [firstMessage] = messages;
+ if (!firstMessage) return;
const prompts = [promptRef.current, ...messages.map((message) => message.prompt)]
.map((prompt) => prompt.trim())
.filter((prompt) => prompt.length > 0);
@@ -7279,6 +7297,8 @@ export default function ChatView(props: ChatViewProps) {
if (restoredImages.length > 0) addComposerDraftImages(composerDraftTarget, restoredImages);
if (restoredFiles.length > 0) addComposerDraftFiles(composerDraftTarget, restoredFiles);
if (overflow.length > 0 && activeThreadKey) {
+ // The overflow is the rest of the restored draft, so it follows the composer.
+ const sendCtx = composerRef.current?.getSendContext();
useQueuedMessageStore.getState().enqueue(activeThreadKey, {
prompt: "",
images: overflow.filter((attachment) => attachment.type === "image"),
@@ -7286,7 +7306,7 @@ export default function ChatView(props: ChatViewProps) {
terminalContexts: [],
previewAnnotations: [],
reviewComments: [],
- submissionIntent: "foreground",
+ sendSettings: sendCtx ? readComposerSendSettings(sendCtx) : firstMessage.sendSettings,
queuedAfterToolActivityId: latestCompletedToolActivityId(threadActivities),
// Restoration is not a send. The user decides when the overflow goes.
holdUntilUserAction: true,
@@ -7329,8 +7349,6 @@ export default function ChatView(props: ChatViewProps) {
annotation: PreviewAnnotationPayload;
image: ComposerImageAttachment | null;
},
- /** A queued message being sent now instead of the live composer draft. */
- queuedMessage?: QueuedComposerMessage,
) => {
e?.preventDefault();
// Typed out in full rather than picked from the menu. Attachments or contexts
@@ -7339,7 +7357,6 @@ export default function ChatView(props: ChatViewProps) {
usageLimitsOffered &&
usageLimitsKey !== null &&
!directAnnotation &&
- !queuedMessage &&
!composerHasNonPromptContent &&
isUsageLimitsCommand(promptRef.current)
) {
@@ -7401,9 +7418,7 @@ export default function ChatView(props: ChatViewProps) {
return;
}
if (activePendingProgress) {
- // A queued message waits until the question is answered; it must not
- // be submitted as the answer.
- if (directAnnotation || queuedMessage) {
+ if (directAnnotation) {
notifyDirectAnnotationAttached();
return;
}
@@ -7415,7 +7430,7 @@ export default function ChatView(props: ChatViewProps) {
notifyDirectAnnotationAttached();
return;
}
- const multipleModelSelections = queuedMessage ? null : sendCtx.multipleModelSelections;
+ const multipleModelSelections = sendCtx.multipleModelSelections;
if (
multipleModelSelections !== null &&
serverConfig?.environment.capabilities.requiredWorktreeBootstrap !== true
@@ -7446,8 +7461,6 @@ export default function ChatView(props: ChatViewProps) {
terminalContexts: composerTerminalContexts,
previewAnnotations: sendContextPreviewAnnotations,
reviewComments: composerReviewComments,
- } = queuedMessage ?? sendCtx;
- const {
selectedProvider: ctxSelectedProvider,
selectedModel: ctxSelectedModel,
selectedProviderModels: ctxSelectedProviderModels,
@@ -7490,13 +7503,11 @@ export default function ChatView(props: ChatViewProps) {
: sendContextPreviewAnnotations;
// A direct "send annotation" writes the draft and sends in the same tick; the reference
// must be in the text now, not after the next render.
- const promptForSend = queuedMessage
- ? queuedMessage.prompt
- : directAnnotation
- ? ensureInlineContextReferences(promptRef.current, [
- previewAnnotationContextReference(directAnnotation.annotation),
- ])
- : promptRef.current;
+ const promptForSend = directAnnotation
+ ? ensureInlineContextReferences(promptRef.current, [
+ previewAnnotationContextReference(directAnnotation.annotation),
+ ])
+ : promptRef.current;
const {
trimmedPrompt: trimmed,
sendableTerminalContexts: sendableComposerTerminalContexts,
@@ -7517,7 +7528,7 @@ export default function ChatView(props: ChatViewProps) {
composerReviewComments.length === 0
? parseCodexFeedbackCommand(trimmed)
: null;
- if (feedbackCommand && !queuedMessage && multipleModelSelections === null) {
+ if (feedbackCommand && multipleModelSelections === null) {
if (!isServerThread || activeThread.session === null) {
toastManager.add(
stackedThreadToast({
@@ -7568,7 +7579,6 @@ export default function ChatView(props: ChatViewProps) {
}
if (
!directAnnotation &&
- !queuedMessage &&
sendInteractionModeEnabled &&
showPlanFollowUpPrompt &&
activeProposedPlan &&
@@ -7640,7 +7650,7 @@ export default function ChatView(props: ChatViewProps) {
composerReviewComments.length === 0
? parseStandaloneComposerSlashCommand(trimmed)
: null;
- if (standaloneSlashCommand && !queuedMessage && multipleModelSelections === null) {
+ if (standaloneSlashCommand && multipleModelSelections === null) {
handleInteractionModeChange(standaloneSlashCommand);
promptRef.current = "";
clearComposerDraftContent(composerDraftTarget);
@@ -7661,12 +7671,6 @@ export default function ChatView(props: ChatViewProps) {
}),
);
}
- // A queued message whose only content expired would retry on every
- // boundary and block the rest of the queue. Nothing sendable is left
- // in it, so drop it and let the queue move on.
- if (queuedMessage && activeThreadKey) {
- useQueuedMessageStore.getState().remove(activeThreadKey, queuedMessage.id);
- }
return;
}
if (!activeProject) {
@@ -7679,14 +7683,26 @@ export default function ChatView(props: ChatViewProps) {
);
return;
}
+ // A queued message that will still leave on its own goes first, so a new
+ // send lines up behind it instead of overtaking it.
+ const queueStillSending =
+ activeThreadKey !== null &&
+ (useQueuedMessageStore.getState().queuesByThreadKey[activeThreadKey] ?? []).some(
+ (message) => message.sending !== undefined || !message.holdUntilUserAction,
+ );
if (
- !queuedMessage &&
!directAnnotation &&
- phase === "running" &&
activeThreadKey &&
- (settings.followUpBehavior === "queue") !== (submissionIntent === "alternate")
+ (queueStillSending ||
+ (phase === "running" &&
+ (settings.followUpBehavior === "queue") !== (submissionIntent === "alternate")))
) {
- if (composerRef.current?.validateProviderInput(promptForSend) === false) {
+ const sendSettings = readComposerSendSettings(sendCtx);
+ if (
+ composerRef.current?.validateProviderInput(
+ applyClaudePromptEffortPrefix(promptForSend, sendSettings.promptEffort),
+ ) === false
+ ) {
return;
}
useQueuedMessageStore.getState().enqueue(activeThreadKey, {
@@ -7696,7 +7712,7 @@ export default function ChatView(props: ChatViewProps) {
terminalContexts: [...composerTerminalContexts],
previewAnnotations: [...composerPreviewAnnotations],
reviewComments: [...composerReviewComments],
- submissionIntent,
+ sendSettings,
queuedAfterToolActivityId: latestCompletedToolActivityId(threadActivities),
createdAt: new Date().toISOString(),
});
@@ -7766,11 +7782,6 @@ export default function ChatView(props: ChatViewProps) {
text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
});
if (composerRef.current?.validateProviderInput(outgoingMessageText) === false) {
- // A queued message that no longer fits is held at the head for the
- // user to edit via Cancel, instead of failing on every boundary.
- if (queuedMessage && activeThreadKey) {
- useQueuedMessageStore.getState().holdAtFront(activeThreadKey, queuedMessage);
- }
return;
}
@@ -7837,41 +7848,10 @@ export default function ChatView(props: ChatViewProps) {
sendInFlightRef.current = true;
const sendGeneration = ++composerSendGenerationRef.current;
- // Every early return above leaves a queued message in the queue for a
- // later retry. From here on a failure hands it back to the composer.
- if (queuedMessage) {
- const taken = activeThreadKey
- ? useQueuedMessageStore
- .getState()
- .take(
- activeThreadKey,
- queuedMessage.id,
- latestCompletedToolActivityId(threadActivities),
- )
- : null;
- if (!taken) {
- sendInFlightRef.current = false;
- return;
- }
- }
- // Stop drains the queue. A queued send whose upload was still running at
- // that moment must not start a turn afterwards; it checks this before
- // dispatch and hands the message back to the composer instead.
- const drainGenerationAtTake = useQueuedMessageStore.getState().drainGeneration;
- // A queued send that fails goes back to the head of the queue, held. The
- // messages behind it keep their order and wait; the composer is not
- // touched, which also keeps a failure after navigation off the new
- // thread's draft. The user retries with Send now or edits with Cancel.
- const abortQueuedReplay = () => {
- if (queuedMessage && activeThreadKey) {
- useQueuedMessageStore.getState().holdAtFront(activeThreadKey, queuedMessage);
- }
- };
const attachmentCapabilitiesBeforeUpload = readLiveAttachmentCapabilities();
if (attachmentCapabilitiesBeforeUpload.fileBlockReason !== null) {
sendInFlightRef.current = false;
setThreadError(threadIdForSend, attachmentCapabilitiesBeforeUpload.fileBlockReason);
- abortQueuedReplay();
return;
}
const turnUsesAttachmentUploads =
@@ -7891,26 +7871,15 @@ export default function ChatView(props: ChatViewProps) {
if (attachmentCapabilitiesAfterUpload.fileBlockReason !== null) {
sendInFlightRef.current = false;
setThreadError(threadIdForSend, attachmentCapabilitiesAfterUpload.fileBlockReason);
- abortQueuedReplay();
return;
}
if (getUploadedAttachments({ environmentId, images: composerAttachmentsSnapshot }) === null) {
sendInFlightRef.current = false;
setThreadError(threadIdForSend, "Retry or remove failed uploads before sending.");
- abortQueuedReplay();
return;
}
}
- if (
- queuedMessage &&
- useQueuedMessageStore.getState().drainGeneration !== drainGenerationAtTake
- ) {
- sendInFlightRef.current = false;
- restoreQueuedMessagesToComposer([queuedMessage]);
- return;
- }
-
const resolvedSubmissionIntent =
(multipleModelSelections !== null || submissionIntent === "background") && isLocalDraftThread
? "background"
@@ -7951,7 +7920,6 @@ export default function ChatView(props: ChatViewProps) {
setDockedDraftHeroThreadKey((currentThreadKey) =>
currentThreadKey === activeThreadKey ? null : currentThreadKey,
);
- abortQueuedReplay();
return;
}
beginLocalDispatch({
@@ -8313,11 +8281,9 @@ export default function ChatView(props: ChatViewProps) {
}),
);
}
- if (!queuedMessage) {
- promptRef.current = "";
- clearComposerDraftContent(composerDraftTarget);
- composerRef.current?.resetCursorState();
- }
+ promptRef.current = "";
+ clearComposerDraftContent(composerDraftTarget);
+ composerRef.current?.resetCursorState();
let firstComposerImageName: string | null = null;
if (composerImagesSnapshot.length > 0) {
@@ -8552,24 +8518,7 @@ export default function ChatView(props: ChatViewProps) {
);
clearBackgroundDraftSubmissionByRef(scopeThreadRef(environmentId, threadIdForSend));
}
- if (queuedMessage) {
- setOptimisticUserMessages((existing) => {
- const removed = existing.filter((message) => message.id === messageIdForSend);
- for (const message of removed) {
- revokeUserMessagePreviewUrls(message);
- }
- const next = existing.filter((message) => message.id !== messageIdForSend);
- return next.length === existing.length ? existing : next;
- });
- // The optimistic row's preview URLs were just revoked, so the images
- // need fresh ones before the row can show them again.
- if (activeThreadKey) {
- useQueuedMessageStore.getState().holdAtFront(activeThreadKey, {
- ...queuedMessage,
- images: queuedMessage.images.map(cloneComposerImageForRetry),
- });
- }
- } else if (
+ if (
backgroundDraftOpened
? !composerDraftHasUserContent(
useComposerDraftStore.getState().getComposerDraft(composerDraftTarget),
@@ -8659,46 +8608,12 @@ export default function ChatView(props: ChatViewProps) {
}
};
- // Sends the oldest queued message once it is due: a tool call finished
- // after it was queued, or the turn ended. Only one leaves per boundary; the
- // take inside onSend re-anchors the rest.
- const sendQueuedMessage = useEffectEvent((message: QueuedComposerMessage) => {
- void onSend(undefined, message.submissionIntent, undefined, message);
- });
- const nextQueuedMessage = queuedMessages[0] ?? null;
- const latestToolActivityId = useMemo(
- () => (nextQueuedMessage ? latestCompletedToolActivityId(threadActivities) : null),
- [nextQueuedMessage, threadActivities],
- );
- // Approvals and questions block the agent; a steer landing on top of them
- // would answer nothing and confuse the turn, so the queue holds until the
- // user resolves them.
+ // Queued messages go out from QueuedMessageSender, which also covers
+ // threads that are not on screen. Send now uses the same path but skips the
+ // wait for a boundary. Approvals and questions still hold it: a steer on
+ // top of them would answer nothing and confuse the turn.
const queueBlockedByPendingRequest =
activePendingApproval !== null || pendingUserInputs.length > 0;
- // onSend bails early on transient gates (environment offline, settings not
- // hydrated, checkpoint rewinding, messages loading, machine not chosen) and
- // leaves the message queued. Re-run when any of them clear so a due message
- // does not wait for an unrelated phase change.
- const queueSendGate =
- activeEnvironmentUnavailable ||
- !clientSettingsHydrated ||
- isRevertingCheckpoint ||
- threadDetailLoading ||
- needsLoadBalancing ||
- activeProviderStatus === null;
- useEffect(() => {
- if (!nextQueuedMessage || isSendBusy || queueBlockedByPendingRequest || queueSendGate) return;
- if (sendInFlightRef.current) return;
- if (!isQueuedMessageDue({ message: nextQueuedMessage, phase, latestToolActivityId })) return;
- sendQueuedMessage(nextQueuedMessage);
- }, [
- isSendBusy,
- latestToolActivityId,
- nextQueuedMessage,
- phase,
- queueBlockedByPendingRequest,
- queueSendGate,
- ]);
// The row handlers are read from refs at call-time so their identity stays
// stable and does not bust TimelineRowCtx on every ChatView render.
@@ -8708,9 +8623,8 @@ export default function ChatView(props: ChatViewProps) {
});
queuedMessageActionsRef.current = {
steer: (id) => {
- const message = queuedMessages.find((entry) => entry.id === id);
- if (!message || sendInFlightRef.current || queueBlockedByPendingRequest) return;
- void onSend(undefined, message.submissionIntent, undefined, message);
+ if (!activeThreadRef || queueBlockedByPendingRequest) return;
+ void sendQueuedMessage(activeThreadRef, id);
},
remove: (id) => {
if (!activeThreadKey) return;
diff --git a/apps/web/src/components/QueuedMessageSender.test.tsx b/apps/web/src/components/QueuedMessageSender.test.tsx
new file mode 100644
index 00000000000..dc31694f8b9
--- /dev/null
+++ b/apps/web/src/components/QueuedMessageSender.test.tsx
@@ -0,0 +1,231 @@
+import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
+import { EnvironmentId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";
+import * as Cause from "effect/Cause";
+import { act, createElement } from "react";
+import { create, type ReactTestRenderer } from "react-test-renderer";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
+
+import { useQueuedMessageStore, type QueuedComposerMessage } from "../queuedMessageStore";
+import { sendQueuedMessage } from "./chat/sendQueuedMessage";
+import { QueuedMessageSender } from "./QueuedMessageSender";
+
+const io = vi.hoisted(() => ({
+ run: vi.fn(),
+ upload: vi.fn(),
+ toast: vi.fn(),
+ thread: null as unknown,
+ shell: { runtimeMode: "full-access", interactionMode: "default" } as Record<string, unknown>,
+}));
+const config = {
+ environment: { capabilities: { attachmentUploads: true, inlineMessageContext: true } },
+};
+vi.mock("@t3tools/client-runtime/state/runtime", async (load) => ({
+ ...(await load<typeof import("@t3tools/client-runtime/state/runtime")>()),
+ runAtomCommand: (...args: unknown[]) => io.run(...args),
+}));
+vi.mock("../rpc/atomRegistry", () => ({
+ appAtomRegistry: { get: () => new Map([["env-a", config]]) },
+}));
+vi.mock("../state/server", () => ({ environmentServerConfigsAtom: {} }));
+vi.mock("../state/threads", () => ({
+ threadEnvironment: {
+ updateMetadata: "metadata",
+ setRuntimeMode: "runtime",
+ setInteractionMode: "interaction",
+ startTurn: "start",
+ },
+}));
+vi.mock("../state/environments", () => ({
+ useEnvironment: () => ({ connection: { phase: "connected" } }),
+}));
+vi.mock("../state/entities", () => ({
+ useThread: () => io.thread,
+ useThreadStatus: () => "live",
+ useServerConfigs: () => new Map([["env-a", config]]),
+ readThreadShell: () => io.shell,
+ readThread: () => io.thread,
+}));
+vi.mock("./ui/toast", () => ({ toastManager: { add: (...args: unknown[]) => io.toast(...args) } }));
+vi.mock("../lib/attachmentUploadQueue", () => ({
+ startAttachmentUpload: vi.fn(),
+ awaitAttachmentUploads: (...args: unknown[]) => io.upload(...args),
+ getUploadedAttachments: () => [
+ { type: "image", id: "uploaded", name: "a.png", mimeType: "image/png", sizeBytes: 4 },
+ ],
+ releaseDraftAttachments: vi.fn(),
+}));
+
+const threadRef = scopeThreadRef(EnvironmentId.make("env-a"), ThreadId.make("thread-a"));
+const threadKey = scopedThreadKey(threadRef);
+const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" };
+
+function enqueue(overrides: Partial<QueuedComposerMessage> = {}) {
+ return useQueuedMessageStore.getState().enqueue(threadKey, {
+ prompt: "follow up",
+ images: [],
+ files: [],
+ terminalContexts: [],
+ previewAnnotations: [],
+ reviewComments: [],
+ sendSettings: {
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ promptEffort: null,
+ },
+ queuedAfterToolActivityId: null,
+ createdAt: "2026-09-25T00:00:00Z",
+ ...overrides,
+ });
+}
+
+const commandsRun = () => io.run.mock.calls.map((call) => call[1]);
+const queue = () => useQueuedMessageStore.getState().queuesByThreadKey[threadKey];
+
+beforeEach(() => {
+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
+ useQueuedMessageStore.setState({ queuesByThreadKey: {}, lastDispatchByThreadKey: {} });
+ io.thread = null;
+ io.run.mockReset().mockResolvedValue({ _tag: "Success", value: undefined });
+ io.upload.mockReset().mockResolvedValue(undefined);
+ io.toast.mockReset();
+ io.shell = {
+ modelSelection,
+ branch: null,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ };
+});
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe("QueuedMessageSender", () => {
+ const thread = (
+ status: string,
+ { toolActivityIds = [] as string[], userMessageIds = [] as string[] } = {},
+ ) => ({
+ session: { status, activeTurnId: null, updatedAt: status },
+ activities: toolActivityIds.map((id, index) => ({
+ id,
+ kind: "tool.completed",
+ sequence: index,
+ createdAt: "2026-09-25T00:00:01Z",
+ })),
+ messages: userMessageIds.map((id) => ({ id, role: "user" })),
+ latestTurn: null,
+ });
+ let root: ReactTestRenderer | null = null;
+ const render = () =>
+ act(() => {
+ if (root) root.update(createElement(QueuedMessageSender));
+ else root = create(createElement(QueuedMessageSender));
+ });
+ afterEach(async () => {
+ await act(() => root?.unmount());
+ root = null;
+ });
+
+ it("sends a queued message when the turn ends, with no chat view open", async () => {
+ enqueue();
+ io.thread = thread("running");
+ await render();
+ expect(commandsRun()).toEqual([]);
+
+ io.thread = thread("ready");
+ await render();
+
+ expect(commandsRun()).toEqual(["start"]);
+ expect(io.run.mock.calls[0]?.[2]).toMatchObject({
+ environmentId: "env-a",
+ input: { threadId: "thread-a", message: { text: "follow up" }, modelSelection },
+ });
+ expect(queue()).toBeUndefined();
+ });
+
+ it("holds the next message until the server picks up the one before it", async () => {
+ enqueue({ prompt: "first" });
+ enqueue({ prompt: "second" });
+ io.thread = thread("ready");
+ await render();
+ await render();
+ expect(commandsRun()).toEqual(["start"]);
+
+ // The first message started a turn; the second waits for its next tool call.
+ io.thread = thread("running", { userMessageIds: ["first"] });
+ await render();
+ expect(commandsRun()).toEqual(["start"]);
+ io.thread = thread("running", { userMessageIds: ["first"], toolActivityIds: ["tool-1"] });
+ await render();
+ expect(commandsRun()).toEqual(["start", "start"]);
+ });
+
+ it("moves on to the next message after a failed one is cancelled", async () => {
+ io.run.mockResolvedValueOnce({ _tag: "Failure", cause: Cause.fail(new Error("offline")) });
+ const first = enqueue({ prompt: "first" });
+ enqueue({ prompt: "second" });
+ io.thread = thread("ready");
+ await render();
+ expect(queue()?.[0]).toMatchObject({ prompt: "first", holdUntilUserAction: true });
+
+ await act(() => {
+ useQueuedMessageStore.getState().remove(threadKey, first.id);
+ });
+ await render();
+
+ expect(commandsRun()).toEqual(["start", "start"]);
+ expect(io.run.mock.calls[1]?.[2]).toMatchObject({ input: { message: { text: "second" } } });
+ });
+});
+
+describe("sendQueuedMessage", () => {
+ it("saves a mode changed before queueing, then starts the turn", async () => {
+ io.shell = { ...io.shell, runtimeMode: "approval-required" };
+ const message = enqueue();
+
+ await sendQueuedMessage(threadRef, message.id);
+
+ expect(commandsRun()).toEqual(["runtime", "start"]);
+ expect(io.run.mock.calls[1]?.[2]).toMatchObject({ input: { runtimeMode: "full-access" } });
+ expect(queue()).toBeUndefined();
+ });
+
+ it("gives a message back to Stop while its upload runs, without starting a turn", async () => {
+ let finishUpload!: () => void;
+ io.upload.mockReturnValue(new Promise<void>((resolve) => (finishUpload = resolve)));
+ const image = {
+ type: "image" as const,
+ id: "image-1",
+ name: "a.png",
+ mimeType: "image/png",
+ sizeBytes: 4,
+ previewUrl: "data:image/png;base64,AAAA",
+ file: new File(["AAAA"], "a.png", { type: "image/png" }),
+ };
+ const message = enqueue({ images: [image] });
+
+ const sending = sendQueuedMessage(threadRef, message.id);
+ expect(useQueuedMessageStore.getState().drain(threadKey)).toHaveLength(1);
+ finishUpload();
+ await sending;
+
+ expect(commandsRun()).toEqual([]);
+ expect(io.toast).not.toHaveBeenCalled();
+ expect(queue()).toBeUndefined();
+ });
+
+ it("holds a message at the head when the turn start fails", async () => {
+ io.run.mockResolvedValue({ _tag: "Failure", cause: Cause.fail(new Error("offline")) });
+ enqueue({ prompt: "first" });
+ const second = enqueue({ prompt: "second" });
+
+ await sendQueuedMessage(threadRef, second.id);
+
+ expect(queue()?.map((entry) => [entry.prompt, entry.holdUntilUserAction])).toEqual([
+ ["second", true],
+ ["first", undefined],
+ ]);
+ expect(io.toast).toHaveBeenCalledWith(expect.objectContaining({ description: "offline" }));
+ });
+});
diff --git a/apps/web/src/components/QueuedMessageSender.tsx b/apps/web/src/components/QueuedMessageSender.tsx
new file mode 100644
index 00000000000..86dfa8a265f
--- /dev/null
+++ b/apps/web/src/components/QueuedMessageSender.tsx
@@ -0,0 +1,100 @@
+import { parseScopedThreadKey } from "@t3tools/client-runtime/environment";
+import { derivePendingRequests } from "@t3tools/client-runtime/pending-requests";
+import { useEffect, useMemo } from "react";
+import { useShallow } from "zustand/react/shallow";
+
+import { useComposerDraftStore } from "../composerDraftStore";
+import {
+ isQueuedMessageDue,
+ latestCompletedToolActivityId,
+ useQueuedMessageStore,
+ useQueuedMessages,
+} from "../queuedMessageStore";
+import { derivePhase } from "../session-logic";
+import { useServerConfigs, useThread, useThreadStatus } from "../state/entities";
+import { useEnvironment } from "../state/environments";
+import { hasServerAcknowledgedLocalDispatch, latestTurnStartFailureId } from "./ChatView.logic";
+import { sendQueuedMessage } from "./chat/sendQueuedMessage";
+
+/**
+ * Sends queued messages when they are due, for every thread with a queue,
+ * whether or not the thread is on screen. Mounted once at the root.
+ */
+export function QueuedMessageSender() {
+ const threadKeys = useQueuedMessageStore(
+ useShallow((state) => Object.keys(state.queuesByThreadKey)),
+ );
+ return threadKeys.map((threadKey) => <ThreadQueueSender key={threadKey} threadKey={threadKey} />);
+}
+
+/**
+ * Watches one thread while it has queued messages. Reading the thread keeps
+ * its detail subscribed, so tool boundaries and the end of the turn are
+ * visible while the user is elsewhere.
+ */
+function ThreadQueueSender({ threadKey }: { threadKey: string }) {
+ const threadRef = useMemo(() => parseScopedThreadKey(threadKey), [threadKey]);
+ const thread = useThread(threadRef);
+ const threadStatus = useThreadStatus(threadRef);
+ const environmentId = threadRef?.environmentId ?? null;
+ const environment = useEnvironment(environmentId);
+ const serverConfigs = useServerConfigs();
+ const serverConfigLoaded = environmentId !== null && serverConfigs.has(environmentId);
+ const rewinding = useComposerDraftStore((store) => store.rewindingThreadKeys.has(threadKey));
+ const queue = useQueuedMessages(threadKey);
+ const next = queue[0];
+ const sending = queue.some((message) => message.sending);
+ const activities = thread?.activities;
+ const latestToolActivityId = useMemo(
+ () => latestCompletedToolActivityId(activities ?? []),
+ [activities],
+ );
+ const pendingRequests = useMemo(() => derivePendingRequests(activities ?? []), [activities]);
+ const phase = derivePhase(thread?.session ?? null);
+
+ // A send that starts a new turn leaves the thread idle until the server
+ // picks it up. Hold the next message until then, as the composer does for
+ // its own sends.
+ const lastDispatch = useQueuedMessageStore(
+ (state) => state.lastDispatchByThreadKey[threadKey]?.thread ?? null,
+ );
+ const latestUserMessageId = thread?.messages.findLast((m) => m.role === "user")?.id ?? null;
+ const waitingForServer =
+ lastDispatch !== null &&
+ !hasServerAcknowledgedLocalDispatch({
+ localDispatch: lastDispatch,
+ phase,
+ latestTurn: thread?.latestTurn ?? null,
+ latestUserMessageId,
+ session: thread?.session ?? null,
+ hasPendingApproval: pendingRequests.approvals.length > 0,
+ hasPendingUserInput: pendingRequests.userInputs.length > 0,
+ latestTurnStartFailureId: latestTurnStartFailureId(thread ?? undefined, latestUserMessageId),
+ threadError: null,
+ });
+
+ // Approvals and questions block the agent; a steer landing on top of them
+ // would answer nothing and confuse the turn, so the queue holds until the
+ // user resolves them.
+ const blocked =
+ threadRef === null ||
+ thread === null ||
+ threadStatus !== "live" ||
+ (environment !== null && environment.connection.phase !== "connected") ||
+ !serverConfigLoaded ||
+ rewinding ||
+ sending ||
+ waitingForServer ||
+ pendingRequests.approvals.length > 0 ||
+ pendingRequests.userInputs.length > 0;
+ const due =
+ next !== undefined &&
+ !blocked &&
+ isQueuedMessageDue({ message: next, phase, latestToolActivityId });
+ const nextId = next?.id;
+ useEffect(() => {
+ if (!due || !threadRef || nextId === undefined) return;
+ void sendQueuedMessage(threadRef, nextId);
+ }, [due, nextId, threadRef]);
+ return null;
+}
diff --git a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
index b2b46302dd2..d95e2251763 100644
--- a/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
+++ b/apps/web/src/components/chat/MessagesTimeline.logic.test.ts
@@ -1100,7 +1100,12 @@ describe("deriveMessagesTimelineRows", () => {
terminalContexts: [],
previewAnnotations: [],
reviewComments: [],
- submissionIntent: "foreground" as const,
+ sendSettings: {
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
+ runtimeMode: "full-access" as const,
+ interactionMode: "default" as const,
+ promptEffort: null,
+ },
queuedAfterToolActivityId: null,
createdAt: "2026-01-01T00:00:01Z",
});
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index f812f67f2bd..a1d8176207a 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -1788,11 +1788,14 @@ function QueuedMessageTimelineRow({
queuedMessage.previewAnnotations.length +
queuedMessage.reviewComments.length;
const text = queuedMessage.prompt.trim();
- const statusLabel = queuedMessage.holdUntilUserAction
- ? "Waits for Send now"
- : row.isNext
- ? "Sends after the next tool call or when the turn ends"
- : "Sends after the messages above it";
+ const sending = queuedMessage.sending !== undefined;
+ const statusLabel = sending
+ ? "Sending to the agent"
+ : queuedMessage.holdUntilUserAction
+ ? "Waits for Send now"
+ : row.isNext
+ ? "Sends after the next tool call or when the turn ends"
+ : "Sends after the messages above it";
return (
<div className="flex flex-col items-end" data-queued-message-id={queuedMessage.id}>
<div className="max-w-[80%] rounded-2xl border border-dashed border-border p-3 text-message-foreground/80">
@@ -1820,14 +1823,14 @@ function QueuedMessageTimelineRow({
<Tooltip>
<TooltipTrigger
render={<span className="inline-flex h-6 items-center gap-1" />}
- aria-label={`Queued. ${statusLabel}.`}
+ aria-label={`${sending ? "Sending" : "Queued"}. ${statusLabel}.`}
>
<ClockIcon className="size-3.5" aria-hidden />
- Queued
+ {sending ? "Sending" : "Queued"}
</TooltipTrigger>
<TooltipPopup side="bottom">{statusLabel}</TooltipPopup>
</Tooltip>
- <div className="ml-auto flex items-center gap-0.5">
+ <div className={cn("ml-auto flex items-center gap-0.5", sending && "invisible")}>
<Tooltip>
<TooltipTrigger
render={
diff --git a/apps/web/src/components/chat/sendQueuedMessage.ts b/apps/web/src/components/chat/sendQueuedMessage.ts
new file mode 100644
index 00000000000..ac10dfef48c
--- /dev/null
+++ b/apps/web/src/components/chat/sendQueuedMessage.ts
@@ -0,0 +1,211 @@
+import { scopedThreadKey } from "@t3tools/client-runtime/environment";
+import {
+ runAtomCommand,
+ squashAtomCommandFailure,
+ type AtomCommand,
+} from "@t3tools/client-runtime/state/runtime";
+import type { ScopedThreadRef } from "@t3tools/contracts";
+import { serializeLegacyContextMessage } from "@t3tools/shared/composerContextLegacySend";
+import { applyClaudePromptEffortPrefix } from "@t3tools/shared/model";
+
+import { buildMessageContext, terminalContextReference } from "../../lib/composerContextRecords";
+import { removeInlineContextReference } from "../../lib/composerContextReferences";
+import {
+ awaitAttachmentUploads,
+ getUploadedAttachments,
+ releaseDraftAttachments,
+ startAttachmentUpload,
+} from "../../lib/attachmentUploadQueue";
+import { newMessageId } from "../../lib/utils";
+import { latestCompletedToolActivityId, useQueuedMessageStore } from "../../queuedMessageStore";
+import { appAtomRegistry } from "../../rpc/atomRegistry";
+import { readThread, readThreadShell } from "../../state/entities";
+import { environmentServerConfigsAtom } from "../../state/server";
+import { threadEnvironment } from "../../state/threads";
+import {
+ createLocalDispatchSnapshot,
+ deriveComposerSendState,
+ readFileAsDataUrl,
+ resolveThreadMetadataUpdateForNextTurn,
+ revokeBlobPreviewUrl,
+} from "../ChatView.logic";
+import { toastManager } from "../ui/toast";
+import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles";
+import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "./composerPromptHistory";
+
+async function run<W, A, E>(command: AtomCommand<W, A, E>, input: W): Promise<A> {
+ const result = await runAtomCommand(appAtomRegistry, command, input, { reportFailure: false });
+ if (result._tag === "Failure") throw squashAtomCommandFailure(result);
+ return result.value;
+}
+
+/**
+ * Sends one queued message as a turn on its thread. `QueuedMessageSender`
+ * calls it when the head message is due, and Send now calls it directly. It
+ * reads nothing from the composer, so it works for threads that are not on
+ * screen. A failed send stays at the head of the queue, held for Send now.
+ */
+export async function sendQueuedMessage(
+ threadRef: ScopedThreadRef,
+ messageId: string,
+): Promise<void> {
+ const { environmentId, threadId } = threadRef;
+ const threadKey = scopedThreadKey(threadRef);
+ const queue = useQueuedMessageStore.getState();
+ const message = queue.beginSend(
+ threadKey,
+ messageId,
+ latestCompletedToolActivityId(readThread(threadRef)?.activities ?? []),
+ );
+ if (!message) return;
+ const { sendSettings } = message;
+ const attachments = [...message.images, ...message.files];
+ const readConfig = () => appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId);
+ const assertFilesAllowed = () => {
+ const config = readConfig();
+ const reason = fileAttachmentCapabilityBlockReason({
+ files: message.files,
+ attachmentUploadsCapabilityKnown: config !== undefined,
+ supportsAttachmentUploads: config?.environment.capabilities.attachmentUploads === true,
+ maxFileAttachmentBytes:
+ config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null,
+ });
+ if (reason !== null) throw new Error(reason);
+ };
+ try {
+ const { sendableTerminalContexts, hasSendableContent } = deriveComposerSendState({
+ prompt: message.prompt,
+ imageCount: attachments.length,
+ terminalContexts: message.terminalContexts,
+ elementContextCount: message.previewAnnotations.length + message.reviewComments.length,
+ });
+ // Only expired terminal context was left. Retrying would block the queue
+ // on every boundary, so drop it and let the queue move on.
+ if (!hasSendableContent) {
+ queue.finishSend(threadKey, message.id);
+ return;
+ }
+ // Expired terminal excerpts are not sent; their chips leave the text with them.
+ const prompt = message.terminalContexts
+ .filter((context) => !sendableTerminalContexts.includes(context))
+ .reduce(
+ (text, context) =>
+ removeInlineContextReference(text, terminalContextReference(context).contextId).prompt,
+ message.prompt,
+ )
+ .trim();
+ const text = applyClaudePromptEffortPrefix(
+ prompt || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
+ sendSettings.promptEffort,
+ );
+
+ assertFilesAllowed();
+ const useUploads = readConfig()?.environment.capabilities.attachmentUploads === true;
+ if (useUploads && attachments.length > 0) {
+ for (const attachment of attachments) {
+ startAttachmentUpload({ environmentId, image: attachment, draftTarget: threadRef });
+ }
+ await awaitAttachmentUploads(attachments.map((attachment) => attachment.id));
+ }
+ const wireAttachments = await Promise.all(
+ attachments.map(async (attachment) => {
+ if (useUploads) {
+ const uploaded = getUploadedAttachments({ environmentId, images: [attachment] })?.[0];
+ if (!uploaded) throw new Error(`Attachment '${attachment.name}' did not upload.`);
+ return uploaded;
+ }
+ if (attachment.type !== "image") {
+ throw new Error("This server does not support file attachments.");
+ }
+ return {
+ type: "image" as const,
+ id: attachment.id,
+ name: attachment.name,
+ mimeType: attachment.mimeType,
+ sizeBytes: attachment.sizeBytes,
+ dataUrl: await readFileAsDataUrl(attachment.file),
+ ...(attachment.source ? { source: attachment.source } : {}),
+ };
+ }),
+ );
+ assertFilesAllowed();
+
+ // The server starts the turn with the thread's stored modes, so a change
+ // made in the composer before queueing is saved first.
+ const createdAt = new Date().toISOString();
+ const shell = readThreadShell(threadRef);
+ const metadataUpdate = shell
+ ? resolveThreadMetadataUpdateForNextTurn({
+ currentModelSelection: shell.modelSelection,
+ nextModelSelection: sendSettings.modelSelection,
+ currentBranch: shell.branch,
+ })
+ : null;
+ if (metadataUpdate) {
+ await run(threadEnvironment.updateMetadata, {
+ environmentId,
+ input: { threadId, ...metadataUpdate },
+ });
+ }
+ if (shell && shell.runtimeMode !== sendSettings.runtimeMode) {
+ await run(threadEnvironment.setRuntimeMode, {
+ environmentId,
+ input: { threadId, runtimeMode: sendSettings.runtimeMode, createdAt },
+ });
+ }
+ if (shell && shell.interactionMode !== sendSettings.interactionMode) {
+ await run(threadEnvironment.setInteractionMode, {
+ environmentId,
+ input: { threadId, interactionMode: sendSettings.interactionMode, createdAt },
+ });
+ }
+
+ // Stop hands a preparing message back to the composer. Past this point
+ // the send can no longer be taken back.
+ const thread = readThread(threadRef) ?? undefined;
+ if (!queue.markDispatching(threadKey, message.id, createLocalDispatchSnapshot(thread))) return;
+ const context = buildMessageContext({
+ terminalContexts: sendableTerminalContexts,
+ reviewComments: message.reviewComments,
+ previewAnnotations: message.previewAnnotations,
+ attachments: attachments.map((attachment, index) => ({
+ attachment,
+ attachmentId: wireAttachments[index]?.id ?? attachment.id,
+ })),
+ });
+ // Servers from before inline context drop the records, so their turns
+ // carry the payload in the text instead.
+ const inlineContext = readConfig()?.environment.capabilities.inlineMessageContext === true;
+ await run(threadEnvironment.startTurn, {
+ environmentId,
+ input: {
+ threadId,
+ message: {
+ messageId: newMessageId(),
+ role: "user",
+ text:
+ context !== undefined && !inlineContext
+ ? serializeLegacyContextMessage({ text, records: context.records })
+ : text,
+ attachments: wireAttachments,
+ ...(context !== undefined && inlineContext ? { context } : {}),
+ },
+ modelSelection: sendSettings.modelSelection,
+ runtimeMode: sendSettings.runtimeMode,
+ interactionMode: sendSettings.interactionMode,
+ createdAt,
+ },
+ });
+ queue.finishSend(threadKey, message.id);
+ if (useUploads) releaseDraftAttachments(attachments);
+ for (const image of message.images) revokeBlobPreviewUrl(image.previewUrl);
+ } catch (error) {
+ if (!queue.failSend(threadKey, message.id)) return;
+ const title = readThreadShell(threadRef)?.title;
+ toastManager.add({
+ type: "error",
+ title: title ? `Queued message not sent in "${title}"` : "Queued message not sent",
+ description: error instanceof Error ? error.message : "Use Send now to try again.",
+ });
+ }
+}
diff --git a/apps/web/src/queuedMessageStore.test.ts b/apps/web/src/queuedMessageStore.test.ts
index 33869d89da6..8d72ab65054 100644
--- a/apps/web/src/queuedMessageStore.test.ts
+++ b/apps/web/src/queuedMessageStore.test.ts
@@ -1,5 +1,7 @@
+import { ProviderInstanceId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it } from "vite-plus/test";
+import { createLocalDispatchSnapshot } from "./components/ChatView.logic";
import {
isQueuedMessageDue,
latestCompletedToolActivityId,
@@ -15,15 +17,23 @@ function makeMessage(prompt: string): Omit<QueuedComposerMessage, "id"> {
terminalContexts: [],
previewAnnotations: [],
reviewComments: [],
- submissionIntent: "foreground",
+ sendSettings: {
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ promptEffort: null,
+ },
queuedAfterToolActivityId: null,
createdAt: "2026-09-11T00:00:00.000Z",
};
}
+const queue = (threadKey: string) =>
+ useQueuedMessageStore.getState().queuesByThreadKey[threadKey] ?? [];
+
describe("queuedMessageStore", () => {
beforeEach(() => {
- useQueuedMessageStore.setState({ queuesByThreadKey: {}, drainGeneration: 0 });
+ useQueuedMessageStore.setState({ queuesByThreadKey: {}, lastDispatchByThreadKey: {} });
});
it("keeps messages in submission order per thread", () => {
@@ -32,71 +42,112 @@ describe("queuedMessageStore", () => {
enqueue("thread-a", makeMessage("second"));
enqueue("thread-b", makeMessage("other"));
- const queues = useQueuedMessageStore.getState().queuesByThreadKey;
- expect(queues["thread-a"]?.map((message) => message.prompt)).toEqual(["first", "second"]);
- expect(queues["thread-b"]?.map((message) => message.prompt)).toEqual(["other"]);
+ expect(queue("thread-a").map((message) => message.prompt)).toEqual(["first", "second"]);
+ expect(queue("thread-b").map((message) => message.prompt)).toEqual(["other"]);
});
- it("take hands the message to exactly one caller", () => {
- const { enqueue, take } = useQueuedMessageStore.getState();
- const entry = enqueue("thread-a", makeMessage("first"));
+ it("allows one send per thread and re-anchors the rest to the current tool boundary", () => {
+ const { enqueue, beginSend } = useQueuedMessageStore.getState();
+ const first = enqueue("thread-a", makeMessage("first"));
+ const second = enqueue("thread-a", makeMessage("second"));
- expect(take("thread-a", entry.id, null)?.prompt).toBe("first");
- expect(take("thread-a", entry.id, null)).toBeNull();
- expect(useQueuedMessageStore.getState().queuesByThreadKey["thread-a"]).toBeUndefined();
+ expect(beginSend("thread-a", first.id, "tool-2")?.prompt).toBe("first");
+ expect(beginSend("thread-a", first.id, "tool-2")).toBeNull();
+ expect(beginSend("thread-a", second.id, "tool-2")).toBeNull();
+
+ const [sending, waiting] = queue("thread-a");
+ expect(sending?.sending).toBe("preparing");
+ expect(waiting?.queuedAfterToolActivityId).toBe("tool-2");
+ expect(
+ isQueuedMessageDue({ message: waiting!, phase: "running", latestToolActivityId: "tool-2" }),
+ ).toBe(false);
});
- it("take re-anchors the remaining messages to the current tool boundary", () => {
- const { enqueue, take } = useQueuedMessageStore.getState();
+ it("finishSend drops the sent message", () => {
+ const { enqueue, beginSend, finishSend } = useQueuedMessageStore.getState();
const first = enqueue("thread-a", makeMessage("first"));
- enqueue("thread-a", makeMessage("second"));
+ beginSend("thread-a", first.id, null);
- take("thread-a", first.id, "tool-2");
+ finishSend("thread-a", first.id);
- const [second] = useQueuedMessageStore.getState().queuesByThreadKey["thread-a"] ?? [];
- expect(second?.queuedAfterToolActivityId).toBe("tool-2");
- expect(
- isQueuedMessageDue({ message: second!, phase: "running", latestToolActivityId: "tool-2" }),
- ).toBe(false);
+ expect(useQueuedMessageStore.getState().queuesByThreadKey["thread-a"]).toBeUndefined();
+ });
+
+ it("failSend returns the message to the head, held", () => {
+ const { enqueue, beginSend, failSend } = useQueuedMessageStore.getState();
+ enqueue("thread-a", makeMessage("first"));
+ const second = enqueue("thread-a", makeMessage("second"));
+ beginSend("thread-a", second.id, null);
+
+ expect(failSend("thread-a", second.id)).toBe(true);
+
+ const [head] = queue("thread-a");
+ expect(queue("thread-a").map((message) => message.prompt)).toEqual(["second", "first"]);
+ expect(head?.sending).toBeUndefined();
+ expect(isQueuedMessageDue({ message: head!, phase: "ready", latestToolActivityId: null })).toBe(
+ false,
+ );
});
- it("remove keeps the other messages' anchors", () => {
- const { enqueue, remove } = useQueuedMessageStore.getState();
+ it("remove keeps the other messages' anchors and refuses a message being sent", () => {
+ const { enqueue, remove, beginSend } = useQueuedMessageStore.getState();
const first = enqueue("thread-a", { ...makeMessage("first"), queuedAfterToolActivityId: "t1" });
const second = enqueue("thread-a", makeMessage("second"));
expect(remove("thread-a", second.id)?.prompt).toBe("second");
expect(remove("thread-a", second.id)).toBeNull();
- expect(useQueuedMessageStore.getState().queuesByThreadKey["thread-a"]).toEqual([first]);
+ expect(queue("thread-a")).toEqual([first]);
+
+ beginSend("thread-a", first.id, "t1");
+ expect(remove("thread-a", first.id)).toBeNull();
});
- it("holdAtFront returns a failed message to the head, held", () => {
- const { enqueue, take, holdAtFront } = useQueuedMessageStore.getState();
+ it("a failed send keeps waiting on the dispatch before it", () => {
+ const { enqueue, beginSend, markDispatching, finishSend, failSend } =
+ useQueuedMessageStore.getState();
+ const earlier = createLocalDispatchSnapshot(undefined);
const first = enqueue("thread-a", makeMessage("first"));
- enqueue("thread-a", makeMessage("second"));
- const taken = take("thread-a", first.id, "t1")!;
+ const second = enqueue("thread-a", makeMessage("second"));
+ const third = enqueue("thread-a", makeMessage("third"));
+ const lastDispatch = () => useQueuedMessageStore.getState().lastDispatchByThreadKey["thread-a"];
+ beginSend("thread-a", first.id, null);
+ markDispatching("thread-a", first.id, earlier);
+ finishSend("thread-a", first.id);
+
+ // Fails before its turn start went out: the first send is still the one to wait on.
+ beginSend("thread-a", second.id, null);
+ failSend("thread-a", second.id);
+ expect(lastDispatch()?.thread).toBe(earlier);
+
+ // Fails after going out: it never reached the server, so the first still counts.
+ beginSend("thread-a", third.id, null);
+ markDispatching("thread-a", third.id, { ...earlier, startedAt: "later" });
+ failSend("thread-a", third.id);
+ expect(lastDispatch()?.thread).toBe(earlier);
+ });
- holdAtFront("thread-a", taken);
+ it("Stop takes back a preparing send but not one already dispatching", () => {
+ const { enqueue, beginSend, markDispatching, drain, failSend } =
+ useQueuedMessageStore.getState();
+ const preparing = enqueue("thread-a", makeMessage("preparing"));
+ enqueue("thread-a", makeMessage("waiting"));
+ beginSend("thread-a", preparing.id, null);
- const queue = useQueuedMessageStore.getState().queuesByThreadKey["thread-a"] ?? [];
- expect(queue.map((message) => message.prompt)).toEqual(["first", "second"]);
- expect(queue[0]?.holdUntilUserAction).toBe(true);
- expect(
- isQueuedMessageDue({ message: queue[0]!, phase: "ready", latestToolActivityId: null }),
- ).toBe(false);
- });
+ expect(drain("thread-a").map((message) => message.prompt)).toEqual(["preparing", "waiting"]);
+ expect(markDispatching("thread-a", preparing.id, createLocalDispatchSnapshot(undefined))).toBe(
+ false,
+ );
+ expect(failSend("thread-a", preparing.id)).toBe(false);
- it("drain empties one thread's queue in order", () => {
- const { enqueue, drain } = useQueuedMessageStore.getState();
- enqueue("thread-a", makeMessage("first"));
- enqueue("thread-a", makeMessage("second"));
- enqueue("thread-b", makeMessage("other"));
+ const dispatching = enqueue("thread-b", makeMessage("dispatching"));
+ enqueue("thread-b", makeMessage("waiting"));
+ beginSend("thread-b", dispatching.id, null);
+ expect(
+ markDispatching("thread-b", dispatching.id, createLocalDispatchSnapshot(undefined)),
+ ).toBe(true);
- expect(drain("thread-a").map((message) => message.prompt)).toEqual(["first", "second"]);
- expect(useQueuedMessageStore.getState().drainGeneration).toBe(1);
- expect(drain("thread-a")).toEqual([]);
- expect(useQueuedMessageStore.getState().drainGeneration).toBe(1);
- expect(useQueuedMessageStore.getState().queuesByThreadKey["thread-b"]).toHaveLength(1);
+ expect(drain("thread-b").map((message) => message.prompt)).toEqual(["waiting"]);
+ expect(queue("thread-b").map((message) => message.prompt)).toEqual(["dispatching"]);
});
});
diff --git a/apps/web/src/queuedMessageStore.ts b/apps/web/src/queuedMessageStore.ts
index b342a1380f7..735cebf33b1 100644
--- a/apps/web/src/queuedMessageStore.ts
+++ b/apps/web/src/queuedMessageStore.ts
@@ -1,12 +1,30 @@
-import type { PreviewAnnotationPayload } from "@t3tools/contracts";
+import type {
+ ModelSelection,
+ PreviewAnnotationPayload,
+ ProviderInteractionMode,
+ RuntimeMode,
+} from "@t3tools/contracts";
import { create } from "zustand";
-import type { ComposerSubmissionIntent } from "./composer-logic";
+import type { LocalDispatchSnapshot } from "./components/ChatView.logic";
import type { ComposerFileAttachment, ComposerImageAttachment } from "./composerDraftStore";
import type { TerminalContextDraft } from "./lib/terminalContext";
import { randomUUID } from "./lib/utils";
import type { ReviewCommentContext } from "./reviewCommentContext";
+/**
+ * The composer's model and modes when the message was queued. The send uses
+ * these instead of the live composer, so it can go out while the user is on
+ * another thread.
+ */
+export interface QueuedMessageSendSettings {
+ modelSelection: ModelSelection;
+ runtimeMode: RuntimeMode;
+ interactionMode: ProviderInteractionMode;
+ /** Effort written into the prompt text, for providers that read it there. */
+ promptEffort: string | null;
+}
+
/**
* A composer submission held back while the thread's turn is running. It
* carries the full draft snapshot so the send path can dispatch it later with
@@ -20,7 +38,7 @@ export interface QueuedComposerMessage {
terminalContexts: TerminalContextDraft[];
previewAnnotations: PreviewAnnotationPayload[];
reviewComments: ReviewCommentContext[];
- submissionIntent: ComposerSubmissionIntent;
+ sendSettings: QueuedMessageSendSettings;
/**
* The newest completed tool activity at queue time. A different id later
* means a tool call finished after the user queued, which is the boundary
@@ -32,125 +50,172 @@ export interface QueuedComposerMessage {
* user pressing send. It waits for Send now instead of leaving on its own.
*/
holdUntilUserAction?: boolean;
+ /**
+ * Set while a send is under way; the row stays until it settles. Stop can
+ * still take a "preparing" message back (uploads, thread settings), but not
+ * a "dispatching" one, whose turn start is already on the wire.
+ */
+ sending?: "preparing" | "dispatching";
createdAt: string;
}
+/**
+ * The thread as it was when its last queued turn start went out. The next
+ * message waits until the server has moved past it, so a send that starts a
+ * new turn and the message after it do not leave on one boundary.
+ */
+interface QueuedDispatch {
+ /** The message that went out, or null for a dispatch restored after a failure. */
+ messageId: string | null;
+ thread: LocalDispatchSnapshot;
+ /** The dispatch this one replaced. If this send fails, that one still counts. */
+ previous: LocalDispatchSnapshot | null;
+}
+
interface QueuedMessageStoreState {
queuesByThreadKey: Record<string, QueuedComposerMessage[]>;
- /**
- * Bumped by `drain`. A send that took a message before a drain and finishes
- * its upload after it compares this to the value it captured and gives up,
- * so Stop cannot be followed by a queued message starting a new turn.
- */
- drainGeneration: number;
+ lastDispatchByThreadKey: Record<string, QueuedDispatch>;
enqueue: (threadKey: string, message: Omit<QueuedComposerMessage, "id">) => QueuedComposerMessage;
/**
- * Removes one message and returns it, or null when another caller already
- * took it. The remaining messages are re-anchored to `toolActivityId` so
- * only one queued message leaves per tool boundary.
+ * Marks one message as sending and returns it, or null when it is gone or
+ * the thread already has a send under way. The other messages are
+ * re-anchored to `toolActivityId` so only one leaves per tool boundary.
*/
- take: (
+ beginSend: (
threadKey: string,
id: string,
toolActivityId: string | null,
) => QueuedComposerMessage | null;
- /** Removes one message without touching the others' anchors. Null when already gone. */
- remove: (threadKey: string, id: string) => QueuedComposerMessage | null;
+ /** The turn start is going out. False when Stop took the message back first. */
+ markDispatching: (threadKey: string, id: string, thread: LocalDispatchSnapshot) => boolean;
+ /** Drops a message whose send went out, or that had nothing left to send. */
+ finishSend: (threadKey: string, id: string) => void;
/**
- * Puts a message back at the head, held for user action. Used when its
- * send failed: the queue keeps its order and nothing behind it overtakes.
+ * Moves a message whose send failed back to the head, held for user action.
+ * The queue keeps its order and nothing behind it overtakes. False when
+ * Stop already took the message back.
*/
- holdAtFront: (threadKey: string, message: QueuedComposerMessage) => void;
- /** Removes and returns every queued message for the thread, oldest first. */
+ failSend: (threadKey: string, id: string) => boolean;
+ /** Removes one message without touching the others' anchors. Null when gone or sending. */
+ remove: (threadKey: string, id: string) => QueuedComposerMessage | null;
+ /** Removes and returns every message for the thread that is not already on the wire. */
drain: (threadKey: string) => QueuedComposerMessage[];
}
const EMPTY_QUEUE: QueuedComposerMessage[] = [];
+type QueueState = Pick<QueuedMessageStoreState, "queuesByThreadKey" | "lastDispatchByThreadKey">;
+
+/** Replaces one thread's queue. `lastDispatch` null forgets it; an empty queue always does. */
+function withQueue(
+ state: QueueState,
+ threadKey: string,
+ queue: QueuedComposerMessage[],
+ lastDispatch?: QueuedDispatch | null,
+): QueueState {
+ const queuesByThreadKey = { ...state.queuesByThreadKey, [threadKey]: queue };
+ const lastDispatchByThreadKey = { ...state.lastDispatchByThreadKey };
+ if (lastDispatch) lastDispatchByThreadKey[threadKey] = lastDispatch;
+ if (queue.length === 0) delete queuesByThreadKey[threadKey];
+ if (queue.length === 0 || lastDispatch === null) delete lastDispatchByThreadKey[threadKey];
+ return { queuesByThreadKey, lastDispatchByThreadKey };
+}
+
/** In-memory only: a queued message is a live intent, not a draft worth persisting. */
-export const useQueuedMessageStore = create<QueuedMessageStoreState>()((set, get) => ({
- queuesByThreadKey: {},
- drainGeneration: 0,
- enqueue: (threadKey, message) => {
- const entry: QueuedComposerMessage = { ...message, id: randomUUID() };
- set((state) => ({
- queuesByThreadKey: {
- ...state.queuesByThreadKey,
- [threadKey]: [...(state.queuesByThreadKey[threadKey] ?? EMPTY_QUEUE), entry],
- },
- }));
- return entry;
- },
- take: (threadKey, id, toolActivityId) => {
- const queue = get().queuesByThreadKey[threadKey];
- const entry = queue?.find((message) => message.id === id);
- if (!queue || !entry) {
- return null;
- }
- set((state) => {
- const remaining = (state.queuesByThreadKey[threadKey] ?? EMPTY_QUEUE)
- .filter((message) => message.id !== id)
- .map((message) =>
- message.queuedAfterToolActivityId === toolActivityId
- ? message
- : { ...message, queuedAfterToolActivityId: toolActivityId },
- );
- const queuesByThreadKey = { ...state.queuesByThreadKey };
- if (remaining.length === 0) {
- delete queuesByThreadKey[threadKey];
- } else {
- queuesByThreadKey[threadKey] = remaining;
- }
- return { queuesByThreadKey };
- });
- return entry;
- },
- remove: (threadKey, id) => {
- const queue = get().queuesByThreadKey[threadKey];
- const entry = queue?.find((message) => message.id === id);
- if (!queue || !entry) {
- return null;
- }
- set((state) => {
- const remaining = (state.queuesByThreadKey[threadKey] ?? EMPTY_QUEUE).filter(
- (message) => message.id !== id,
- );
- const queuesByThreadKey = { ...state.queuesByThreadKey };
- if (remaining.length === 0) {
- delete queuesByThreadKey[threadKey];
- } else {
- queuesByThreadKey[threadKey] = remaining;
- }
- return { queuesByThreadKey };
- });
- return entry;
- },
- holdAtFront: (threadKey, message) => {
- set((state) => {
- const rest = (state.queuesByThreadKey[threadKey] ?? EMPTY_QUEUE).filter(
- (entry) => entry.id !== message.id,
+export const useQueuedMessageStore = create<QueuedMessageStoreState>()((set, get) => {
+ const queueOf = (threadKey: string) => get().queuesByThreadKey[threadKey] ?? EMPTY_QUEUE;
+ const update = (
+ threadKey: string,
+ queue: QueuedComposerMessage[],
+ lastDispatch?: QueuedDispatch | null,
+ ) => set((state) => withQueue(state, threadKey, queue, lastDispatch));
+ return {
+ queuesByThreadKey: {},
+ lastDispatchByThreadKey: {},
+ enqueue: (threadKey, message) => {
+ const entry: QueuedComposerMessage = { ...message, id: randomUUID() };
+ update(threadKey, [...queueOf(threadKey), entry]);
+ return entry;
+ },
+ beginSend: (threadKey, id, toolActivityId) => {
+ const queue = queueOf(threadKey);
+ const entry = queue.find((message) => message.id === id);
+ if (!entry || queue.some((message) => message.sending)) return null;
+ update(
+ threadKey,
+ queue.map((message) =>
+ message.id === id
+ ? { ...message, sending: "preparing" }
+ : message.queuedAfterToolActivityId === toolActivityId
+ ? message
+ : { ...message, queuedAfterToolActivityId: toolActivityId },
+ ),
);
- return {
- queuesByThreadKey: {
- ...state.queuesByThreadKey,
- [threadKey]: [{ ...message, holdUntilUserAction: true }, ...rest],
+ return entry;
+ },
+ markDispatching: (threadKey, id, thread) => {
+ const queue = queueOf(threadKey);
+ if (!queue.some((message) => message.id === id && message.sending)) return false;
+ update(
+ threadKey,
+ queue.map((message) =>
+ message.id === id ? { ...message, sending: "dispatching" } : message,
+ ),
+ {
+ messageId: id,
+ thread,
+ previous: get().lastDispatchByThreadKey[threadKey]?.thread ?? null,
},
- };
- });
- },
- drain: (threadKey) => {
- const queue = get().queuesByThreadKey[threadKey];
- if (!queue || queue.length === 0) {
- return EMPTY_QUEUE;
- }
- set((state) => {
- const queuesByThreadKey = { ...state.queuesByThreadKey };
- delete queuesByThreadKey[threadKey];
- return { queuesByThreadKey, drainGeneration: state.drainGeneration + 1 };
- });
- return queue;
- },
-}));
+ );
+ return true;
+ },
+ finishSend: (threadKey, id) => {
+ const queue = queueOf(threadKey);
+ if (!queue.some((message) => message.id === id)) return;
+ update(
+ threadKey,
+ queue.filter((message) => message.id !== id),
+ );
+ },
+ failSend: (threadKey, id) => {
+ const queue = queueOf(threadKey);
+ const entry = queue.find((message) => message.id === id);
+ if (!entry) return false;
+ const { sending: _sending, ...rest } = entry;
+ // This send never reached the server, so only an earlier one is worth
+ // waiting for.
+ const dispatch = get().lastDispatchByThreadKey[threadKey];
+ update(
+ threadKey,
+ [{ ...rest, holdUntilUserAction: true }, ...queue.filter((message) => message.id !== id)],
+ dispatch?.messageId !== id
+ ? undefined
+ : dispatch.previous && { messageId: null, thread: dispatch.previous, previous: null },
+ );
+ return true;
+ },
+ remove: (threadKey, id) => {
+ const queue = queueOf(threadKey);
+ const entry = queue.find((message) => message.id === id);
+ if (!entry || entry.sending) return null;
+ update(
+ threadKey,
+ queue.filter((message) => message.id !== id),
+ );
+ return entry;
+ },
+ drain: (threadKey) => {
+ const queue = queueOf(threadKey);
+ const drained = queue.filter((message) => message.sending !== "dispatching");
+ if (drained.length === 0) return EMPTY_QUEUE;
+ update(
+ threadKey,
+ queue.filter((message) => message.sending === "dispatching"),
+ );
+ return drained;
+ },
+ };
+});
/**
* The newest finished tool call. Its id changing is the boundary a queued
diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx
index e89240878c3..b9dcbae5c32 100644
--- a/apps/web/src/routes/__root.tsx
+++ b/apps/web/src/routes/__root.tsx
@@ -29,6 +29,7 @@ import { DesktopAppActivationCoordinator } from "../components/desktop/DesktopAp
import { RunningThreadKeepAlive } from "../components/desktop/RunningThreadKeepAlive";
import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";
import { ThreadNotificationCoordinator } from "../components/ThreadNotificationCoordinator";
+import { QueuedMessageSender } from "../components/QueuedMessageSender";
import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator";
import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";
import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";
@@ -227,6 +228,7 @@ function RootRouteView() {
<SshPasswordPromptDialog />
<SnapShotCoordinator />
<ThreadNotificationCoordinator />
+ <QueuedMessageSender />
<ConfirmDialogHost />
<CustomSnoozeDialogHost />
<SlowRpcRequestToastCoordinator />
diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts
index dcd6358cb52..af977d567f2 100644
--- a/apps/web/src/state/entities.ts
+++ b/apps/web/src/state/entities.ts
@@ -183,6 +183,14 @@ export function readThreadShell(ref: ScopedThreadRef): EnvironmentThreadShell |
return appAtomRegistry.get(environmentThreadShells.threadShellAtom(ref));
}
+/** The thread as `useThread` returns it, read outside React. */
+export function readThread(ref: ScopedThreadRef): EnvironmentThread | null {
+ return mergeEnvironmentThread(
+ appAtomRegistry.get(environmentThreadDetails.detailAtom(ref)),
+ readThreadShell(ref),
+ );
+}
+
/** Whether the environment's server understands thread.settle/unsettle.
False for pre-settlement servers (capability defaults false on decode),
so clients under version skew fall back instead of erroring. */
diff --git a/docs/user/composer.md b/docs/user/composer.md
index a10e3dbe4d2..7ee8edcbb12 100644
--- a/docs/user/composer.md
+++ b/docs/user/composer.md
@@ -36,7 +36,7 @@ See [images and videos](#images-and-videos-in-messages) for previewing and savin
On web and desktop, a message sent during a running turn waits at the end of the conversation as a
dashed bubble. It goes out on its own when the agent finishes its next tool
-call, or when the turn ends. Use the arrow under the bubble to send it right
+call, or when the turn ends, even while you have another thread open. Use the arrow under the bubble to send it right
away, or the X to move it back into the composer. Stop returns every queued
message to the composer.