Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🫴 fix: Preserve Queued Follow-Ups Through Handoff (#15942)

Danny Avila96cb5e757d90
diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsx
index 8e127931f5..bb8ffcb351 100644
--- a/client/src/components/Chat/ChatView.tsx
+++ b/client/src/components/Chat/ChatView.tsx
@@ -14,6 +14,7 @@ import {
useAdaptiveSSE,
useChatHelpers,
useQueueDrain,
+ useQueuedTurnReveal,
useLocalize,
} from '~/hooks';
import { ChatContext, AddedChatContext, ChatFormProvider, useFileMapContext } from '~/Providers';
@@ -105,8 +106,12 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje
// refetch is in flight, and resume must not build from (or race) it.
useResumeOnLoad(conversationId, chatHelpers.getMessages, index, !isLoading && !isFetching);
+ // Show a server-owned queued follow-up as the next user turn as soon as its
+ // predecessor completes, ahead of the receipt and active-job polls.
+ const revealQueuedTurn = useQueuedTurnReveal(conversationId, index);
+
// Auto-send queued follow-up messages once a run finishes cleanly.
- useQueueDrain(index, conversationId, chatHelpers.ask);
+ useQueueDrain(index, conversationId, chatHelpers.ask, revealQueuedTurn);
let content: JSX.Element | null | undefined;
const isLandingPage =
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index e155035d30..dd0b1e8e92 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -57,6 +57,7 @@ import FileFormChat from './Files/FileFormChat';
import InFlightSteers from './InFlightSteers';
import TextareaHeader from './TextareaHeader';
import PromptsCommand from './PromptsCommand';
+import { submitFromComposer } from './submit';
import SkillsCommand from './SkillsCommand';
import AudioRecorder from './AudioRecorder';
import AutoPlayAudio from './AutoPlayAudio';
@@ -279,7 +280,7 @@ const ChatForm = memo(function ChatForm({
* collapsed batch is neither — it hands the composer back to the thread. */
const composerReserved = answerMode.composerAnswers || answerMode.composerLocked;
- useAutoSave({
+ const consumeDraft = useAutoSave({
index,
files,
setFiles,
@@ -381,6 +382,7 @@ const ChatForm = memo(function ChatForm({
[methods, setFiles, restoreComposerContext],
);
const steering = useSteering({
+ consumeDraft,
index,
conversationId,
conversation,
@@ -613,25 +615,27 @@ const ChatForm = memo(function ChatForm({
bottomClearance = 'sm:mb-10';
}
+ /** Answer mode, then during-run steering or queueing (a run in flight, or a
+ * queued follow-up about to start), then an ordinary send: the same route
+ * for typed, dictated, and shortcut-bound submissions. */
+ const submitComposerText = useCallback(
+ (data: { text: string }): false | void =>
+ submitFromComposer(
+ {
+ answerMode,
+ steering,
+ submitMessage,
+ reset: () => methods.reset(),
+ },
+ data,
+ ),
+ [answerMode, steering, submitMessage, methods],
+ );
+
return (
<form
onSubmit={methods.handleSubmit((data) => {
- // Answer mode: composer text answers the paused run instead of
- // starting a new turn (submitText resets the composer itself).
- // Dismissing the popover — or collapsing a batch, which answers in its
- // own card — restores normal sends.
- if (answerMode.active && answerMode.submitText(data.text)) {
- return;
- }
- // During a run, a submit steers or queues per the effective action
- // instead of starting a new turn (which would be dropped anyway).
- if (steering.duringRunActive) {
- if (steering.submitDuringRun(data.text)) {
- methods.reset();
- }
- return;
- }
- return submitMessage(data);
+ submitComposerText(data);
})}
className={cn(
/* `margin-bottom` is animated as well as `max-width`: it is what carries
@@ -876,7 +880,7 @@ const ChatForm = memo(function ChatForm({
{SpeechToText && (
<AudioRecorder
methods={methods}
- ask={submitMessage}
+ ask={submitComposerText}
disabled={disableInputs || isNotAppendable}
isSubmitting={isSubmitting}
/>
diff --git a/client/src/components/Chat/Input/PendingSteerChips.tsx b/client/src/components/Chat/Input/PendingSteerChips.tsx
index 04078e80ee..2467a7e588 100644
--- a/client/src/components/Chat/Input/PendingSteerChips.tsx
+++ b/client/src/components/Chat/Input/PendingSteerChips.tsx
@@ -27,8 +27,8 @@ import {
useDefaultToggleEntry,
useInterruptToggleEntry,
} from './SteerMenu';
+import { escalatingSteerFamily, revealedQueuedTurnFamily } from '~/store/steer';
import { QUEUE_ICON, STEER_ICON } from '~/components/Chat/Steering/identity';
-import { escalatingSteerFamily } from '~/store/steer';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
import store from '~/store';
@@ -109,6 +109,7 @@ function QueuedRow({
steering,
conversationId,
interruptPending,
+ revealed,
onEditToComposer,
onRestoreToComposer,
}: {
@@ -116,6 +117,8 @@ function QueuedRow({
steering: SteeringControls;
conversationId: string;
interruptPending: boolean;
+ /** Shown as the next user turn already; only removal remains meaningful. */
+ revealed?: boolean;
onEditToComposer: (
text: string,
files?: TMessage['files'],
@@ -186,12 +189,16 @@ function QueuedRow({
// Edit/remove are safe because `afterDiscard` tombstones that source first.
const canSteerNow = steering.duringRunActive && steering.canSteer && !isRecovered;
const showPrimary =
- serverActionable && (canSteerNow || (!steering.duringRunActive && steering.canSendQueuedNow));
+ revealed !== true &&
+ serverActionable &&
+ (canSteerNow || (!steering.duringRunActive && steering.canSendQueuedNow));
/** `canSteer` is defined as false while paused on approval, but the
* escalation control must stay visible-and-disabled there — hiding it
* during the pause is exactly the discoverability gap this button fixes. */
const showEscalate =
- !isRecovered && (steering.pausedOnApproval || (steering.duringRunActive && steering.canSteer));
+ revealed !== true &&
+ !isRecovered &&
+ (steering.pausedOnApproval || (steering.duringRunActive && steering.canSteer));
const entries: MenuEntry[] = [
{
@@ -256,6 +263,11 @@ function QueuedRow({
{(isRejected || isUnconfirmed || isIndeterminate) && (
<span className="shrink-0 text-xs text-text-warning">{localize(statusLabel)}</span>
)}
+ {revealed === true && (
+ <span className="shrink-0 text-xs text-text-secondary">
+ {localize('com_ui_queued_turn_starting')}
+ </span>
+ )}
{showPrimary && (
<button
type="button"
@@ -291,7 +303,12 @@ function QueuedRow({
aria-label={localize(
isUnconfirmed ? 'com_ui_dismiss_unconfirmed_delivery' : 'com_ui_remove_queued',
)}
- disabled={actionPending || (!serverActionable && !isUnconfirmed)}
+ disabled={
+ actionPending ||
+ (!serverActionable &&
+ !isUnconfirmed &&
+ !(message.server?.id != null && message.server.status === 'claimed'))
+ }
onClick={() => {
if (isUnconfirmed) {
steering.removeQueued(message.id);
@@ -320,11 +337,13 @@ function QueuedRow({
>
<Trash2 className="h-4 w-4" aria-hidden="true" />
</button>
- <RowMenu
- label={localize('com_ui_more_options')}
- entries={entries}
- preferences={preferences}
- />
+ {revealed !== true && (
+ <RowMenu
+ label={localize('com_ui_more_options')}
+ entries={entries}
+ preferences={preferences}
+ />
+ )}
</div>
);
}
@@ -472,6 +491,9 @@ function PendingSteerChips({
const localize = useLocalize();
const steers = useRecoilValue(store.pendingSteersByConvoId(conversationId));
const queued = useRecoilValue(store.queuedMessagesByConvoId(steering.queueKey));
+ /** A row already shown as the next user turn keeps only its remove action
+ * here: the turn can still be retracted until the server admits it. */
+ const revealed = useAtomValue(revealedQueuedTurnFamily(steering.queueKey));
const failedSteers = useMemo(() => steers.filter((steer) => steer.status === 'failed'), [steers]);
/** Only one interrupt can be in flight: a second preempt while one is
* unresolved would arm a second seal, so escalation buttons disable. The
@@ -509,6 +531,11 @@ function PendingSteerChips({
steering={steering}
conversationId={conversationId}
interruptPending={interruptPending}
+ revealed={
+ revealed != null &&
+ message.clientRequestId != null &&
+ revealed.clientRequestId === message.clientRequestId
+ }
onEditToComposer={onEditToComposer}
onRestoreToComposer={onRestoreToComposer}
/>
diff --git a/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsx b/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsx
index e757c562bd..76bb6bfa34 100644
--- a/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsx
+++ b/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsx
@@ -2,10 +2,10 @@ import React from 'react';
import { getDefaultStore } from 'jotai';
import userEvent from '@testing-library/user-event';
import { RecoilRoot, useRecoilValue, useSetRecoilState } from 'recoil';
-import { render, screen, fireEvent, act, waitFor } from '@testing-library/react';
+import { render, screen, fireEvent, act, waitFor, within } from '@testing-library/react';
import type { PendingSteer, QueuedMessage } from '~/store/families';
import type { SteeringControls } from '~/hooks/Chat/useSteering';
-import { escalatingSteerFamily } from '~/store/steer';
+import { escalatingSteerFamily, revealedQueuedTurnFamily } from '~/store/steer';
import PendingSteerChips from '../PendingSteerChips';
import store from '~/store';
@@ -706,3 +706,72 @@ describe('PendingSteerChips — queued hint', () => {
expect(screen.queryByRole('img', { name: hintName })).toBeNull();
});
});
+
+describe('PendingSteerChips — revealed queued turn', () => {
+ const revealedFamily = () => revealedQueuedTurnFamily(CONVO_ID);
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ act(() => {
+ getDefaultStore().set(revealedFamily(), null);
+ });
+ });
+
+ afterEach(() => {
+ act(() => {
+ getDefaultStore().set(revealedFamily(), null);
+ });
+ });
+
+ const serverRow = (clientRequestId: string): QueuedMessage => ({
+ id: `q-${clientRequestId}`,
+ text: `queued ${clientRequestId}`,
+ createdAt: 1,
+ clientRequestId,
+ server: { id: `server-${clientRequestId}`, status: 'queued', revision: 1 },
+ });
+
+ it('reduces the row shown as the next turn to its remove action', () => {
+ getDefaultStore().set(revealedFamily(), {
+ clientRequestId: 'req-1',
+ parentMessageId: 'response-1',
+ text: 'queued req-1',
+ revealedAt: '2026-09-14T00:00:00.000Z',
+ });
+ renderChips([serverRow('req-1'), serverRow('req-2')], {
+ steering: { duringRunActive: true, canSendQueuedNow: false, canSteer: false },
+ });
+
+ const rows = screen.getAllByTestId('queued-message-row');
+ expect(rows).toHaveLength(2);
+ expect(rows[0]).toHaveTextContent('com_ui_queued_turn_starting');
+ expect(within(rows[0]).queryByRole('button', { name: 'com_ui_more_options' })).toBeNull();
+ expect(within(rows[0]).getByRole('button', { name: /com_ui_remove/ })).toBeInTheDocument();
+ expect(rows[1]).not.toHaveTextContent('com_ui_queued_turn_starting');
+ expect(
+ within(rows[1]).getByRole('button', { name: 'com_ui_more_options' }),
+ ).toBeInTheDocument();
+ });
+ it.each([true, false])(
+ 'attempts claimed cancellation and respects acceptance=%s',
+ async (accepted) => {
+ const message = serverRow('req-1');
+ message.server!.status = 'claimed';
+ getDefaultStore().set(revealedFamily(), {
+ clientRequestId: 'req-1',
+ parentMessageId: 'response-1',
+ text: message.text,
+ revealedAt: new Date().toISOString(),
+ });
+ mockDiscardQueued.mockResolvedValueOnce(accepted);
+ renderChips([message], { steering: { duringRunActive: true, canSendQueuedNow: false } });
+ const remove = screen.getByRole('button', { name: /com_ui_remove/ });
+ expect(remove).toBeEnabled();
+ await userEvent.click(remove);
+ await waitFor(() => expect(mockDiscardQueued).toHaveBeenCalledWith(message));
+ expect(mockRemoveQueued).toHaveBeenCalledTimes(accepted ? 1 : 0);
+ expect(mockRestoreToComposer).toHaveBeenCalledTimes(accepted ? 1 : 0);
+ expect(mockSendQueuedNow).not.toHaveBeenCalled();
+ },
+ );
+});
diff --git a/client/src/components/Chat/Input/__tests__/submit.spec.ts b/client/src/components/Chat/Input/__tests__/submit.spec.ts
new file mode 100644
index 0000000000..754e5755ba
--- /dev/null
+++ b/client/src/components/Chat/Input/__tests__/submit.spec.ts
@@ -0,0 +1,49 @@
+import type { ComposerSubmitRoute } from '../submit';
+import { submitFromComposer } from '../submit';
+
+const route = (overrides: Partial<ComposerSubmitRoute> = {}): ComposerSubmitRoute => ({
+ answerMode: { active: false, submitText: jest.fn(() => false) },
+ steering: { duringRunActive: false, submitDuringRun: jest.fn(() => true) },
+ submitMessage: jest.fn(),
+ reset: jest.fn(),
+ ...overrides,
+});
+
+describe('submitFromComposer', () => {
+ it('starts an ordinary turn when nothing owns the composer', () => {
+ const r = route();
+ submitFromComposer(r, { text: 'hello' });
+ expect(r.submitMessage).toHaveBeenCalledWith({ text: 'hello' });
+ expect(r.steering.submitDuringRun).not.toHaveBeenCalled();
+ });
+
+ it('answers the paused run before any send or steer routing', () => {
+ const r = route({
+ answerMode: { active: true, submitText: jest.fn(() => true) },
+ steering: { duringRunActive: true, submitDuringRun: jest.fn(() => true) },
+ });
+ submitFromComposer(r, { text: 'option b' });
+ expect(r.answerMode.submitText).toHaveBeenCalledWith('option b');
+ expect(r.steering.submitDuringRun).not.toHaveBeenCalled();
+ expect(r.submitMessage).not.toHaveBeenCalled();
+ });
+
+ it('steers or queues instead of starting a turn while a run or a revealed follow-up is pending', () => {
+ const r = route({
+ steering: { duringRunActive: true, submitDuringRun: jest.fn(() => true) },
+ });
+ expect(submitFromComposer(r, { text: 'wait for it' })).toBeUndefined();
+ expect(r.steering.submitDuringRun).toHaveBeenCalledWith('wait for it');
+ expect(r.reset).toHaveBeenCalled();
+ expect(r.submitMessage).not.toHaveBeenCalled();
+ });
+
+ it('keeps the text in the composer when the during-run route refuses it', () => {
+ const r = route({
+ steering: { duringRunActive: true, submitDuringRun: jest.fn(() => false) },
+ });
+ expect(submitFromComposer(r, { text: 'not now' })).toBe(false);
+ expect(r.reset).not.toHaveBeenCalled();
+ expect(r.submitMessage).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/components/Chat/Input/submit.ts b/client/src/components/Chat/Input/submit.ts
new file mode 100644
index 0000000000..58adbb6211
--- /dev/null
+++ b/client/src/components/Chat/Input/submit.ts
@@ -0,0 +1,31 @@
+export type ComposerSubmitRoute = {
+ answerMode: { active: boolean; submitText: (text: string) => boolean };
+ steering: { duringRunActive: boolean; submitDuringRun: (text: string) => boolean };
+ submitMessage: (data: { text: string }) => false | void;
+ reset: () => void;
+};
+
+/**
+ * One route for every submission that originates in the composer, whether
+ * typed, dictated, or bound to a shortcut. Answer mode takes the text for the
+ * paused run; during a run, or while a queued follow-up is about to start, the
+ * text steers or queues per the effective action instead of starting a turn
+ * that would race the one already owed. `false` means the composer keeps the
+ * text, exactly as a refused send does.
+ */
+export function submitFromComposer(
+ route: ComposerSubmitRoute,
+ data: { text: string },
+): false | void {
+ if (route.answerMode.active && route.answerMode.submitText(data.text)) {
+ return;
+ }
+ if (route.steering.duringRunActive) {
+ if (!route.steering.submitDuringRun(data.text)) {
+ return false;
+ }
+ route.reset();
+ return;
+ }
+ return route.submitMessage(data);
+}
diff --git a/client/src/components/Chat/Messages/HoverButtons.tsx b/client/src/components/Chat/Messages/HoverButtons.tsx
index 97133fa06f..15c59e3438 100644
--- a/client/src/components/Chat/Messages/HoverButtons.tsx
+++ b/client/src/components/Chat/Messages/HoverButtons.tsx
@@ -1,5 +1,6 @@
import React, { useState, useMemo, useCallback, memo } from 'react';
import { Copy, Check } from 'lucide';
+import { useAtomValue } from 'jotai';
import { useRecoilState } from 'recoil';
import { findMessageById, isUserInitiatedCompaction } from 'librechat-data-provider';
import {
@@ -14,6 +15,7 @@ import type { TConversation, TMessage, TFeedback } from 'librechat-data-provider
import { useGenerationsByLatest, useLocalize } from '~/hooks';
import { useOptionalMessagesOperations } from '~/Providers';
import { hasEditablePart } from './Content/editableParts';
+import { revealedQueuedTurnFamily } from '~/store/steer';
import { Fork } from '~/components/Conversations';
import { hoverButtonClasses } from './styles';
import MessageAudio from './MessageAudio';
@@ -139,6 +141,7 @@ const HoverButtons = ({
const [isCopied, setIsCopied] = useState(false);
const [TextToSpeech] = useRecoilState<boolean>(store.textToSpeech);
const { getMessages } = useOptionalMessagesOperations();
+ const pendingReveal = useAtomValue(revealedQueuedTurnFamily(conversation?.conversationId ?? ''));
const endpoint = useMemo(() => {
if (!conversation) {
@@ -171,9 +174,11 @@ const HoverButtons = ({
* inside parses markdown. */
const getHasEditablePart = useCallback(() => hasEditablePart(message), [message]);
+ /** A pending queued follow-up is a generation about to start: no rerun or
+ * continuation may race it, exactly as while a run is submitting. */
const generationCapabilities = useGenerationsByLatest({
isEditing,
- isSubmitting,
+ isSubmitting: isSubmitting || pendingReveal != null,
error: message.error,
endpoint: endpoint ?? '',
messageId: message.messageId,
diff --git a/client/src/components/Chat/Messages/MessagesView.tsx b/client/src/components/Chat/Messages/MessagesView.tsx
index 0b7642f1b9..1369a74791 100644
--- a/client/src/components/Chat/Messages/MessagesView.tsx
+++ b/client/src/components/Chat/Messages/MessagesView.tsx
@@ -14,6 +14,7 @@ import { FLAT_THREAD, ThreadList } from './Thread';
import { fontSizeAtom } from '~/store/fontSize';
import MultiMessage from './MultiMessage';
import ScrollButton from './ScrollButton';
+import PendingTurn from './PendingTurn';
import MessageNav from './MessageNav';
import { cn } from '~/utils';
import store from '~/store';
@@ -125,6 +126,11 @@ function MessagesViewContent({
)}
</RowMountProvider>
</div>
+ <PendingTurn
+ scrollableRef={scrollableRef}
+ messages={messages}
+ maximizeChatSpace={maximizeChatSpace}
+ />
</>
)}
<div
diff --git a/client/src/components/Chat/Messages/PendingTurn.tsx b/client/src/components/Chat/Messages/PendingTurn.tsx
new file mode 100644
index 0000000000..f04f1cdc55
--- /dev/null
+++ b/client/src/components/Chat/Messages/PendingTurn.tsx
@@ -0,0 +1,132 @@
+import { useEffect, useMemo, useRef } from 'react';
+import { useAtomValue } from 'jotai';
+import { useRecoilValue } from 'recoil';
+import type { TMessage } from 'librechat-data-provider';
+import type { RefObject } from 'react';
+import type { TMessageIcon } from '~/common';
+import { buildRevealedMessage, hasRevealSuccessor } from '~/hooks/Chat/useQueuedTurnReveal';
+import { getHeaderPrefixForScreenReader, getMessageAriaLabel } from '~/utils';
+import { messageFooterClasses } from '~/components/Chat/Messages/styles';
+import MessageRow from '~/components/Chat/Messages/ui/MessageRow';
+import MessageIcon from '~/components/Chat/Messages/MessageIcon';
+import { revealedQueuedTurnFamily } from '~/store/steer';
+import { useAuthContext } from '~/hooks/AuthContext';
+import MarkdownLite from './Content/MarkdownLite';
+import { useChatContext } from '~/Providers';
+import Container from './Content/Container';
+import { useLocalize } from '~/hooks';
+import SubRow from './SubRow';
+import { cn } from '~/utils';
+import store from '~/store';
+
+/** How far above the end of the thread a reader can be and still be handed
+ * the next turn, matching the scroll button's own near-bottom band. */
+const FOLLOW_THRESHOLD_PX = 160;
+
+/**
+ * The queued follow-up the server is about to admit, drawn as the user turn
+ * after the completed response it follows. It is not a message: it holds no
+ * hover actions, anchors no send, and leaves the thread the moment the thread
+ * gains a turn after that response (see `useQueuedTurnReveal`).
+ */
+export default function PendingTurn({
+ scrollableRef,
+ messages,
+ maximizeChatSpace = false,
+}: {
+ scrollableRef?: RefObject<HTMLDivElement | null>;
+ messages?: TMessage[] | null;
+ maximizeChatSpace?: boolean;
+}) {
+ const localize = useLocalize();
+ const { user } = useAuthContext();
+ const { conversation, latestMessageId } = useChatContext();
+ const conversationId = conversation?.conversationId ?? '';
+ const reveal = useAtomValue(revealedQueuedTurnFamily(conversationId));
+ const usernameDisplay = useRecoilValue(store.UsernameDisplay);
+ const enableUserMsgMarkdown = useRecoilValue(store.enableUserMsgMarkdown);
+ const rowRef = useRef<HTMLDivElement | null>(null);
+ const message = useMemo(
+ () => (reveal == null ? null : buildRevealedMessage(reveal, conversationId)),
+ [reveal, conversationId],
+ );
+ const successorSeen = useMemo(
+ () => reveal != null && hasRevealSuccessor(messages ?? [], reveal),
+ [messages, reveal],
+ );
+ const shown =
+ message != null &&
+ reveal != null &&
+ reveal.parentMessageId === latestMessageId &&
+ !successorSeen;
+
+ /** A reader resting at the end of the thread was following the response;
+ * bring the turn that replaces it into view the way its streaming did.
+ * Anyone reading further up is left where they are. */
+ useEffect(() => {
+ const row = rowRef.current;
+ const scrollEl = scrollableRef?.current;
+ if (!shown || row == null || scrollEl == null) {
+ return;
+ }
+ const distanceFromEnd =
+ scrollEl.scrollHeight - scrollEl.scrollTop - scrollEl.clientHeight - row.offsetHeight;
+ if (distanceFromEnd > FOLLOW_THRESHOLD_PX) {
+ return;
+ }
+ const reduceMotion = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true;
+ row.scrollIntoView({ block: 'end', behavior: reduceMotion ? 'auto' : 'smooth' });
+ }, [shown, scrollableRef]);
+
+ if (!shown) {
+ return null;
+ }
+
+ const label = usernameDisplay
+ ? (user?.name ?? '') || (user?.username ?? '')
+ : localize('com_user_message');
+ const iconData: TMessageIcon = {
+ endpoint: conversation?.endpoint,
+ model: conversation?.model,
+ modelLabel: label,
+ isCreatedByUser: true,
+ };
+
+ return (
+ <div
+ ref={rowRef}
+ className="w-full border-0 bg-transparent text-text-primary"
+ data-testid="pending-turn"
+ >
+ <div className="m-auto justify-center px-4 py-3 sm:px-0">
+ <MessageRow
+ icon={<MessageIcon iconData={iconData} />}
+ label={label}
+ timestamp={reveal.revealedAt}
+ ariaLabel={getMessageAriaLabel(message, localize)}
+ headerPrefix={getHeaderPrefixForScreenReader(message, localize)}
+ isCreatedByUser
+ fullWidth={maximizeChatSpace}
+ footer={
+ <SubRow classes={cn(messageFooterClasses, 'justify-end')}>
+ <span className="text-xs text-text-secondary" role="status">
+ {localize('com_ui_queued_turn_starting')}
+ </span>
+ </SubRow>
+ }
+ >
+ <Container message={message}>
+ <div
+ className={cn(
+ 'markdown prose message-content dark:prose-invert light w-full break-words text-text-primary',
+ !enableUserMsgMarkdown && 'whitespace-pre-wrap',
+ )}
+ >
+ {enableUserMsgMarkdown ? <MarkdownLite content={reveal.text} /> : reveal.text}
+ </div>
+ </Container>
+ </MessageRow>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/components/Chat/Messages/__tests__/PendingTurn.spec.tsx b/client/src/components/Chat/Messages/__tests__/PendingTurn.spec.tsx
new file mode 100644
index 0000000000..ae4a67fa3c
--- /dev/null
+++ b/client/src/components/Chat/Messages/__tests__/PendingTurn.spec.tsx
@@ -0,0 +1,125 @@
+import React from 'react';
+import { RecoilRoot } from 'recoil';
+import { EModelEndpoint } from 'librechat-data-provider';
+import { act, render, screen } from '@testing-library/react';
+import { Provider as JotaiProvider, createStore } from 'jotai';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { TConversation, TMessage } from 'librechat-data-provider';
+import type { RevealedQueuedTurn } from '~/store/steer';
+import PendingTurn from '~/components/Chat/Messages/PendingTurn';
+import { revealedQueuedTurnFamily } from '~/store/steer';
+import { ChatContext } from '~/Providers';
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string) => key,
+}));
+
+jest.mock('~/hooks/AuthContext', () => ({
+ useAuthContext: () => ({ user: { name: 'Danny', username: 'danny' } }),
+}));
+
+jest.mock('~/components/Chat/Messages/MessageIcon', () => ({
+ __esModule: true,
+ default: () => <span data-testid="message-icon" />,
+}));
+
+jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({
+ __esModule: true,
+ default: ({ content }: { content: string }) => <span data-testid="markdown-lite">{content}</span>,
+}));
+
+const CONVO_ID = 'convo-pending';
+const RESPONSE_ID = 'response-1';
+
+const conversation = {
+ conversationId: CONVO_ID,
+ endpoint: EModelEndpoint.agents,
+ model: 'gpt-x',
+} as TConversation;
+
+const reveal = (overrides: Partial<RevealedQueuedTurn> = {}): RevealedQueuedTurn => ({
+ clientRequestId: 'client-request-1',
+ parentMessageId: RESPONSE_ID,
+ text: 'queued follow-up',
+ revealedAt: '2026-09-14T00:00:00.000Z',
+ ...overrides,
+});
+
+function renderPendingTurn({
+ revealed,
+ latestMessageId = RESPONSE_ID,
+ messages,
+}: {
+ revealed?: RevealedQueuedTurn | null;
+ latestMessageId?: string | undefined;
+ messages?: TMessage[];
+}) {
+ const jotaiStore = createStore();
+ if (revealed != null) {
+ jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), revealed);
+ }
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const chatContext = { conversation, latestMessageId, index: 0 } as unknown as React.ContextType<
+ typeof ChatContext
+ >;
+ const rendered = render(
+ <QueryClientProvider client={queryClient}>
+ <RecoilRoot>
+ <JotaiProvider store={jotaiStore}>
+ <ChatContext.Provider value={chatContext}>
+ <PendingTurn messages={messages} />
+ </ChatContext.Provider>
+ </JotaiProvider>
+ </RecoilRoot>
+ </QueryClientProvider>,
+ );
+ return { ...rendered, jotaiStore };
+}
+
+describe('PendingTurn', () => {
+ it('draws the revealed queued turn as a user turn after the response it follows', () => {
+ const { container } = renderPendingTurn({ revealed: reveal() });
+
+ const row = screen.getByTestId('pending-turn');
+ expect(row.querySelector('.message-render')).not.toBeNull();
+ expect(row.querySelector('.user-turn')).not.toBeNull();
+ expect(row).toHaveTextContent('queued follow-up');
+ expect(screen.getByRole('status')).toHaveTextContent('com_ui_queued_turn_starting');
+ expect(container.querySelectorAll('button')).toHaveLength(0);
+ });
+
+ it('renders nothing without a reveal', () => {
+ renderPendingTurn({ revealed: null });
+ expect(screen.queryByTestId('pending-turn')).toBeNull();
+ });
+
+ it('renders nothing while the thread shows a different tail than the response it follows', () => {
+ renderPendingTurn({ revealed: reveal(), latestMessageId: 'another-branch' });
+ expect(screen.queryByTestId('pending-turn')).toBeNull();
+ });
+
+ it('leaves the thread the moment the reveal ends', () => {
+ const { jotaiStore } = renderPendingTurn({ revealed: reveal() });
+ expect(screen.getByTestId('pending-turn')).toBeInTheDocument();
+
+ act(() => {
+ jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), null);
+ });
+
+ expect(screen.queryByTestId('pending-turn')).toBeNull();
+ });
+ it('hides the drawing once history has a successor while the handoff guard remains', () => {
+ const { jotaiStore } = renderPendingTurn({
+ revealed: reveal(),
+ messages: [
+ {
+ messageId: 'real-successor',
+ parentMessageId: RESPONSE_ID,
+ isCreatedByUser: true,
+ } as TMessage,
+ ],
+ });
+ expect(screen.queryByTestId('pending-turn')).toBeNull();
+ expect(jotaiStore.get(revealedQueuedTurnFamily(CONVO_ID))).not.toBeNull();
+ });
+});
diff --git a/client/src/components/Chat/__tests__/ChatView.spec.tsx b/client/src/components/Chat/__tests__/ChatView.spec.tsx
index f97f4d7e1e..80d03eada0 100644
--- a/client/src/components/Chat/__tests__/ChatView.spec.tsx
+++ b/client/src/components/Chat/__tests__/ChatView.spec.tsx
@@ -33,6 +33,7 @@ jest.mock('~/hooks', () => ({
useAdaptiveSSE: jest.fn(),
useResumeOnLoad: jest.fn(),
useQueueDrain: jest.fn(),
+ useQueuedTurnReveal: jest.fn(),
useScrollbarGutterSeed: jest.fn(),
}));
diff --git a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx
index 7f7a5cadfe..72a66c62bc 100644
--- a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx
+++ b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx
@@ -32,6 +32,7 @@ jest.mock('~/hooks', () => ({
useResumeOnLoad: jest.fn(),
useAdaptiveSSE: jest.fn(),
useQueueDrain: jest.fn(),
+ useQueuedTurnReveal: jest.fn(),
useScrollbarGutterSeed: jest.fn(),
useLocalize: () => (key: string) => key,
useChatHelpers: () => ({
diff --git a/client/src/data-provider/SSE/__tests__/queuedTurns.test.ts b/client/src/data-provider/SSE/__tests__/queuedTurns.test.ts
index 3e1db9a5b9..4f7a435f89 100644
--- a/client/src/data-provider/SSE/__tests__/queuedTurns.test.ts
+++ b/client/src/data-provider/SSE/__tests__/queuedTurns.test.ts
@@ -145,6 +145,12 @@ describe('Agent queued-turn data adapter', () => {
expect(shouldPollAgentQueuedTurns([{ status: 'queued' }])).toBe(true);
});
+ it('keeps polling an empty projection while the client still holds a server-owned row', () => {
+ expect(shouldPollAgentQueuedTurns([])).toBe(false);
+ expect(shouldPollAgentQueuedTurns([], undefined, Date.now(), true)).toBe(true);
+ expect(shouldPollAgentQueuedTurns(undefined, undefined, Date.now(), true)).toBe(true);
+ });
+
it('counts an admitted turn as an owed run, unlike the receipt poll', () => {
/**
* The receipt poll stops at `admitted` because nothing is left to wait
diff --git a/client/src/data-provider/SSE/queuedTurns.ts b/client/src/data-provider/SSE/queuedTurns.ts
index ea7097adc6..e87b9b7961 100644
--- a/client/src/data-provider/SSE/queuedTurns.ts
+++ b/client/src/data-provider/SSE/queuedTurns.ts
@@ -83,8 +83,10 @@ export function shouldPollAgentQueuedTurns(
receipts: unknown,
reconcileUntil?: number,
observedAt = Date.now(),
+ expectsReceipts = false,
): boolean {
return (
+ expectsReceipts ||
(reconcileUntil != null && observedAt < reconcileUntil) ||
(Array.isArray(receipts) &&
receipts.some(
@@ -117,11 +119,18 @@ export function isQueuedTurnSuccessorOwed(receipts: unknown): boolean {
);
}
+/**
+ * `expectsReceipts` keeps the poll alive while the caller still holds a
+ * server-owned row the projection has not settled. A snapshot fetched while
+ * the enqueue is still committing can come back empty, and a poll that stops
+ * on that answer would leave a fast successor unnoticed until the next focus.
+ */
export function useAgentQueuedTurns(
conversationId: string,
enabled: boolean,
clientRequestIds: string[] = [],
reconcileUntil?: number,
+ expectsReceipts = false,
) {
const queryClient = useQueryClient();
const knownIds = [...new Set(clientRequestIds)].sort();
@@ -138,7 +147,9 @@ export function useAgentQueuedTurns(
refetchOnMount: 'always',
refetchOnWindowFocus: 'always',
refetchInterval: (receipts) =>
- shouldPollAgentQueuedTurns(receipts, reconcileUntil) ? 2_000 : false,
+ shouldPollAgentQueuedTurns(receipts, reconcileUntil, Date.now(), expectsReceipts)
+ ? 2_000
+ : false,
retry: false,
});
const { refetch } = query;
diff --git a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
index 4ad5ab196b..2bce016518 100644
--- a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx
@@ -1,3 +1,4 @@
+import { getDefaultStore } from 'jotai';
import { renderHook, act } from '@testing-library/react';
import { Constants, ContentTypes, EModelEndpoint, createPayload } from 'librechat-data-provider';
import type {
@@ -7,6 +8,7 @@ import type {
TMessage,
TSubmission,
} from 'librechat-data-provider';
+import { revealedQueuedTurnFamily } from '~/store/steer';
import useChatFunctions from '../useChatFunctions';
import { isPasteSubmitted } from '~/utils';
@@ -208,6 +210,30 @@ describe('useChatFunctions ask', () => {
expect(submission.codeWorkspaces).toEqual([selection]);
});
+ it('refuses every direct send before consuming composer context during handoff', () => {
+ const family = revealedQueuedTurnFamily('conversation-1');
+ getDefaultStore().set(family, {
+ clientRequestId: 'queued',
+ parentMessageId: 'response',
+ generationCreatedAt: 41,
+ text: 'queued',
+ revealedAt: new Date().toISOString(),
+ });
+ try {
+ const { result, setSubmission, getMessages } = renderAsk([]);
+ expect(result.current.ask({ text: 'direct' })).toBe(false);
+ expect(
+ result.current.ask({ text: 'rerun', parentMessageId: 'earlier' }, { isRegenerate: true }),
+ ).toBe(false);
+ expect(mockResolveCodeWorkspaceSubmission).not.toHaveBeenCalled();
+ expect(getMessages).not.toHaveBeenCalled();
+ expect(setSubmission).not.toHaveBeenCalled();
+ expect(mockSetFilesToDelete).not.toHaveBeenCalled();
+ } finally {
+ getDefaultStore().set(family, null);
+ }
+ });
+
it('refuses to send when workspace submission resolution is not ready', () => {
mockResolveCodeWorkspaceSubmission.mockReturnValue(undefined);
const { result, setSubmission } = renderAsk([]);
diff --git a/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx b/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx
index 232c79c993..d14d0b6a7e 100644
--- a/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx
@@ -1,4 +1,5 @@
import React from 'react';
+import { getDefaultStore } from 'jotai';
import { Constants } from 'librechat-data-provider';
import { act, renderHook, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
@@ -9,6 +10,7 @@ import type {
QueuedMessage,
SettledQueuedTurnReceipt,
} from '~/store/families';
+import { revealedQueuedTurnFamily } from '~/store/steer';
import useQueueDrain from '../useQueueDrain';
import store from '~/store';
@@ -24,6 +26,7 @@ const CONVO_ID = 'convo-drain';
function setup(
initialize?: (snapshot: MutableSnapshot) => void,
activeConversationId: string | undefined = CONVO_ID,
+ revealQueuedTurn?: jest.Mock,
) {
const ask = jest.fn();
const setters: {
@@ -54,7 +57,7 @@ function setup(
setters.newConvoQueue = useRecoilValue(store.queuedMessagesByConvoId(Constants.NEW_CONVO));
setters.settledReceipts = useRecoilValue(store.settledQueuedTurnReceiptsByConvoId(CONVO_ID));
setters.runEnd = useRecoilValue(store.runEndByIndex(INDEX));
- useQueueDrain(INDEX, activeConversationId, ask);
+ useQueueDrain(INDEX, activeConversationId, ask, revealQueuedTurn);
return null;
}
@@ -140,6 +143,135 @@ describe('useQueueDrain', () => {
});
});
+ it('hands the server-owned head to the reveal on clean completion and keeps the boundary', async () => {
+ const reveal = jest.fn();
+ const head = {
+ ...queuedMessage('q-server', 'the server starts this turn'),
+ clientRequestId: 'client-request-1',
+ server: { id: 'server-queue-1', status: 'queued' as const, revision: 1 },
+ };
+ const { ask, setters } = setup(
+ ({ set }) => {
+ set(store.queuedMessagesByConvoId(CONVO_ID), [head]);
+ },
+ CONVO_ID,
+ reveal,
+ );
+
+ const end = runEnd({ responseMessageId: 'response-1' });
+ act(() => {
+ setters.setRunEnd!(end);
+ });
+
+ await waitFor(() => expect(reveal).toHaveBeenCalled());
+ expect(reveal).toHaveBeenCalledWith(head, expect.objectContaining(end));
+ expect(ask).not.toHaveBeenCalled();
+ expect(setters.runEnd).toEqual(expect.objectContaining(end));
+ expect(setters.queue).toEqual([head]);
+ });
+
+ it('re-selects the next server-owned row once the revealed head settles', async () => {
+ const reveal = jest.fn();
+ const first = {
+ ...queuedMessage('q-first', 'first server turn'),
+ clientRequestId: 'client-request-1',
+ server: { id: 'server-queue-1', status: 'queued' as const, revision: 1 },
+ };
+ const second = {
+ ...queuedMessage('q-second', 'second server turn'),
+ clientRequestId: 'client-request-2',
+ server: { id: 'server-queue-2', status: 'queued' as const, revision: 2 },
+ };
+ const { setters } = setup(
+ ({ set }) => {
+ set(store.queuedMessagesByConvoId(CONVO_ID), [first, second]);
+ },
+ CONVO_ID,
+ reveal,
+ );
+
+ act(() => {
+ setters.setRunEnd!(runEnd({ responseMessageId: 'response-1' }));
+ });
+ await waitFor(() => expect(reveal).toHaveBeenCalled());
+ expect(reveal.mock.calls[0][0]).toEqual(first);
+ act(() => {
+ getDefaultStore().set(revealedQueuedTurnFamily(CONVO_ID), {
+ clientRequestId: 'client-request-1',
+ parentMessageId: 'response-1',
+ text: first.text,
+ revealedAt: '2026-09-14T00:00:00.000Z',
+ });
+ });
+ reveal.mockClear();
+
+ /** The first row is cancelled before admission: its reveal ends and the
+ * row leaves the queue, while the boundary stays server-owned. */
+ act(() => {
+ getDefaultStore().set(revealedQueuedTurnFamily(CONVO_ID), null);
+ setters.setQueue!([second]);
+ });
+
+ await waitFor(() => expect(reveal).toHaveBeenCalled());
+ expect(reveal.mock.calls[reveal.mock.calls.length - 1][0]).toEqual(second);
+ expect(setters.runEnd).toEqual(expect.objectContaining({ responseMessageId: 'response-1' }));
+ });
+
+ it('reveals the server-owned row behind a migrated local head', async () => {
+ const reveal = jest.fn();
+ const local = queuedMessage('q-local', 'queued before the id arrived');
+ const serverRow = {
+ ...queuedMessage('q-server', 'queued after the id arrived'),
+ clientRequestId: 'client-request-2',
+ server: { id: 'server-queue-2', status: 'queued' as const, revision: 1 },
+ };
+ const { ask, setters } = setup(
+ ({ set }) => {
+ set(store.queuedMessagesByConvoId(Constants.NEW_CONVO), [local]);
+ set(store.queuedMessagesByConvoId(CONVO_ID), [serverRow]);
+ },
+ CONVO_ID,
+ reveal,
+ );
+
+ act(() => {
+ setters.setRunEnd!(runEnd({ startedAsNewConvo: true, responseMessageId: 'response-1' }));
+ });
+
+ await waitFor(() => expect(reveal).toHaveBeenCalled());
+ expect(reveal.mock.calls[0][0]).toEqual(serverRow);
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('reveals nothing on a stop, or when the completed run carries no response id', async () => {
+ const reveal = jest.fn();
+ const { setters } = setup(
+ ({ set }) => {
+ set(store.queuedMessagesByConvoId(CONVO_ID), [
+ {
+ ...queuedMessage('q-server', 'the server starts this turn'),
+ clientRequestId: 'client-request-1',
+ server: { id: 'server-queue-1', status: 'queued', revision: 1 },
+ },
+ ]);
+ },
+ CONVO_ID,
+ reveal,
+ );
+
+ act(() => {
+ setters.setRunEnd!(runEnd({ outcome: 'aborted', responseMessageId: 'response-1' }));
+ });
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ act(() => {
+ setters.setRunEnd!(null);
+ setters.setRunEnd!(runEnd());
+ });
+ await new Promise((resolve) => setTimeout(resolve, 25));
+
+ expect(reveal).not.toHaveBeenCalled();
+ });
+
it('retains the terminal boundary until server authority releases a local successor', async () => {
const localSuccessor = queuedMessage('q-local', 'legacy successor');
const queue: QueuedMessage[] = [
diff --git a/client/src/hooks/Chat/__tests__/useQueuedTurnReveal.spec.tsx b/client/src/hooks/Chat/__tests__/useQueuedTurnReveal.spec.tsx
new file mode 100644
index 0000000000..b112b97248
--- /dev/null
+++ b/client/src/hooks/Chat/__tests__/useQueuedTurnReveal.spec.tsx
@@ -0,0 +1,457 @@
+import React from 'react';
+import { QueryKeys } from 'librechat-data-provider';
+import { RecoilRoot, useSetRecoilState } from 'recoil';
+import { Provider as JotaiProvider, createStore } from 'jotai';
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { TMessage, TAgentQueuedTurnReceipt } from 'librechat-data-provider';
+import type { QueuedMessage, RunEnd } from '~/store/families';
+import type { RevealedQueuedTurn } from '~/store/steer';
+import useQueuedTurnReveal, {
+ buildRevealedMessage,
+ hasRevealSuccessor,
+ selectQueuedTurnReveal,
+ shouldRollbackReveal,
+} from '../useQueuedTurnReveal';
+import { agentQueuedTurnsQueryKey } from '~/data-provider/SSE/queuedTurns';
+import { streamStatusQueryKey } from '~/data-provider/SSE/queries';
+import { revealedQueuedTurnFamily } from '~/store/steer';
+import store from '~/store';
+
+const CONVO_ID = 'convo-reveal';
+const RESPONSE_ID = 'response-1';
+
+const serverRow = (overrides: Partial<QueuedMessage> = {}): QueuedMessage => ({
+ id: 'q-server',
+ text: 'queued follow-up',
+ createdAt: 10,
+ parentMessageId: 'original-queue-parent',
+ expectedPredecessorCreatedAt: 41,
+ clientRequestId: 'client-request-1',
+ server: { id: 'server-queue-1', status: 'queued', revision: 1 },
+ ...overrides,
+});
+
+const completedEnd = (overrides: Partial<RunEnd> = {}): RunEnd => ({
+ conversationId: CONVO_ID,
+ outcome: 'completed',
+ endedAt: 100,
+ generationCreatedAt: 41,
+ responseMessageId: RESPONSE_ID,
+ ...overrides,
+});
+
+const history = (): TMessage[] => [
+ { messageId: 'user-1', parentMessageId: '00000000-0000-0000-0000-000000000000' } as TMessage,
+ { messageId: RESPONSE_ID, parentMessageId: 'user-1', isCreatedByUser: false } as TMessage,
+];
+
+const successor = (messageId = 'user-2'): TMessage =>
+ ({ messageId, parentMessageId: RESPONSE_ID, isCreatedByUser: true }) as TMessage;
+
+const reveal = (overrides: Partial<RevealedQueuedTurn> = {}): RevealedQueuedTurn => ({
+ clientRequestId: 'client-request-1',
+ parentMessageId: RESPONSE_ID,
+ text: 'queued follow-up',
+ revealedAt: '2026-09-14T00:00:00.000Z',
+ ...overrides,
+});
+
+const receipt = (overrides: Partial<TAgentQueuedTurnReceipt> = {}): TAgentQueuedTurnReceipt =>
+ ({
+ queuedTurnId: 'server-queue-1',
+ clientRequestId: 'client-request-1',
+ conversationId: CONVO_ID,
+ text: 'queued follow-up',
+ status: 'queued',
+ revision: 1,
+ createdAt: '2026-09-14T00:00:00.000Z',
+ updatedAt: '2026-09-14T00:00:00.000Z',
+ ...overrides,
+ }) as TAgentQueuedTurnReceipt;
+
+describe('selectQueuedTurnReveal', () => {
+ it('picks a durably queued server-owned head after a clean completion', () => {
+ expect(selectQueuedTurnReveal(completedEnd(), [serverRow()])?.id).toBe('q-server');
+ expect(
+ selectQueuedTurnReveal(completedEnd(), [
+ serverRow({ server: { id: 'server-queue-1', status: 'claimed', revision: 1 } }),
+ ])?.id,
+ ).toBe('q-server');
+ });
+
+ it('reveals nothing for a stop, an error, or a run with no response to follow', () => {
+ expect(selectQueuedTurnReveal(completedEnd({ outcome: 'aborted' }), [serverRow()])).toBeNull();
+ expect(selectQueuedTurnReveal(completedEnd({ outcome: 'error' }), [serverRow()])).toBeNull();
+ expect(
+ selectQueuedTurnReveal(completedEnd({ generationCreatedAt: undefined }), [serverRow()]),
+ ).toBeNull();
+ expect(
+ selectQueuedTurnReveal(completedEnd({ responseMessageId: undefined }), [serverRow()]),
+ ).toBeNull();
+ });
+
+ it('skips rejected server rows and local rows ahead of the admissible successor', () => {
+ const rejected = serverRow({
+ id: 'q-rejected',
+ clientRequestId: 'client-request-0',
+ server: { id: 'server-queue-0', status: 'rejected', revision: 0 },
+ });
+ const local: QueuedMessage = { id: 'q-local', text: 'local first', createdAt: 5 };
+ expect(selectQueuedTurnReveal(completedEnd(), [rejected, serverRow()])?.id).toBe('q-server');
+ expect(selectQueuedTurnReveal(completedEnd(), [local, serverRow()])?.id).toBe('q-server');
+ expect(selectQueuedTurnReveal(completedEnd(), [local])).toBeNull();
+ });
+
+ it('leaves rows the server has not durably accepted, or has settled, on the chip', () => {
+ expect(
+ selectQueuedTurnReveal(completedEnd(), [serverRow({ server: { status: 'sending' } })]),
+ ).toBeNull();
+ expect(selectQueuedTurnReveal(completedEnd(), [serverRow({ server: undefined })])).toBeNull();
+ expect(selectQueuedTurnReveal(completedEnd(), [])).toBeNull();
+ });
+});
+
+describe('hasRevealSuccessor', () => {
+ it('is true once anything parents on the response the reveal follows', () => {
+ expect(hasRevealSuccessor(history(), reveal())).toBe(false);
+ expect(hasRevealSuccessor([...history(), successor()], reveal())).toBe(true);
+ expect(
+ hasRevealSuccessor(
+ [...history(), { messageId: 'x', parentMessageId: 'user-1' } as TMessage],
+ reveal(),
+ ),
+ ).toBe(false);
+ });
+});
+
+describe('shouldRollbackReveal', () => {
+ it('ends the reveal on cancelled, dead, or indeterminate receipts for its request', () => {
+ expect(shouldRollbackReveal([receipt({ status: 'cancelled' })], reveal())).toBe(true);
+ expect(shouldRollbackReveal([receipt({ status: 'dead' })], reveal())).toBe(true);
+ expect(
+ shouldRollbackReveal(
+ [receipt({ status: 'claimed', failure: { code: 'ADMISSION_INDETERMINATE' } })],
+ reveal(),
+ ),
+ ).toBe(true);
+ expect(
+ shouldRollbackReveal(
+ [receipt({ status: 'cancelled', clientRequestId: 'client-request-9' })],
+ reveal(),
+ ),
+ ).toBe(false);
+ });
+
+ it('keeps the reveal while the turn is queued, claimed, or admitted', () => {
+ expect(shouldRollbackReveal([receipt()], reveal())).toBe(false);
+ expect(shouldRollbackReveal([receipt({ status: 'claimed' })], reveal())).toBe(false);
+ expect(shouldRollbackReveal([receipt({ status: 'admitted' })], reveal())).toBe(false);
+ expect(shouldRollbackReveal([], reveal())).toBe(false);
+ });
+});
+
+describe('buildRevealedMessage', () => {
+ it('shapes a render-only user turn after the completed response with the queued context', () => {
+ const message = buildRevealedMessage(
+ reveal({ files: [{ file_id: 'f1' }], quotes: ['q'], manualSkills: ['s'] }),
+ CONVO_ID,
+ );
+ expect(message).toEqual(
+ expect.objectContaining({
+ parentMessageId: RESPONSE_ID,
+ conversationId: CONVO_ID,
+ text: 'queued follow-up',
+ isCreatedByUser: true,
+ clientTimestamp: '2026-09-14T00:00:00.000Z',
+ files: [{ file_id: 'f1' }],
+ quotes: ['q'],
+ manualSkills: ['s'],
+ }),
+ );
+ expect(message.createdAt).toBeUndefined();
+ expect(buildRevealedMessage(reveal(), CONVO_ID)).not.toHaveProperty('files');
+ });
+});
+
+describe('useQueuedTurnReveal', () => {
+ function setup(initialMessages: TMessage[] = history()) {
+ let setSubmitting: (value: boolean) => void;
+ let setEpoch: (value: number | null) => void;
+ function StateProbe() {
+ setSubmitting = useSetRecoilState(store.isSubmittingFamily(0));
+ setEpoch = useSetRecoilState(store.activeGenerationCreatedAtByConvoId(CONVO_ID));
+ return null;
+ }
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ queryClient.setQueryData<TMessage[]>([QueryKeys.messages, CONVO_ID], initialMessages);
+ const jotaiStore = createStore();
+ const getMessages = () => queryClient.getQueryData<TMessage[]>([QueryKeys.messages, CONVO_ID]);
+ const setMessages = (messages: TMessage[]) =>
+ queryClient.setQueryData<TMessage[]>([QueryKeys.messages, CONVO_ID], messages);
+ const wrapper = ({ children }: { children: React.ReactNode }) => (
+ <QueryClientProvider client={queryClient}>
+ <RecoilRoot>
+ <JotaiProvider store={jotaiStore}>
+ <StateProbe />
+ {children}
+ </JotaiProvider>
+ </RecoilRoot>
+ </QueryClientProvider>
+ );
+ const rendered = renderHook(() => useQueuedTurnReveal(CONVO_ID), { wrapper });
+ const current = () => jotaiStore.get(revealedQueuedTurnFamily(CONVO_ID));
+ return {
+ ...rendered,
+ queryClient,
+ jotaiStore,
+ getMessages,
+ setMessages,
+ current,
+ attach: (epoch: number, submitting = true) => {
+ setEpoch(epoch);
+ setSubmitting(submitting);
+ },
+ setReceipts: (receipts: TAgentQueuedTurnReceipt[]) =>
+ queryClient.setQueryData(agentQueuedTurnsQueryKey(CONVO_ID), receipts),
+ };
+ }
+
+ it('records the queued turn as the next user turn without touching the message cache', () => {
+ const { result, getMessages, current } = setup();
+
+ act(() => {
+ result.current(
+ serverRow({ files: [{ file_id: 'f1' }], quotes: ['why'], manualSkills: ['skill'] }),
+ completedEnd(),
+ );
+ });
+
+ expect(getMessages()).toHaveLength(2);
+ expect(current()).toEqual(
+ expect.objectContaining({
+ clientRequestId: 'client-request-1',
+ parentMessageId: RESPONSE_ID,
+ queueParentMessageId: 'original-queue-parent',
+ queuePredecessorCreatedAt: 41,
+ text: 'queued follow-up',
+ files: [{ file_id: 'f1' }],
+ quotes: ['why'],
+ manualSkills: ['skill'],
+ }),
+ );
+ });
+
+ it('reveals once per boundary however often the drain re-observes it', () => {
+ const { result, current } = setup();
+
+ act(() => {
+ result.current(serverRow(), completedEnd());
+ });
+ const first = current();
+ act(() => {
+ result.current(serverRow({ text: 'a later observation' }), completedEnd());
+ });
+
+ expect(current()).toBe(first);
+ });
+
+ it('refuses a foreign conversation, a row without a request id, and a run without a response', () => {
+ const { result, current } = setup();
+
+ act(() => {
+ result.current(serverRow(), completedEnd({ conversationId: 'elsewhere' }));
+ result.current(serverRow({ clientRequestId: undefined }), completedEnd());
+ result.current(serverRow(), completedEnd({ responseMessageId: undefined }));
+ });
+
+ expect(current()).toBeNull();
+ });
+
+ it('keeps admission guarded when history already has the successor before attachment', () => {
+ const { result, current } = setup([...history(), successor()]);
+
+ act(() => {
+ result.current(serverRow(), completedEnd());
+ });
+
+ expect(current()).not.toBeNull();
+ });
+
+ it('keeps admission guarded when history receives the successor before attachment', async () => {
+ const { result, setMessages, current } = setup();
+ act(() => {
+ result.current(serverRow(), completedEnd());
+ });
+ expect(current()).not.toBeNull();
+
+ act(() => {
+ setMessages([...history(), successor('someone-elses-turn')]);
+ });
+
+ expect(current()).not.toBeNull();
+ });
+
+ it('survives a history refetch that has not yet caught up with the admitted turn', async () => {
+ const { result, setMessages, current } = setup();
+ act(() => {
+ result.current(serverRow(), completedEnd());
+ });
+
+ act(() => {
+ setMessages(history());
+ });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ });
+
+ expect(current()).not.toBeNull();
+ });
+
+ it('ends on a cancelled, dead, or indeterminate receipt for the revealed request', async () => {
+ const { result, setReceipts, current } = setup();
+ act(() => {
+ result.current(serverRow(), completedEnd());
+ });
+
+ act(() => {
+ setReceipts([receipt({ status: 'dead' })]);
+ });
+
+ await waitFor(() => expect(current()).toBeNull());
+ });
+
+ it('keeps the reveal through queued, claimed, and admitted receipts', async () => {
+ const { result, setReceipts, current } = setup();
+ act(() => {
+ result.current(serverRow(), completedEnd());
+ });
+
+ act(() => {
+ setReceipts([receipt({ status: 'admitted' })]);
+ });
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ });
+
+ expect(current()).not.toBeNull();
+ });
+ it('hands the guard to a newer attached generation, never to the predecessor or a pending attach', () => {
+ const { result, attach, current } = setup();
+ act(() => {
+ result.current(serverRow(), completedEnd());
+ });
+ act(() => {
+ attach(41);
+ });
+ expect(current()).not.toBeNull();
+ act(() => {
+ attach(42, false);
+ });
+ expect(current()).not.toBeNull();
+ act(() => {
+ attach(42);
+ });
+ expect(current()).toBeNull();
+ act(() => {
+ result.current(serverRow(), completedEnd());
+ });
+ expect(current()).toBeNull();
+ });
+
+ it('settles a successor that completed inside the poll gap without trusting old inactive status', () => {
+ const { result, queryClient, current } = setup();
+ act(() => {
+ queryClient.setQueryData(streamStatusQueryKey(CONVO_ID), { active: false, createdAt: 41 });
+ result.current(serverRow(), completedEnd());
+ });
+ expect(current()).not.toBeNull();
+ act(() => {
+ queryClient.setQueryData(streamStatusQueryKey(CONVO_ID), {
+ active: false,
+ status: 'complete',
+ createdAt: 42,
+ });
+ });
+ expect(current()).toBeNull();
+ act(() => {
+ result.current(serverRow(), completedEnd());
+ });
+ expect(current()).toBeNull();
+ });
+
+ it('does not resurrect a cancelled head from a stale queue snapshot', () => {
+ const { result, setReceipts, current } = setup();
+ act(() => {
+ setReceipts([receipt({ status: 'cancelled' })]);
+ });
+ act(() => {
+ result.current(serverRow(), completedEnd());
+ });
+ expect(current()).toBeNull();
+ act(() => {
+ result.current(serverRow({ clientRequestId: 'next-request' }), completedEnd());
+ });
+ expect(current()?.clientRequestId).toBe('next-request');
+ });
+
+ it('does not register a message fetcher or replace history fetching during invalidation', async () => {
+ const { queryClient, getMessages, unmount } = setup();
+ const key = [QueryKeys.messages, CONVO_ID];
+ const fetchHistory = jest.fn(async () => [...history(), successor()]);
+ await queryClient.fetchQuery({ queryKey: key, queryFn: fetchHistory });
+ fetchHistory.mockClear();
+ await queryClient.invalidateQueries({ queryKey: key, refetchType: 'all' });
+ expect(fetchHistory).toHaveBeenCalledTimes(1);
+ expect(getMessages()).toHaveLength(3);
+ expect(queryClient.getQueryCache().find(key)?.getObserversCount()).toBe(0);
+ unmount();
+ });
+ it.each(['queued', 'claimed'] as const)(
+ 'keeps the handoff through a %s sibling and its admission boundary',
+ (status) => {
+ const { result, current, queryClient, setReceipts } = setup();
+ act(() => {
+ result.current(serverRow(), completedEnd());
+ setReceipts([
+ receipt({ status: 'admitted', effectivePredecessorCreatedAt: 41 }),
+ receipt({ clientRequestId: 'second', status, expectedPredecessorCreatedAt: 41 }),
+ ]);
+ queryClient.setQueryData(streamStatusQueryKey(CONVO_ID), {
+ active: false,
+ status: 'complete',
+ createdAt: 42,
+ });
+ });
+ expect(current()).not.toBeNull();
+ act(() => {
+ setReceipts([
+ receipt({
+ clientRequestId: 'second',
+ status: 'admitted',
+ effectivePredecessorCreatedAt: 42,
+ }),
+ ]);
+ });
+ expect(current()).toMatchObject({
+ generationCreatedAt: 42,
+ queueParentMessageId: 'original-queue-parent',
+ queuePredecessorCreatedAt: 41,
+ });
+ act(() => {
+ setReceipts([]);
+ });
+ expect(current()).not.toBeNull();
+ act(() => {
+ queryClient.setQueryData(streamStatusQueryKey(CONVO_ID), {
+ active: false,
+ status: 'complete',
+ createdAt: 43,
+ });
+ });
+ expect(current()).toBeNull();
+ },
+ );
+});
diff --git a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
index 56c9d3422a..2e62cbe58d 100644
--- a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
@@ -1,10 +1,13 @@
import React from 'react';
+import { getDefaultStore } from 'jotai';
import { act, renderHook, waitFor } from '@testing-library/react';
import { RecoilRoot, useRecoilValue, useSetRecoilState, type MutableSnapshot } from 'recoil';
import { Constants, ContentTypes, EModelEndpoint, LocalStorageKeys } from 'librechat-data-provider';
import type { TConversation, TFile, TMessage } from 'librechat-data-provider';
import type { QueuedMessage } from '~/store/families';
+import { clearAllDrafts, getPendingDraftId, getNewConversationDraftId } from '~/utils';
import useSteering, { mergeQueuedTurnFileMetadata } from '../useSteering';
+import { revealedQueuedTurnFamily } from '~/store/steer';
import useQueueDrain from '../useQueueDrain';
import store from '~/store';
@@ -109,6 +112,14 @@ function setup(params: HookParams = {}, initialize?: (snapshot: MutableSnapshot)
const rendered = renderHook(
() =>
useSteering({
+ consumeDraft: () => {
+ const id = params.conversationId ?? CONVO_ID;
+ const conversationDraftId =
+ id === Constants.NEW_CONVO ? getNewConversationDraftId(0) : id;
+ clearAllDrafts(
+ params.isSubmitting === false ? conversationDraftId : getPendingDraftId(0),
+ );
+ },
index: 0,
conversationId: CONVO_ID,
conversation: agentsConversation,
@@ -135,6 +146,7 @@ function useQueue(convoId: string) {
describe('useSteering', () => {
beforeEach(() => {
jest.clearAllMocks();
+ getDefaultStore().set(revealedQueuedTurnFamily(CONVO_ID), null);
mockMessages = undefined;
mockLatestMessage = undefined;
mockServerQueuedTurns = undefined;
@@ -302,6 +314,7 @@ describe('useSteering', () => {
const rendered = renderHook(
() => ({
steering: useSteering({
+ consumeDraft: jest.fn(),
index: 0,
conversationId: CONVO_ID,
conversation: agentsConversation,
@@ -348,6 +361,70 @@ describe('useSteering', () => {
expect(result.current.queue[0].server).toBeUndefined();
});
+ it('persists another follow-up against the original queue lineage after its completion boundary advances', async () => {
+ const family = revealedQueuedTurnFamily(CONVO_ID);
+ getDefaultStore().set(family, {
+ clientRequestId: 'pending-first',
+ parentMessageId: 'completed-response',
+ generationCreatedAt: 42,
+ queueParentMessageId: 'original-queue-parent',
+ queuePredecessorCreatedAt: 41,
+ text: 'first',
+ revealedAt: new Date().toISOString(),
+ });
+ mockEnqueueQueuedTurn.mockImplementation((input, options) => {
+ options.onSuccess({
+ ...input,
+ queuedTurnId: 'durable-second',
+ status: 'queued',
+ revision: 1,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ });
+ });
+ const { result, unmount } = setup({ isSubmitting: false }, ({ set }) => {
+ set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), null);
+ set(store.pendingQuotesByConvoId(CONVO_ID), ['quoted context']);
+ set(store.pendingManualSkillsByConvoId(CONVO_ID), ['skill']);
+ });
+ expect(result.current.duringRunActive).toBe(true);
+ expect(result.current.canSteer).toBe(false);
+ await act(async () => {
+ expect(result.current.submitDuringRun('second')).toBe(true);
+ });
+ expect(mockEnqueueQueuedTurn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ parentMessageId: 'original-queue-parent',
+ expectedPredecessorCreatedAt: 41,
+ text: 'second',
+ quotes: ['quoted context'],
+ manualSkills: ['skill'],
+ }),
+ expect.any(Object),
+ );
+ unmount();
+ getDefaultStore().set(family, null);
+ mockServerQueuedTurns = [
+ {
+ ...mockEnqueueQueuedTurn.mock.calls[0][0],
+ queuedTurnId: 'durable-second',
+ status: 'queued',
+ revision: 1,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ },
+ ];
+ const restored = setupServerQueue();
+ await waitFor(() =>
+ expect(restored.result.current.queue[0]).toMatchObject({
+ text: 'second',
+ quotes: ['quoted context'],
+ manualSkills: ['skill'],
+ server: { id: 'durable-second', status: 'queued' },
+ }),
+ );
+ });
+
it('enrolls one optimistic row with a stable request and visible branch identity', async () => {
mockEnqueueQueuedTurn.mockImplementation((input, options) => {
options.onSuccess({
@@ -904,6 +981,7 @@ describe('useSteering', () => {
true,
[clientRequestId],
uncertainSince! + 60_000,
+ true,
);
});
@@ -931,6 +1009,15 @@ describe('useSteering', () => {
expect(result.current.queue[0]).toMatchObject({
server: { status: 'uncertain', reconciliationExpired: true },
});
+ /** Held for manual recovery only: the projection owes it nothing more,
+ * so the poll no longer stays alive on its account. */
+ expect(mockUseAgentQueuedTurns).toHaveBeenLastCalledWith(
+ CONVO_ID,
+ true,
+ [result.current.queue[0].clientRequestId],
+ expect.any(Number),
+ false,
+ );
} finally {
jest.useRealTimers();
}
@@ -1097,6 +1184,7 @@ describe('useSteering', () => {
const { result } = renderHook(
() => {
useSteering({
+ consumeDraft: jest.fn(),
index: 0,
conversationId: CONVO_ID,
conversation: agentsConversation,
@@ -1301,6 +1389,7 @@ describe('useSteering', () => {
const rendered = renderHook(
() => ({
steering: useSteering({
+ consumeDraft: jest.fn(),
index: 0,
conversationId: CONVO_ID,
conversation: agentsConversation,
@@ -1480,6 +1569,7 @@ describe('useSteering', () => {
const rendered = renderHook(
({ convoId, isSubmitting }: { convoId: string; isSubmitting: boolean }) => ({
steering: useSteering({
+ consumeDraft: jest.fn(),
index: 0,
conversationId: convoId,
conversation: agentsConversation,
@@ -2056,6 +2146,7 @@ describe('useSteering', () => {
const { result, rerender } = renderHook(
({ conversationId }: { conversationId: string }) =>
useSteering({
+ consumeDraft: jest.fn(),
index: 0,
conversationId,
conversation: {
@@ -2116,6 +2207,7 @@ describe('useSteering', () => {
const rendered = renderHook(
() => ({
steering: useSteering({
+ consumeDraft: jest.fn(),
index: 0,
conversationId: CONVO_ID,
conversation: agentsConversation,
@@ -3077,6 +3169,7 @@ describe('useSteering', () => {
const rendered = renderHook(
() => ({
steering: useSteering({
+ consumeDraft: jest.fn(),
index: 0,
conversationId: CONVO_ID,
conversation: agentsConversation,
@@ -3279,6 +3372,7 @@ describe('useSteering', () => {
const rendered = renderHook(
() => ({
steering: useSteering({
+ consumeDraft: jest.fn(),
index: 0,
conversationId: CONVO_ID,
conversation: agentsConversation,
@@ -3839,6 +3933,45 @@ describe('useSteering', () => {
expect(localStorage.getItem(pendingDraftKey)).toBeNull();
});
+ it.each([false, true])(
+ 'consumes the conversation draft only after a handoff submission is accepted (blocked=%s)',
+ async (filesLoading) => {
+ const key = `${LocalStorageKeys.TEXT_DRAFT}${CONVO_ID}`;
+ const unrelatedKey = `${LocalStorageKeys.TEXT_DRAFT}another-conversation`;
+ localStorage.setItem(key, 'ZHJhZnRlZCB0ZXh0');
+ localStorage.setItem(unrelatedKey, 'other draft');
+ getDefaultStore().set(revealedQueuedTurnFamily(CONVO_ID), {
+ clientRequestId: 'pending',
+ parentMessageId: 'response',
+ generationCreatedAt: 41,
+ text: 'pending',
+ revealedAt: new Date().toISOString(),
+ });
+ const { result, unmount } = setup({ isSubmitting: false, filesLoading }, ({ set }) => {
+ set(store.activeGenerationCreatedAtByConvoId(CONVO_ID), null);
+ });
+ await act(async () => {
+ expect(result.current.submitDuringRun('drafted text')).toBe(!filesLoading);
+ });
+ expect(localStorage.getItem(key)).toBe(filesLoading ? 'ZHJhZnRlZCB0ZXh0' : null);
+ expect(localStorage.getItem(unrelatedKey)).toBe('other draft');
+ unmount();
+ getDefaultStore().set(revealedQueuedTurnFamily(CONVO_ID), null);
+ },
+ );
+
+ it.each([false, true])(
+ 'delegates draft consumption to its owner only on acceptance (blocked=%s)',
+ (filesLoading) => {
+ const consumeDraft = jest.fn();
+ const { result } = setup({ filesLoading, consumeDraft });
+ act(() => {
+ expect(result.current.queueFromComposer('drafted text')).toBe(!filesLoading);
+ });
+ expect(consumeDraft).toHaveBeenCalledTimes(filesLoading ? 0 : 1);
+ },
+ );
+
it('drops the pending draft when steering from the composer', () => {
stageDraft();
const { result } = setup();
diff --git a/client/src/hooks/Chat/index.ts b/client/src/hooks/Chat/index.ts
index 9da73b1749..589a942252 100644
--- a/client/src/hooks/Chat/index.ts
+++ b/client/src/hooks/Chat/index.ts
@@ -11,6 +11,7 @@ export { default as useGetAddedConvo } from './useGetAddedConvo';
export { default as useIdChangeEffect } from './useIdChangeEffect';
export { default as useFocusChatEffect } from './useFocusChatEffect';
export { default as useQueueDrain } from './useQueueDrain';
+export { default as useQueuedTurnReveal } from './useQueuedTurnReveal';
export { default as useSteering } from './useSteering';
export { default as useSteerCancel, useSteerReclaim } from './useSteerCancel';
export { default as useSteerConvert } from './useSteerConvert';
diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.ts
index fb91b23feb..d3b370da95 100644
--- a/client/src/hooks/Chat/useChatFunctions.ts
+++ b/client/src/hooks/Chat/useChatFunctions.ts
@@ -1,4 +1,5 @@
import { v4 } from 'uuid';
+import { useStore } from 'jotai';
import { cloneDeep } from 'lodash';
import { useNavigate } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
@@ -42,6 +43,7 @@ import useCodeApprovalMode from '~/hooks/Agents/useCodeApprovalMode';
import useSetFilesToDelete from '~/hooks/Files/useSetFilesToDelete';
import useCodeWorkspace from '~/hooks/Agents/useCodeWorkspace';
import useGetSender from '~/hooks/Conversations/useGetSender';
+import { revealedQueuedTurnFamily } from '~/store/steer';
import store, { useGetEphemeralAgent } from '~/store';
import { startupConfigKey } from '~/data-provider';
import useUserKey from '~/hooks/Input/useUserKey';
@@ -227,6 +229,7 @@ export default function useChatFunctions({
const setSubmissionStart = useSetRecoilState(store.submissionStartFamily(index));
const setShowStopButton = useSetRecoilState(store.showStopButtonByIndex(index));
const focusRegeneratedResponse = useFocusRegeneratedResponse();
+ const jotaiStore = useStore();
const getConversation = useGetConversation(index);
const addedConversation = useRecoilValue(store.conversationByKeySelector(1));
const { modes: codeApprovalModes, selected: fallbackCodeApprovalMode } = useCodeApprovalMode(
@@ -320,6 +323,8 @@ export default function useChatFunctions({
const regenerateShaped = isRegenerate || compact;
if (
!!isSubmitting ||
+ jotaiStore.get(revealedQueuedTurnFamily(immutableConversation?.conversationId ?? '')) !=
+ null ||
(!regenerateShaped && !isSubmittableMessage(text, (files?.size ?? 0) + replayFileCount))
) {
return false;
diff --git a/client/src/hooks/Chat/useQueueDrain.ts b/client/src/hooks/Chat/useQueueDrain.ts
index 7039adc21d..b0e4c21fa5 100644
--- a/client/src/hooks/Chat/useQueueDrain.ts
+++ b/client/src/hooks/Chat/useQueueDrain.ts
@@ -1,9 +1,12 @@
import { useEffect, useMemo } from 'react';
+import { useAtomValue } from 'jotai';
import { Constants } from 'librechat-data-provider';
import { useRecoilValue, useRecoilCallback } from 'recoil';
import type { DrainAfterAbort, QueuedMessage, QueuedMessageOrigin, RunEnd } from '~/store/families';
import type { TAskFunction } from '~/common';
+import { selectQueuedTurnReveal } from '~/hooks/Chat/useQueuedTurnReveal';
import { useMarkFilesUsageMutation } from '~/data-provider';
+import { revealedQueuedTurnFamily } from '~/store/steer';
import store from '~/store';
/** Mirrors the server's per-request cap on a usage touch. */
@@ -75,6 +78,7 @@ export default function useQueueDrain(
index: string | number,
activeConversationId: string | undefined,
ask: TAskFunction,
+ revealQueuedTurn?: (item: QueuedMessage, end: RunEnd) => void,
) {
const runEnd = useRecoilValue(store.runEndByIndex(index));
const parkedRunEnd = useRecoilValue(
@@ -97,6 +101,20 @@ export default function useQueueDrain(
store.settledQueuedTurnReceiptsByConvoId(activeConversationId ?? Constants.NEW_CONVO),
);
const hasServerOwnedQueue = [...ownQueue, ...newConvoQueue].some((item) => item.server != null);
+ /** The row the reveal would pick, and whether one is already revealed: a
+ * revealed head that is cancelled or dies before admission leaves the
+ * server-owned queue non-empty and its terminal evidence out of the
+ * settled receipts, so nothing above re-runs the effect for the row the
+ * backend moves on to. */
+ const revealedQueuedTurn = useAtomValue(
+ revealedQueuedTurnFamily(activeConversationId ?? Constants.NEW_CONVO),
+ );
+ const admissibleHeadId =
+ [...ownQueue, ...newConvoQueue].find(
+ (item) =>
+ item.server?.id != null &&
+ (item.server.status === 'queued' || item.server.status === 'claimed'),
+ )?.id ?? null;
/* Deduped because the two subscriptions are the same atom before migration.
* Keyed by id list so the effect re-runs when the held set changes, not
@@ -172,12 +190,16 @@ export default function useQueueDrain(
// awaits may interleave with the reads.
const drainNext = useRecoilCallback(
({ snapshot, set }) =>
- (): {
- next: QueuedMessage;
- conversationId: string;
- queuedMessageOrigin: QueuedMessageOrigin;
- expectedPredecessorCreatedAt?: number;
- } | null => {
+ ():
+ | {
+ kind: 'drain';
+ next: QueuedMessage;
+ conversationId: string;
+ queuedMessageOrigin: QueuedMessageOrigin;
+ expectedPredecessorCreatedAt?: number;
+ }
+ | { kind: 'reveal'; item: QueuedMessage; end: RunEnd }
+ | null => {
let end = snapshot.getLoadable(store.runEndByIndex(index)).getValue();
let fromParked = false;
if (
@@ -305,8 +327,11 @@ export default function useQueueDrain(
/** Keep the one-shot terminal signal until the authoritative snapshot
* removes the server row. If it was admitted, its own later terminal
* signal orders the remaining local queue; if it was cancelled/dead,
- * this signal still lets the legacy successor make progress. */
- return null;
+ * this signal still lets the legacy successor make progress. The
+ * head the server is about to admit can already be shown as the
+ * next user turn; the signal itself stays untouched. */
+ const reveal = selectQueuedTurnReveal(end, merged);
+ return reveal == null ? null : { kind: 'reveal', item: reveal, end };
}
// Consume only after server authority has yielded the boundary — a
@@ -324,6 +349,7 @@ export default function useQueueDrain(
}
return next
? {
+ kind: 'drain',
next,
conversationId,
queuedMessageOrigin: {
@@ -365,6 +391,10 @@ export default function useQueueDrain(
if (drained == null) {
return;
}
+ if (drained.kind === 'reveal') {
+ revealQueuedTurn?.(drained.item, drained.end);
+ return;
+ }
const { next, conversationId, queuedMessageOrigin, expectedPredecessorCreatedAt } = drained;
// The queued item is the FULL submission context: explicit (possibly
// empty) overrides stop `ask` from vacuuming up files, quotes, or skill
@@ -414,6 +444,9 @@ export default function useQueueDrain(
markFilesUsage,
hasServerOwnedQueue,
settledQueuedTurnReceipts,
+ revealedQueuedTurn,
+ admissibleHeadId,
+ revealQueuedTurn,
ask,
]);
}
diff --git a/client/src/hooks/Chat/useQueuedTurnReveal.ts b/client/src/hooks/Chat/useQueuedTurnReveal.ts
new file mode 100644
index 0000000000..31e686fc4f
--- /dev/null
+++ b/client/src/hooks/Chat/useQueuedTurnReveal.ts
@@ -0,0 +1,209 @@
+import { useCallback, useEffect, useSyncExternalStore } from 'react';
+import { useRecoilValue } from 'recoil';
+import { useStore, useAtomValue } from 'jotai';
+import { QueryKeys } from 'librechat-data-provider';
+import { useQueryClient } from '@tanstack/react-query';
+import type { TMessage, TAgentQueuedTurnReceipt } from 'librechat-data-provider';
+import type { StreamStatusResponse } from '~/data-provider/SSE/queries';
+import type { QueuedMessage, RunEnd } from '~/store/families';
+import type { RevealedQueuedTurn } from '~/store/steer';
+import { agentQueuedTurnsQueryKey } from '~/data-provider/SSE/queuedTurns';
+import { streamStatusQueryKey } from '~/data-provider/SSE/queries';
+import { revealedQueuedTurnFamily } from '~/store/steer';
+import store from '~/store';
+
+const isAdmissible = (item: QueuedMessage): boolean =>
+ item.server?.id != null &&
+ item.clientRequestId != null &&
+ (item.server.status === 'queued' || item.server.status === 'claimed');
+
+/**
+ * The server-owned row the backend will admit behind a run that just
+ * completed cleanly: the first durably enqueued row that has not settled.
+ * Rows ahead of it never stand in for the successor: a local row cannot
+ * drain while the server owns the boundary, and a rejected or still-sending
+ * server row is not what the backend will admit. A Stop or an error leaves
+ * every chip in place.
+ */
+export const selectQueuedTurnReveal = (
+ end: RunEnd,
+ queue: QueuedMessage[],
+): QueuedMessage | null => {
+ if (
+ end.outcome !== 'completed' ||
+ end.responseMessageId == null ||
+ end.generationCreatedAt == null
+ ) {
+ return null;
+ }
+ return queue.find(isAdmissible) ?? null;
+};
+
+/** The thread has moved past the response the reveal follows: the admitted
+ * turn, or any other turn, now parents on it. */
+export const hasRevealSuccessor = (messages: TMessage[], reveal: RevealedQueuedTurn): boolean =>
+ messages.some((message) => message.parentMessageId === reveal.parentMessageId);
+
+/** Authoritative evidence that the revealed turn will not run as shown. */
+export const shouldRollbackReveal = (
+ receipts: TAgentQueuedTurnReceipt[],
+ reveal: RevealedQueuedTurn,
+): boolean =>
+ receipts.some(
+ (receipt) =>
+ receipt.clientRequestId === reveal.clientRequestId &&
+ (receipt.status === 'cancelled' ||
+ receipt.status === 'dead' ||
+ receipt.failure?.code === 'ADMISSION_INDETERMINATE'),
+ );
+
+/** A render-only message for the revealed row: it feeds the same row
+ * primitives a persisted user turn uses and is never written to the cache. */
+export const buildRevealedMessage = (
+ reveal: RevealedQueuedTurn,
+ conversationId: string,
+): TMessage =>
+ ({
+ messageId: `revealed-${reveal.clientRequestId}`,
+ parentMessageId: reveal.parentMessageId,
+ conversationId,
+ text: reveal.text,
+ sender: 'User',
+ isCreatedByUser: true,
+ error: false,
+ clientTimestamp: reveal.revealedAt,
+ ...(reveal.files != null && reveal.files.length > 0 && { files: reveal.files }),
+ ...(reveal.quotes != null && reveal.quotes.length > 0 && { quotes: reveal.quotes }),
+ ...(reveal.manualSkills != null &&
+ reveal.manualSkills.length > 0 && { manualSkills: reveal.manualSkills }),
+ }) as TMessage;
+
+/** Presentation and admission have separate lifetimes: history replaces the
+ * drawn row, but sends stay queued until the successor attaches or terminates.
+ * Observe existing caches without registering a competing query function. */
+export default function useQueuedTurnReveal(
+ conversationId: string | undefined,
+ index: string | number = 0,
+): (item: QueuedMessage, end: RunEnd) => void {
+ const jotaiStore = useStore();
+ const queryClient = useQueryClient();
+ const revealKey = conversationId ?? '';
+ const reveal = useAtomValue(revealedQueuedTurnFamily(revealKey));
+ const isSubmitting = useRecoilValue(store.isSubmittingFamily(index));
+ const activeEpoch = useRecoilValue(store.activeGenerationCreatedAtByConvoId(revealKey));
+ const readHandoff = useCallback(
+ (intent: RevealedQueuedTurn) => {
+ const receipts = queryClient.getQueryData<TAgentQueuedTurnReceipt[]>(
+ agentQueuedTurnsQueryKey(revealKey),
+ );
+ const status = queryClient.getQueryData<StreamStatusResponse>(
+ streamStatusQueryKey(revealKey),
+ );
+ let generationCreatedAt = intent.generationCreatedAt;
+ let waiting = false;
+ for (const receipt of receipts ?? []) {
+ const actionable =
+ (receipt.status === 'queued' || receipt.status === 'claimed') &&
+ receipt.failure?.code !== 'ADMISSION_INDETERMINATE';
+ waiting ||= actionable;
+ if (!actionable && receipt.status !== 'admitted') {
+ continue;
+ }
+ const boundary =
+ receipt.effectivePredecessorCreatedAt ?? receipt.expectedPredecessorCreatedAt;
+ if (boundary != null && (generationCreatedAt == null || boundary > generationCreatedAt)) {
+ generationCreatedAt = boundary;
+ }
+ }
+ return {
+ generationCreatedAt,
+ settled:
+ (receipts != null && shouldRollbackReveal(receipts, intent)) ||
+ (generationCreatedAt != null &&
+ ((isSubmitting && activeEpoch != null && activeEpoch > generationCreatedAt) ||
+ (!waiting &&
+ status?.active === false &&
+ (status.status === 'complete' ||
+ status.status === 'error' ||
+ status.status === 'aborted') &&
+ status.createdAt != null &&
+ status.createdAt > generationCreatedAt))),
+ };
+ },
+ [queryClient, revealKey, isSubmitting, activeEpoch],
+ );
+ const subscribe = useCallback(
+ (notify: () => void) =>
+ queryClient.getQueryCache().subscribe((event) => {
+ const key = event?.query.queryKey;
+ if (
+ key?.[1] === revealKey &&
+ (key[0] === QueryKeys.agentQueuedTurns || key[0] === 'streamStatus')
+ ) {
+ notify();
+ }
+ }),
+ [queryClient, revealKey],
+ );
+ /** Only ownership facts trigger a render, not every receipt poll. Remember
+ * an admitted successor's effective boundary even after its receipt leaves
+ * the projection, so an earlier terminal cannot release a later handoff. */
+ const getSnapshot = useCallback(() => {
+ if (reveal == null) return '';
+ const handoff = readHandoff(reveal);
+ return `${handoff.generationCreatedAt ?? ''}:${handoff.settled}`;
+ }, [reveal, readHandoff]);
+ const handoffVersion = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+
+ const revealQueuedTurn = useCallback(
+ (item: QueuedMessage, end: RunEnd) => {
+ const target = end.conversationId;
+ if (
+ target == null ||
+ target !== conversationId ||
+ end.outcome !== 'completed' ||
+ end.responseMessageId == null ||
+ end.generationCreatedAt == null ||
+ item.clientRequestId == null ||
+ !isAdmissible(item)
+ ) {
+ return;
+ }
+ const family = revealedQueuedTurnFamily(target);
+ if (jotaiStore.get(family) != null) {
+ return;
+ }
+ const intent: RevealedQueuedTurn = {
+ clientRequestId: item.clientRequestId,
+ parentMessageId: end.responseMessageId,
+ generationCreatedAt: end.generationCreatedAt,
+ queueParentMessageId: item.parentMessageId,
+ queuePredecessorCreatedAt: item.expectedPredecessorCreatedAt,
+ text: item.text,
+ ...(item.files != null && item.files.length > 0 && { files: item.files }),
+ ...(item.quotes != null && item.quotes.length > 0 && { quotes: item.quotes }),
+ ...(item.manualSkills != null &&
+ item.manualSkills.length > 0 && { manualSkills: item.manualSkills }),
+ revealedAt: new Date().toISOString(),
+ };
+ const handoff = readHandoff(intent);
+ if (!handoff.settled) {
+ jotaiStore.set(family, { ...intent, generationCreatedAt: handoff.generationCreatedAt });
+ }
+ },
+ [conversationId, readHandoff, jotaiStore],
+ );
+
+ useEffect(() => {
+ const family = revealedQueuedTurnFamily(revealKey);
+ if (reveal == null || jotaiStore.get(family) !== reveal) return;
+ const handoff = readHandoff(reveal);
+ if (handoff.settled) {
+ jotaiStore.set(family, null);
+ } else if (handoff.generationCreatedAt !== reveal.generationCreatedAt) {
+ jotaiStore.set(family, { ...reveal, generationCreatedAt: handoff.generationCreatedAt });
+ }
+ }, [jotaiStore, revealKey, reveal, readHandoff, handoffVersion]);
+
+ return revealQueuedTurn;
+}
diff --git a/client/src/hooks/Chat/useSteering.ts b/client/src/hooks/Chat/useSteering.ts
index 56e9520d19..02867fcb73 100644
--- a/client/src/hooks/Chat/useSteering.ts
+++ b/client/src/hooks/Chat/useSteering.ts
@@ -1,5 +1,6 @@
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { v4 } from 'uuid';
+import { useAtomValue, useStore } from 'jotai';
import { useToastContext } from '@librechat/client';
import { useRecoilValue, useSetRecoilState, useRecoilCallback } from 'recoil';
import {
@@ -37,13 +38,12 @@ import {
import {
appendAppliedSteerIds,
carriedSteerContext,
- clearAllDrafts,
- getPendingDraftId,
insertQueuedOrigin,
hydrateFileDeliveryMetadata,
mergeRestagedQuotes,
} from '~/utils';
import useSteerConvert from '~/hooks/Chat/useSteerConvert';
+import { revealedQueuedTurnFamily } from '~/store/steer';
import { useLatestMessage } from '~/hooks/Messages';
import { useSetFilesToDelete } from '~/hooks/Files';
import { useFileMapContext } from '~/Providers';
@@ -372,6 +372,8 @@ function reconcileServerQueuedTurns(
}
export interface UseSteeringParams {
+ /** Consume the actual storage key selected by the composer’s autosave owner. */
+ consumeDraft: () => void;
index: number;
conversationId: string;
conversation: TConversation | null;
@@ -405,6 +407,7 @@ export interface UseSteeringParams {
* (abort, then auto-send via the one-shot drain override).
*/
export default function useSteering({
+ consumeDraft: takeComposerDraft,
index,
conversationId,
conversation,
@@ -418,6 +421,7 @@ export default function useSteering({
}: UseSteeringParams) {
const localize = useLocalize();
const { showToast } = useToastContext();
+ const jotaiStore = useStore();
const fileMap = useFileMapContext();
const setFilesToDelete = useSetFilesToDelete();
const convertSteersToQueued = useSteerConvert();
@@ -471,12 +475,31 @@ export default function useSteering({
const expiry = item.server.uncertainSince + QUEUED_TURN_RECONCILIATION_MS;
return earliest == null ? expiry : Math.min(earliest, expiry);
}, undefined);
+ /** An expired uncertain row is held for manual recovery only; nothing the
+ * projection can say about it is still expected. */
+ const expectsReceipts = useMemo(
+ () =>
+ queuedMessages.some(
+ (item) =>
+ item.server != null &&
+ (item.server.status === 'sending' ||
+ item.server.status === 'queued' ||
+ item.server.status === 'claimed' ||
+ (item.server.status === 'uncertain' && item.server.reconciliationExpired !== true)),
+ ),
+ [queuedMessages],
+ );
const { data: serverQueuedTurns } = useAgentQueuedTurns(
conversationId,
serverQueueEnabled,
knownClientRequestIds,
reconciliationUntil,
+ expectsReceipts,
);
+ /** Retain admission ownership through history hydration and stream attach;
+ * ordinary sends must not overtake the server-owned successor. */
+ const pendingReveal = useAtomValue(revealedQueuedTurnFamily(queueKey));
+ const revealPending = pendingReveal != null;
const activeGenerationCreatedAt = useRecoilValue(
store.activeGenerationCreatedAtByConvoId(queueKey),
);
@@ -603,7 +626,7 @@ export default function useSteering({
* `isSubmitting` flips earlier so the user can keep typing; during that
* bounded interval submits degrade to the local queue and Stop/steer refuse. */
const canControlGeneration = activeGenerationCreatedAt != null;
- const duringRunActive = enabled && isSubmitting && !answerModeActive;
+ const duringRunActive = enabled && (isSubmitting || revealPending) && !answerModeActive;
/** Queue rows can be sent concurrently. Keep their captured origins while
* absent so a later capture still sees the complete logical queue. Origins
* are isolated per conversation because this hook survives navigation. */
@@ -724,7 +747,7 @@ export default function useSteering({
/** Whether a queued row has a real immediate-send path. Answer mode keeps
* `isSubmitting` true while hiding during-run steering, so presenting Send
* now there would be an enabled no-op. */
- const canSendQueuedNow = !isSubmitting || (duringRunActive && canSteer);
+ const canSendQueuedNow = (!isSubmitting && !revealPending) || (duringRunActive && canSteer);
/** Steering needs a live server-side job; degrade to queue otherwise. */
const effectiveAction: DuringRunAction = canSteer ? defaultAction : 'queue';
@@ -962,12 +985,20 @@ export default function useSteering({
if (trimmed.length === 0) {
return;
}
- const parentMessageId = liveMessageState?.parentMessageId;
- /** The active epoch is the authority-transfer fence. During startup an
- * existing branch tail may already be visible while no generation owns
- * it yet, so keep those turns local until the epoch is concrete. */
+ const parentMessageId =
+ pendingReveal != null
+ ? pendingReveal.queueParentMessageId
+ : liveMessageState?.parentMessageId;
+ const predecessorCreatedAt =
+ pendingReveal != null
+ ? pendingReveal.queuePredecessorCreatedAt
+ : activeGenerationCreatedAt;
+ /** FINAL clears the active epoch before attachment. The revealed
+ * intent retains the queue's original parent/epoch pair. Its display
+ * parent and advancing completion boundary are not queue lineage.
+ * Without an authoritative pair, retain the follow-up locally. */
const serverOwned =
- serverQueueEnabled && parentMessageId != null && activeGenerationCreatedAt != null;
+ serverQueueEnabled && parentMessageId != null && predecessorCreatedAt != null;
const generatedClientRequestId = options?.clientRequestId == null;
const clientRequestId = options?.clientRequestId ?? (serverOwned ? v4() : undefined);
const item: QueuedMessage = {
@@ -979,9 +1010,9 @@ export default function useSteering({
parentMessageId,
server: { status: 'sending' },
}),
- ...((options?.expectedPredecessorCreatedAt ?? activeGenerationCreatedAt) != null && {
+ ...((options?.expectedPredecessorCreatedAt ?? predecessorCreatedAt) != null && {
expectedPredecessorCreatedAt:
- options?.expectedPredecessorCreatedAt ?? activeGenerationCreatedAt ?? undefined,
+ options?.expectedPredecessorCreatedAt ?? predecessorCreatedAt ?? undefined,
}),
...(options?.files && options.files.length > 0 && { files: options.files }),
...(options?.quotes && options.quotes.length > 0 && { quotes: options.quotes }),
@@ -1078,6 +1109,7 @@ export default function useSteering({
conversationId,
serverQueueEnabled,
liveMessageState?.parentMessageId,
+ pendingReveal,
markQueuedFilesUsage,
activeGenerationCreatedAt,
enqueueAgentQueuedTurn,
@@ -1203,19 +1235,6 @@ export default function useSteering({
[],
);
- /** Consumes the composer's autosaved draft once its text has been taken into
- * a steer or queued item. The composer clears via the form's `reset()`,
- * which is programmatic and never fires the `input` event `useAutoSave`
- * listens on — so the draft would outlive the submit. It is keyed under
- * this pane's pending draft key here (every caller is gated on
- * `duringRunActive`, which requires `isSubmitting` and rules out the
- * answer-mode draft key), and run end migrates a surviving pending draft
- * onto the conversation and restores it: resurfacing text the user already
- * sent. */
- const takeComposerDraft = useCallback(() => {
- clearAllDrafts(getPendingDraftId(index));
- }, [index]);
-
const removeQueued = useRecoilCallback(
({ set }) =>
(id: string) => {
@@ -1309,6 +1328,12 @@ export default function useSteering({
return false;
}
applyQueuedTurnReceipts([receipt], 'direct');
+ /** The turn was shown as next; the confirmed cancellation ends that
+ * at once rather than on the next receipt refetch. */
+ const revealFamily = revealedQueuedTurnFamily(queueKey);
+ if (jotaiStore.get(revealFamily)?.clientRequestId === item.clientRequestId) {
+ jotaiStore.set(revealFamily, null);
+ }
return downgradeServerQueuedTurn(item.id);
} catch {
showToast({
@@ -1360,6 +1385,8 @@ export default function useSteering({
hasRealConvoId,
localize,
showToast,
+ jotaiStore,
+ queueKey,
],
);
diff --git a/client/src/hooks/Input/useAutoSave.spec.ts b/client/src/hooks/Input/useAutoSave.spec.ts
index 09d2d1d608..62cc492a7a 100644
--- a/client/src/hooks/Input/useAutoSave.spec.ts
+++ b/client/src/hooks/Input/useAutoSave.spec.ts
@@ -36,6 +36,7 @@ import { useGetFiles } from '~/data-provider';
import { hasInFlightUpload } from '~/hooks/Files/useFileHandling';
import {
encodeBase64,
+ clearAllDrafts,
getAskAnswerDraftId,
getDraft,
getFilesDraft,
@@ -735,6 +736,41 @@ describe('useAutoSave — file cache updates', () => {
expect(mockSetValue).not.toHaveBeenCalledWith('text', 'other tab text');
expect(getFilesDraft('convo-2').tabId).toBe('other-tab');
});
+ it('consumes the retained pending draft without clearing a foreign conversation draft', () => {
+ markTabLive('other-tab');
+ (clearAllDrafts as jest.Mock).mockImplementation(jest.requireActual('~/utils').clearAllDrafts);
+ const { result, rerender, unmount } = renderHook(
+ ({ isSubmitting }: { isSubmitting: boolean }) =>
+ useAutoSave({
+ isSubmitting,
+ conversationId: 'convo-2',
+ textAreaRef: makeTextAreaRef(),
+ files: new Map(),
+ setFiles: jest.fn(),
+ }),
+ { initialProps: { isSubmitting: true } },
+ );
+ setFilesDraft(Constants.PENDING_CONVO, { fileIds: ['ours'], pendingPastes: {} });
+ setFilesDraft('convo-2', {
+ fileIds: ['theirs'],
+ pendingPastes: {},
+ tabId: 'other-tab',
+ });
+ const pendingTextKey = `${LocalStorageKeys.TEXT_DRAFT}${Constants.PENDING_CONVO}`;
+ const foreignTextKey = `${LocalStorageKeys.TEXT_DRAFT}convo-2`;
+ localStorage.setItem(pendingTextKey, encodeBase64('submitted text'));
+ localStorage.setItem(foreignTextKey, encodeBase64('their text'));
+ act(() => rerender({ isSubmitting: false }));
+ act(() => result.current());
+ expect(clearAllDrafts).toHaveBeenLastCalledWith(Constants.PENDING_CONVO);
+ expect(localStorage.getItem(pendingTextKey)).toBeNull();
+ expect(getFilesDraft(Constants.PENDING_CONVO).fileIds).toEqual([]);
+ expect(localStorage.getItem(foreignTextKey)).toBe(encodeBase64('their text'));
+ expect(getFilesDraft('convo-2').fileIds).toEqual(['theirs']);
+ unmount();
+ (clearAllDrafts as jest.Mock).mockReset();
+ });
+
it('keeps autosaving to the pending key while the destination is owned by another live tab', () => {
jest.useFakeTimers();
markTabLive('other-tab');
diff --git a/client/src/hooks/Input/useAutoSave.ts b/client/src/hooks/Input/useAutoSave.ts
index 31ccc1f54f..f6d46fd9ed 100644
--- a/client/src/hooks/Input/useAutoSave.ts
+++ b/client/src/hooks/Input/useAutoSave.ts
@@ -8,6 +8,7 @@ import type { ExtendedFile } from '~/common';
import {
applyPendingPastesToDraft,
clearDraft,
+ clearAllDrafts,
getDraft,
getFilesDraft,
getNewConversationDraftId,
@@ -208,6 +209,13 @@ export const useAutoSave = ({
* which after a send put the just-sent attachment straight back as a chip. */
const activeStorageId =
currentConversationId === pendingDraftId ? pendingDraftId : conversationId;
+ /** Only autosave knows whether a foreign tab kept this composer on the
+ * pending key. Submission consumes that actual key under its ownership guard. */
+ const consumeDraft = useCallback(() => {
+ if (activeStorageId) {
+ clearAllDrafts(activeStorageId);
+ }
+ }, [activeStorageId]);
useEffect(() => {
// This useEffect is responsible for setting up and cleaning up the auto-save functionality
// for the text area input. It saves the text to localStorage with a debounce to prevent
@@ -456,4 +464,6 @@ export const useAutoSave = ({
pendingPastes: existingDraft.pendingPastes,
});
}, [conversationId, saveDrafts, currentConversationId, fileIds, files]);
+
+ return consumeDraft;
};
diff --git a/client/src/hooks/Messages/__tests__/useSubmitMessage.spec.ts b/client/src/hooks/Messages/__tests__/useSubmitMessage.spec.ts
index 9525d4a622..ee07598295 100644
--- a/client/src/hooks/Messages/__tests__/useSubmitMessage.spec.ts
+++ b/client/src/hooks/Messages/__tests__/useSubmitMessage.spec.ts
@@ -83,6 +83,21 @@ describe('useSubmitMessage', () => {
expect(reset).not.toHaveBeenCalled();
});
+ it.each([false, true])('preserves a refused automatic prompt (accepted=%s)', (accepted) => {
+ mockUseRecoilValue.mockReturnValue(true);
+ ask.mockReturnValue(accepted);
+ const { result } = renderHook(() => useSubmitMessage());
+ act(() => result.current.submitPrompt('selected prompt'));
+ expect(ask).toHaveBeenCalledWith({ text: 'selected prompt' }, expect.any(Object));
+ if (accepted) {
+ expect(mockSetActivePrompt).not.toHaveBeenCalled();
+ expect(reset).toHaveBeenCalled();
+ } else {
+ expect(mockSetActivePrompt).toHaveBeenCalledWith('selected prompt');
+ expect(reset).not.toHaveBeenCalled();
+ }
+ });
+
it('reads the tail at call time and appends it to root when missing', () => {
const rootMessages = [{ messageId: 'root-user' }];
const latest = { messageId: 'assistant-tail', text: 'tail' };
diff --git a/client/src/hooks/Messages/useSubmitMessage.ts b/client/src/hooks/Messages/useSubmitMessage.ts
index 17179e7f0b..a01d1ce1d4 100644
--- a/client/src/hooks/Messages/useSubmitMessage.ts
+++ b/client/src/hooks/Messages/useSubmitMessage.ts
@@ -72,10 +72,12 @@ export default function useSubmitMessage() {
const submitPrompt = useCallback(
(text: string) => {
const parsedText = replaceSpecialVars({ text, user });
- if (autoSendPrompts) {
- submitMessage({ text: parsedText });
+ if (autoSendPrompts && submitMessage({ text: parsedText }) !== false) {
return;
}
+ /** A refused auto-send still belongs to the user. Stage it exactly like
+ * a non-auto-sent prompt so every picker, including variable dialogs,
+ * preserves the text for the composer's guarded submit route. */
const textarea = document.getElementById(mainTextareaId) as HTMLTextAreaElement | null;
const currentText = textarea?.value ?? methods.getValues('text');
diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
index a0adf1d577..b0fedd0067 100644
--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
@@ -2192,73 +2192,114 @@ describe('useResumableSSE', () => {
unmount();
});
- it('reconciles a synthesized terminal frame without rendering a bogus final or error', async () => {
- (request.post as jest.Mock).mockResolvedValue({
- streamId: CONV_ID,
- status: 'started',
- generationCreatedAt: 1000,
- generationProtocolVersion: 2,
- });
- const persisted = [
- {
- messageId: 'persisted-response',
- conversationId: CONV_ID,
- isCreatedByUser: false,
- text: 'Persisted answer',
- },
- ] as TMessage[];
- mockGetQueryData.mockReturnValue(persisted);
- mockFetchStreamStatus.mockResolvedValue({ active: false, generationProtocolVersion: 2 });
- const submission = buildSubmission();
- const chatHelpers = buildChatHelpers();
- getDefaultStore().set(pendingApprovalActionFamily(CONV_ID), {
- actionId: 'stale-action',
- streamId: CONV_ID,
- createdAt: 1000,
- payload: { type: 'tool_approval', action_requests: [], review_configs: [] },
- });
+ it.each([
+ 'status',
+ 'submission',
+ 'unique-placeholder',
+ 'ambiguous-placeholder',
+ 'missing-response',
+ ])(
+ 'reconciles a synthesized terminal using %s response identity instead of a later sibling',
+ async (identitySource) => {
+ (request.post as jest.Mock).mockResolvedValue({
+ streamId: CONV_ID,
+ status: 'started',
+ generationCreatedAt: 1000,
+ generationProtocolVersion: 2,
+ });
+ const persisted = [
+ {
+ messageId: 'persisted-response',
+ parentMessageId: 'msg-1',
+ conversationId: CONV_ID,
+ isCreatedByUser: false,
+ text: 'Persisted answer',
+ },
+ {
+ messageId: 'later-sibling',
+ parentMessageId: 'msg-1',
+ conversationId: CONV_ID,
+ isCreatedByUser: false,
+ text: 'A different branch',
+ },
+ ] as TMessage[];
+ if (identitySource === 'unique-placeholder') {
+ persisted.pop();
+ }
+ mockGetQueryData.mockReturnValue(persisted);
+ mockFetchStreamStatus.mockResolvedValue({
+ active: false,
+ generationProtocolVersion: 2,
+ ...(identitySource === 'status' && {
+ resumeState: { responseMessageId: 'persisted-response' },
+ }),
+ });
+ const responseIds: Record<string, string> = {
+ submission: 'persisted-response_',
+ 'missing-response': 'missing-response_',
+ };
+ const submission = buildSubmission({
+ initialResponse: { messageId: responseIds[identitySource] ?? 'msg-1_' },
+ });
+ const chatHelpers = buildChatHelpers();
+ getDefaultStore().set(pendingApprovalActionFamily(CONV_ID), {
+ actionId: 'stale-action',
+ streamId: CONV_ID,
+ createdAt: 1000,
+ payload: { type: 'tool_approval', action_requests: [], review_configs: [] },
+ });
- const { unmount } = renderHook(() => useResumableSSE(submission, chatHelpers));
- await flushMicrotasks();
+ const { unmount } = renderHook(() => useResumableSSE(submission, chatHelpers));
+ await flushMicrotasks();
- const sse = getLastSSE();
- await act(async () => {
- sse._emit('message', {
- data: JSON.stringify({
- final: true,
- reconcile: true,
- reconcileReason: 'terminal_payload_missing',
- terminalStatus: 'complete',
- generationCreatedAt: 1000,
- generationProtocolVersion: 2,
- conversation: { conversationId: CONV_ID },
- }),
+ const sse = getLastSSE();
+ await act(async () => {
+ sse._emit('message', {
+ data: JSON.stringify({
+ final: true,
+ reconcile: true,
+ reconcileReason: 'terminal_payload_missing',
+ terminalStatus: 'complete',
+ generationCreatedAt: 1000,
+ generationProtocolVersion: 2,
+ conversation: { conversationId: CONV_ID },
+ }),
+ });
+ await Promise.resolve();
});
- await Promise.resolve();
- });
- await flushMicrotasks();
+ await flushMicrotasks();
- expect(mockFinalHandler).not.toHaveBeenCalled();
- expect(mockErrorHandler).not.toHaveBeenCalled();
- expect(getDefaultStore().get(pendingApprovalActionFamily(CONV_ID))).toBeNull();
- expect(mockInvalidateQueries).toHaveBeenCalledWith({
- queryKey: [QueryKeys.messages, CONV_ID],
- refetchType: 'none',
- });
- expect(mockInvalidateQueries).toHaveBeenCalledWith({
- queryKey: [QueryKeys.allConversations],
- });
- expect(mockInvalidateQueries).toHaveBeenCalledWith({
- queryKey: [QueryKeys.pinnedConversations],
- });
- expect(mockSettleAppliedSteerParts).toHaveBeenCalledWith(CONV_ID, persisted);
- expect(mockSetRunEnd).toHaveBeenCalledWith(
- expect.objectContaining({ conversationId: CONV_ID, outcome: 'completed' }),
- );
- expect(mockSetSubmission).toHaveBeenCalledWith(null);
- expect(mockUpdateGenerationEpoch).toHaveBeenCalledWith(CONV_ID, null, 1000);
- unmount();
- });
+ expect(mockFinalHandler).not.toHaveBeenCalled();
+ expect(mockErrorHandler).not.toHaveBeenCalled();
+ expect(getDefaultStore().get(pendingApprovalActionFamily(CONV_ID))).toBeNull();
+ expect(mockInvalidateQueries).toHaveBeenCalledWith({
+ queryKey: [QueryKeys.messages, CONV_ID],
+ refetchType: 'none',
+ });
+ expect(mockInvalidateQueries).toHaveBeenCalledWith({
+ queryKey: [QueryKeys.allConversations],
+ });
+ expect(mockInvalidateQueries).toHaveBeenCalledWith({
+ queryKey: [QueryKeys.pinnedConversations],
+ });
+ expect(mockSettleAppliedSteerParts).toHaveBeenCalledWith(CONV_ID, persisted);
+ expect(mockSetRunEnd).toHaveBeenCalledWith(
+ expect.objectContaining({
+ conversationId: CONV_ID,
+ outcome: 'completed',
+ ...(['status', 'submission', 'unique-placeholder'].includes(identitySource) && {
+ responseMessageId: 'persisted-response',
+ }),
+ }),
+ );
+ if (['ambiguous-placeholder', 'missing-response'].includes(identitySource)) {
+ expect(mockSetRunEnd.mock.calls.at(-1)?.[0]).not.toHaveProperty('responseMessageId');
+ }
+ expect(mockSetSubmission).toHaveBeenCalledWith(null);
+ expect(mockUpdateGenerationEpoch).toHaveBeenCalledWith(CONV_ID, null, 1000);
+ unmount();
+ },
+ );
it('ignores v2-only lifecycle reconciliation on a legacy generation', async () => {
(request.post as jest.Mock).mockResolvedValue({
diff --git a/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx b/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx
index 6365f2097e..9104c4c6b6 100644
--- a/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx
+++ b/client/src/hooks/SSE/__tests__/useResumeOnLoad.spec.tsx
@@ -9,6 +9,8 @@ import type { ReactNode } from 'react';
import type { PendingSteer, QueuedMessage } from '~/store/families';
import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/state';
import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
+import { agentQueuedTurnsQueryKey } from '~/data-provider/SSE/queuedTurns';
+import { revealedQueuedTurnFamily } from '~/store/steer';
import useResumeOnLoad from '../useResumeOnLoad';
import store from '~/store';
@@ -976,15 +978,50 @@ describe('useResumeOnLoad', () => {
expect(attached?.resumeStreamId).toBe(CONVERSATION_ID);
});
+ it('retires a remounted reveal after fresh inactive status and restored successor history', async () => {
+ mockUseStreamStatus.mockReturnValue({ ...INACTIVE_STATUS, isSuccess: false });
+ mockUseAgentQueuedTurns.mockReturnValue({ data: [] });
+ const messages = [
+ buildUserMessage(CONVERSATION_ID),
+ { messageId: 'successor', parentMessageId: 'response' } as TMessage,
+ ];
+ const { rerender, jotaiStore, queryClient } = renderUseResumeOnLoad({ messages });
+ const family = revealedQueuedTurnFamily(CONVERSATION_ID);
+ act(() => {
+ queryClient.setQueryData([QueryKeys.messages, CONVERSATION_ID], messages);
+ jotaiStore.set(family, {
+ clientRequestId: 'queued',
+ parentMessageId: 'response',
+ generationCreatedAt: 41,
+ text: 'queued',
+ revealedAt: new Date(Date.now() - 60_000).toISOString(),
+ });
+ });
+ mockUseStreamStatus.mockReturnValue({ ...INACTIVE_STATUS, dataUpdatedAt: Date.now() + 1 });
+ rerender();
+ expect(jotaiStore.get(family)).toBeNull();
+ });
+
it('lets the owed state lapse once the receipt has gone quiet for the window', async () => {
jest.useFakeTimers();
mockUseStreamStatus.mockReturnValue(INACTIVE_STATUS);
mockUseAgentQueuedTurns.mockReturnValue({ data: [{ status: 'queued' }], dataUpdatedAt: 2 });
- const { rerender } = renderUseResumeOnLoad({ messages: [buildUserMessage(CONVERSATION_ID)] });
+ const { rerender, jotaiStore } = renderUseResumeOnLoad({
+ messages: [buildUserMessage(CONVERSATION_ID)],
+ });
await act(async () => {
await Promise.resolve();
});
+ const revealFamily = revealedQueuedTurnFamily(CONVERSATION_ID);
+ jotaiStore.set(revealFamily, {
+ clientRequestId: 'queued',
+ parentMessageId: 'response',
+ generationCreatedAt: 41,
+ text: 'queued',
+ revealedAt: new Date().toISOString(),
+ });
+
/** A long wait behind an unadmitted turn must not burn the window: the
* countdown starts only when the receipt stops reporting. */
await act(async () => {
@@ -992,6 +1029,7 @@ describe('useResumeOnLoad', () => {
});
expect(mockUseActiveJobs).toHaveBeenLastCalledWith(true, true);
+ expect(jotaiStore.get(revealFamily)).not.toBeNull();
mockUseAgentQueuedTurns.mockReturnValue({ data: [], dataUpdatedAt: 3 });
rerender();
await act(async () => {
@@ -1004,6 +1042,7 @@ describe('useResumeOnLoad', () => {
});
rerender();
expect(mockUseActiveJobs).toHaveBeenLastCalledWith(true, false);
+ expect(jotaiStore.get(revealFamily)).toBeNull();
jest.useRealTimers();
});
@@ -1263,6 +1302,47 @@ describe('useResumeOnLoad', () => {
nowSpy.mockRestore();
});
+ it.each(['queued', 'claimed', 'admitted'])(
+ 'retains off-screen admission ownership while a cached receipt is %s',
+ async (status) => {
+ jest.useFakeTimers();
+ mockUseStreamStatus.mockReturnValue(INACTIVE_STATUS);
+ mockUseAgentQueuedTurns.mockReturnValue({
+ data: [{ queuedTurnId: 'q1', status }],
+ dataUpdatedAt: 2,
+ });
+ const { rerender, queryClient, jotaiStore } = renderUseResumeOnLoad({
+ messages: [buildUserMessage(CONVERSATION_ID)],
+ });
+ const family = revealedQueuedTurnFamily(CONVERSATION_ID);
+ act(() => {
+ jotaiStore.set(family, {
+ clientRequestId: 'request',
+ parentMessageId: 'response',
+ generationCreatedAt: 41,
+ text: 'queued',
+ revealedAt: new Date().toISOString(),
+ });
+ queryClient.setQueryData(agentQueuedTurnsQueryKey(CONVERSATION_ID), [
+ { queuedTurnId: 'q1', status },
+ ]);
+ });
+ mockUseAgentQueuedTurns.mockReturnValue({ data: [], dataUpdatedAt: 3 });
+ rerender({ conversationId: STALE_CONVERSATION_ID });
+ await act(async () => {
+ jest.advanceTimersByTime(30_001);
+ });
+ expect(jotaiStore.get(family)).not.toBeNull();
+ mockUseAgentQueuedTurns.mockReturnValue({
+ data: [{ queuedTurnId: 'q1', status }],
+ dataUpdatedAt: 4,
+ });
+ rerender({ conversationId: CONVERSATION_ID });
+ expect(jotaiStore.get(family)).not.toBeNull();
+ jest.useRealTimers();
+ },
+ );
+
it('expires the owed state on an absolute window even while its conversation is off-screen', async () => {
jest.useFakeTimers();
mockUseStreamStatus.mockReturnValue(INACTIVE_STATUS);
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index 2050e2799c..f677914321 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -501,6 +501,38 @@ const replaceNewConversationUrl = (conversationId: string) => {
const shouldHydrateMessage = (message: TMessage) =>
!hasConcreteConversationId(message.conversationId);
+/** Recovery must identify the response itself: regenerations share a user
+ * parent, and array order says nothing about which sibling just completed.
+ * A fresh-turn placeholder has no server response ID yet; only an unambiguous
+ * persisted child can stand in for it. */
+const completedResponseMessageId = (
+ messages: TMessage[] | undefined,
+ userMessageId: string | undefined,
+ responseMessageId: string | undefined,
+): string | undefined => {
+ if (messages == null || userMessageId == null) {
+ return undefined;
+ }
+ const target = responseMessageId?.replace(/_+$/, '');
+ const hasResponseIdentity = target != null && target !== userMessageId;
+ let candidate: string | undefined;
+ let ambiguous = false;
+ for (const message of messages) {
+ if (message.isCreatedByUser !== false || message.parentMessageId !== userMessageId) {
+ continue;
+ }
+ if (hasResponseIdentity) {
+ if (message.messageId === target) {
+ return message.messageId;
+ }
+ continue;
+ }
+ ambiguous ||= candidate != null;
+ candidate = message.messageId;
+ }
+ return hasResponseIdentity || ambiguous ? undefined : candidate;
+};
+
const hydrateMessageConversationId = (message: TMessage, conversationId: string): TMessage =>
shouldHydrateMessage(message) ? { ...message, conversationId } : message;
@@ -2086,6 +2118,9 @@ export default function useResumableSSE(
startedAsNewConvo: runEndTarget.startedAsNewConvo,
endedAt: Date.now(),
generationCreatedAt,
+ ...(data.responseMessage?.messageId != null && {
+ responseMessageId: data.responseMessage.messageId,
+ }),
});
// Clear handler maps on stream completion to prevent memory leaks
clearStepMaps();
@@ -2965,11 +3000,23 @@ export default function useResumableSSE(
} else if (event.terminalStatus === 'error') {
reconciliationOutcome = 'error';
}
+ const reconciledResponseMessageId =
+ reconciliationOutcome === 'completed'
+ ? completedResponseMessageId(
+ persistedMessages,
+ userMessage?.messageId,
+ status?.resumeState?.responseMessageId ??
+ currentSubmission.initialResponse?.messageId,
+ )
+ : undefined;
setRunEnd({
conversationId: reconciliationConvoId,
outcome: reconciliationOutcome,
endedAt: Date.now(),
generationCreatedAt: status?.createdAt ?? generationCreatedAt,
+ ...(reconciledResponseMessageId != null && {
+ responseMessageId: reconciledResponseMessageId,
+ }),
});
setSubmission(null);
setStreamId(null);
@@ -3657,11 +3704,23 @@ export default function useResumableSSE(
} else if (status.status === 'aborted') {
recoveryOutcome = 'aborted';
}
+ const recoveredResponseMessageId =
+ recoveryOutcome === 'completed'
+ ? completedResponseMessageId(
+ persistedMessages,
+ userMessage?.messageId,
+ status?.resumeState?.responseMessageId ??
+ currentSubmission.initialResponse?.messageId,
+ )
+ : undefined;
setRunEnd({
conversationId: recoveryConvoId,
outcome: recoveryOutcome,
endedAt: Date.now(),
generationCreatedAt: status.createdAt ?? generationCreatedAt,
+ ...(recoveredResponseMessageId != null && {
+ responseMessageId: recoveredResponseMessageId,
+ }),
});
setSubmission(null);
setStreamId(null);
diff --git a/client/src/hooks/SSE/useResumeOnLoad.ts b/client/src/hooks/SSE/useResumeOnLoad.ts
index 9edb747fa6..68e9bb6055 100644
--- a/client/src/hooks/SSE/useResumeOnLoad.ts
+++ b/client/src/hooks/SSE/useResumeOnLoad.ts
@@ -37,7 +37,9 @@ import {
} from '~/data-provider/SSE/protocol';
import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/state';
import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
+import { agentQueuedTurnsQueryKey } from '~/data-provider/SSE/queuedTurns';
import useSteerConvert from '~/hooks/Chat/useSteerConvert';
+import { revealedQueuedTurnFamily } from '~/store/steer';
import { useFileMapContext } from '~/Providers';
import store from '~/store';
@@ -762,6 +764,17 @@ export default function useResumeOnLoad(
* and finished inside a poll gap, its turns are on the server and
* nowhere else; one refetch is the whole repair, and marking an
* off-screen conversation stale costs nothing until it is opened. */
+ const revealFamily = revealedQueuedTurnFamily(owedConversationId);
+ const pendingReveal = jotaiStore.get(revealFamily);
+ if (
+ pendingReveal != null &&
+ Date.parse(pendingReveal.revealedAt) <= latch.quietSince! &&
+ !isQueuedTurnSuccessorOwed(
+ queryClient.getQueryData(agentQueuedTurnsQueryKey(owedConversationId)),
+ )
+ ) {
+ jotaiStore.set(revealFamily, null);
+ }
queryClient.invalidateQueries({ queryKey: [QueryKeys.messages, owedConversationId] });
}, remaining),
);
@@ -783,7 +796,7 @@ export default function useResumeOnLoad(
clearTimeout(timer);
}
};
- }, [owedSuccessors, owedIsReporting, conversationId, queryClient]);
+ }, [owedSuccessors, owedIsReporting, conversationId, queryClient, jotaiStore]);
const shouldCheck =
resumableEnabled &&
@@ -905,6 +918,30 @@ export default function useResumeOnLoad(
if (!streamStatus.active || !streamStatus.streamId) {
console.log('[ResumeOnLoad] No active job to resume for:', conversationId);
+ const revealFamily = revealedQueuedTurnFamily(conversationId);
+ const pendingReveal = jotaiStore.get(revealFamily);
+ /** A remounted pane may have missed attachment and the quiet-window
+ * timer. An expired job has no epoch; require a fresh inactive read
+ * after restored history before retiring its surviving handoff guard. */
+ const historyUpdatedAt = queryClient.getQueryState([
+ QueryKeys.messages,
+ conversationId,
+ ])?.dataUpdatedAt;
+ if (
+ pendingReveal != null &&
+ streamStatus.active === false &&
+ streamStatus.createdAt == null &&
+ historyUpdatedAt != null &&
+ streamStatusUpdatedAt >= historyUpdatedAt &&
+ streamStatusUpdatedAt > Date.parse(pendingReveal.revealedAt) &&
+ !isQueuedTurnSuccessorOwed(queuedTurnReceipts) &&
+ (getMessages() ?? []).some(
+ (message) => message.parentMessageId === pendingReveal.parentMessageId,
+ )
+ ) {
+ jotaiStore.set(revealFamily, null);
+ }
+
// A terminal drain may have parked acknowledged steers no subscriber
// received (tab closed / reload racing the final event) — the status
// claim returns them exactly once; restore as queued follow-up chips.
@@ -1035,6 +1072,8 @@ export default function useResumeOnLoad(
isFetching,
streamStatus,
streamStatusUpdatedAt,
+ queuedTurnReceipts,
+ queryClient,
getMessages,
setSubmission,
setSubmissionStart,
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 6ca1ba26a7..446501702b 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -1996,6 +1996,7 @@
"com_ui_queued_quote_count": "{{0}} quoted excerpts included with this message",
"com_ui_queued_turn_failed": "Queued message failed",
"com_ui_queued_turn_reconciliation_required": "Awaiting reconciliation",
+ "com_ui_queued_turn_starting": "Starting as the next turn",
"com_ui_quote_selections": "{{0}} selections",
"com_ui_quotes_queued": "Quotes added for your next message",
"com_ui_ran_n_actions": "Ran {{0}} actions",
diff --git a/client/src/store/families.ts b/client/src/store/families.ts
index 3bfb45ec9d..b66a555291 100644
--- a/client/src/store/families.ts
+++ b/client/src/store/families.ts
@@ -510,6 +510,8 @@ export type RunEnd = {
endedAt: number;
/** Exact terminal epoch whose idle transition may release one queued start. */
generationCreatedAt?: number;
+ /** The completed run's response, which a revealed queued follow-up parents to. */
+ responseMessageId?: string;
/** Armed "Interrupt & send" flag traveling with a PARKED signal, so
* another run on the same pane can neither consume nor clear it. */
interruptArmed?: boolean;
diff --git a/client/src/store/steer.ts b/client/src/store/steer.ts
index d0c152f483..87a1298949 100644
--- a/client/src/store/steer.ts
+++ b/client/src/store/steer.ts
@@ -1,5 +1,6 @@
import { atom } from 'jotai';
import { atomFamily } from 'jotai/utils';
+import type { TMessage } from 'librechat-data-provider';
/**
* Measured pixel height of the in-flight steer overlay for a conversation.
@@ -20,3 +21,26 @@ export const steerOverlayHeightFamily = atomFamily((_conversationId: string) =>
* and the chip-derived check cannot see an arm until its response lands.
*/
export const escalatingSteerFamily = atomFamily((_conversationId: string) => atom<boolean>(false));
+
+/** A server-owned follow-up and its admission handoff, keyed by conversation.
+ * The drawing never enters history. Its guard survives the drawing until a
+ * successor generation owns the pane or terminal evidence settles the turn. */
+export type RevealedQueuedTurn = {
+ clientRequestId: string;
+ /** The drawing follows this response only while history has no successor. */
+ parentMessageId: string;
+ /** Completion boundary, advanced as later queued turns are admitted. */
+ generationCreatedAt?: number;
+ /** Immutable queue lineage, independent of the display/completion boundary. */
+ queueParentMessageId?: string;
+ queuePredecessorCreatedAt?: number;
+ text: string;
+ files?: TMessage['files'];
+ quotes?: string[];
+ manualSkills?: string[];
+ revealedAt: string;
+};
+
+export const revealedQueuedTurnFamily = atomFamily((_conversationId: string) =>
+ atom<RevealedQueuedTurn | null>(null),
+);
diff --git a/e2e/specs/mock/queued-reveal.spec.ts b/e2e/specs/mock/queued-reveal.spec.ts
new file mode 100644
index 0000000000..ce6e07dda5
--- /dev/null
+++ b/e2e/specs/mock/queued-reveal.spec.ts
@@ -0,0 +1,217 @@
+import { expect, test } from '@playwright/test';
+import type { Page, Route } from '@playwright/test';
+import type { AgentDetail } from './agents.helpers';
+import { cleanupAgent, openAgentBuilder, uniqueAgentName } from './agents.helpers';
+import {
+ MOCK_ENDPOINTS,
+ MOCK_REPLY_TEXT,
+ NEW_CHAT_PATH,
+ messagesView,
+ replyPrompt,
+ replyText,
+ getAccessToken,
+ requestJson,
+ sendMessage,
+} from './helpers';
+
+/** Last chunk streamed by the fake model's slow replies (160 chunks, 0-indexed). */
+const SLOW_REPLY_LAST_CHUNK = 'chunk-159';
+
+const uniqueLabel = (prefix: string) =>
+ `${prefix}-${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
+
+const messageInput = (page: Page) => page.getByRole('textbox', { name: 'Message input' });
+const duringRunSendButton = (page: Page) => page.getByTestId('during-run-send-button');
+const queuedRows = (page: Page) => page.getByTestId('queued-message-row');
+const messageTurns = (page: Page) => messagesView(page).locator('.message-render');
+
+const RECEIPTS_ROUTE = /\/api\/agents\/chat\/queued-turns\?/;
+const STATUS_ROUTE = /\/api\/agents\/chat\/status\//;
+
+type ReceiptsBody = { queuedTurns?: Array<{ status?: string }> };
+type StatusBody = { active?: boolean; resumeState?: { userMessage?: { text?: string } } };
+
+/**
+ * Reproduces production timing inside the mock lane. Here the backend admits a
+ * queued turn within milliseconds, so the predecessor's terminal reconcile
+ * already sees the successor in stream status and hands off to it at once. A
+ * real deployment admits later, and the client then learns of the successor
+ * only through the receipt projection and the status it re-arms. While held
+ * back, the receipts stay frozen at their pre-admission snapshot and a status
+ * that describes the successor reads as inactive, so the next user turn can
+ * only come from the completion event itself. Every other request, including
+ * the predecessor's own terminal status, passes through untouched.
+ */
+function holdBackSuccessor(page: Page, successorText: string) {
+ let holding = false;
+ let frozenReceipts: ReceiptsBody | null = null;
+ const receipts = async (route: Route) => {
+ const response = await route.fetch();
+ if (response.status() !== 200) {
+ return route.fulfill({ response });
+ }
+ const body = (await response.json()) as ReceiptsBody;
+ if (!holding) {
+ frozenReceipts = body;
+ return route.fulfill({ response, json: body });
+ }
+ return route.fulfill({ response, json: frozenReceipts ?? body });
+ };
+ const status = async (route: Route) => {
+ const response = await route.fetch();
+ if (!holding || response.status() !== 200) {
+ return route.fulfill({ response });
+ }
+ const body = (await response.json()) as StatusBody;
+ const describesSuccessor =
+ body.active === true && body.resumeState?.userMessage?.text === successorText;
+ return route.fulfill({
+ response,
+ json: describesSuccessor ? { active: false } : body,
+ });
+ };
+ return {
+ arm: async () => {
+ await page.route(RECEIPTS_ROUTE, receipts);
+ await page.route(STATUS_ROUTE, status);
+ },
+ hold: () => {
+ holding = true;
+ },
+ release: async () => {
+ holding = false;
+ await page.unroute(RECEIPTS_ROUTE, receipts);
+ await page.unroute(STATUS_ROUTE, status);
+ },
+ };
+}
+
+async function createAgent(page: Page, token: string, name: string): Promise<AgentDetail> {
+ return requestJson<AgentDetail>(page, {
+ path: '/api/agents',
+ token,
+ method: 'POST',
+ body: {
+ name,
+ description: 'Playwright verification of the queued follow-up reveal.',
+ instructions: 'Follow the deterministic end-to-end request exactly.',
+ provider: MOCK_ENDPOINTS[0].label,
+ model: MOCK_ENDPOINTS[0].model,
+ },
+ });
+}
+
+async function selectAgent(page: Page, name: string): Promise<void> {
+ const form = await openAgentBuilder(page);
+ await form.getByRole('combobox', { name: 'Agent', exact: true }).click();
+ await page.getByRole('option', { name }).click();
+ await expect(form.getByLabel('Agent name')).toHaveValue(name);
+ await form.getByRole('button', { name: 'Select Agent' }).click();
+}
+
+async function establishConversation(page: Page, label: string) {
+ const setup = await sendMessage(page, replyPrompt(label));
+ expect(setup.ok()).toBeTruthy();
+ await expect(messagesView(page).getByText(replyText(label))).toBeVisible({ timeout: 30000 });
+ await expect(page).toHaveURL(/\/c\/[0-9a-fA-F-]{36}$/, { timeout: 15000 });
+}
+
+async function typeDuringRun(page: Page, text: string) {
+ const input = messageInput(page);
+ await input.click();
+ await input.fill(text);
+ await expect(duringRunSendButton(page)).toBeVisible({ timeout: 5000 });
+}
+
+test.describe('server-queued follow-up reveal', () => {
+ test('shows the queued follow-up as the next user turn the moment the run completes', async ({
+ page,
+ }) => {
+ test.setTimeout(120000);
+ const label = uniqueLabel('queue-reveal');
+ const queueText = `Queued reveal ${label}`;
+ let agentId: string | undefined;
+
+ try {
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ const token = await getAccessToken(page);
+ const agent = await createAgent(page, token, uniqueAgentName('E2E Queue Reveal Agent'));
+ agentId = agent.id;
+ await selectAgent(page, agent.name);
+ await establishConversation(page, `queue-reveal-setup-${label}`);
+
+ const successor = holdBackSuccessor(page, queueText);
+ await successor.arm();
+
+ const run = await sendMessage(page, `E2E_SLOW_REPLY:${label}`);
+ expect(run.ok()).toBeTruthy();
+
+ await typeDuringRun(page, queueText);
+ /** Agent conversations queue on the server: the row is only eligible for
+ * the reveal once the durable enqueue has been acknowledged. */
+ const [enqueued] = await Promise.all([
+ page.waitForResponse(
+ (response) =>
+ response.request().method() === 'POST' &&
+ new URL(response.url()).pathname === '/api/agents/chat/queued-turns',
+ { timeout: 10000 },
+ ),
+ messageInput(page).press('ControlOrMeta+Enter'),
+ ]);
+ expect(enqueued.ok()).toBeTruthy();
+ const row = queuedRows(page).filter({ hasText: queueText });
+ await expect(row).toBeVisible({ timeout: 10000 });
+ successor.hold();
+
+ const predecessor = messageTurns(page).nth(3);
+ await expect(predecessor).toContainText(SLOW_REPLY_LAST_CHUNK, { timeout: 60000 });
+
+ const queuedTurn = messageTurns(page).nth(4);
+ await expect(queuedTurn).toContainText(queueText, { timeout: 5000 });
+ await expect(queuedTurn.locator('.user-turn')).toBeVisible();
+ /** The chip stays only as a way to retract the turn until it is admitted. */
+ await expect(row).toContainText('Starting as the next turn');
+ await expect(row.getByRole('button', { name: 'Send now' })).toHaveCount(0);
+ await expect(row.getByRole('button', { name: 'Remove message' })).toBeVisible();
+
+ const nextQueueText = `Queued during handoff ${label}`;
+ await messageInput(page).fill(nextQueueText);
+ const [handoffEnqueue] = await Promise.all([
+ page.waitForResponse(
+ (response) =>
+ response.request().method() === 'POST' &&
+ new URL(response.url()).pathname === '/api/agents/chat/queued-turns',
+ ),
+ messageInput(page).press('Enter'),
+ ]);
+ expect(handoffEnqueue.ok()).toBeTruthy();
+ const originalQueue = enqueued.request().postDataJSON();
+ expect(handoffEnqueue.request().postDataJSON()).toMatchObject({
+ parentMessageId: originalQueue.parentMessageId,
+ expectedPredecessorCreatedAt: originalQueue.expectedPredecessorCreatedAt,
+ });
+ await successor.release();
+
+ /** Once the successor attaches, the shown row is the server's own turn:
+ * exactly one copy of the text, followed by its reply. */
+ await expect(messageTurns(page)).toHaveCount(8, { timeout: 30000 });
+ await expect(messageTurns(page).filter({ hasText: queueText })).toHaveCount(1);
+ const followupReply = messageTurns(page).nth(5);
+ await expect(followupReply).toContainText(MOCK_REPLY_TEXT, { timeout: 30000 });
+ await expect(followupReply.locator('.agent-turn')).toBeVisible();
+ await expect(queuedRows(page)).toHaveCount(0);
+
+ /** The turn ran and was persisted, not merely shown. */
+ const conversationPath = new URL(page.url()).pathname;
+ await page.reload({ waitUntil: 'domcontentloaded' });
+ await expect(page).toHaveURL(conversationPath);
+ await expect(messageTurns(page)).toHaveCount(8, { timeout: 30000 });
+ await expect(messageTurns(page).nth(4)).toContainText(queueText);
+ await expect(messageTurns(page).nth(5)).toContainText(MOCK_REPLY_TEXT);
+ await expect(messageTurns(page).nth(6)).toContainText(nextQueueText);
+ await expect(messageTurns(page).nth(7)).toContainText(MOCK_REPLY_TEXT);
+ } finally {
+ await cleanupAgent(page, agentId);
+ }
+ });
+});