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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🚉 fix: Keep Queue Controls with the Starting Turn (#16268)
lia-by-librechat[bot]e4fe31623e0b
diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsxindex bb8ffcb351..a7bd0361f1 100644--- a/client/src/components/Chat/ChatView.tsx+++ b/client/src/components/Chat/ChatView.tsx@@ -18,6 +18,7 @@ import {useLocalize,} from '~/hooks';import { ChatContext, AddedChatContext, ChatFormProvider, useFileMapContext } from '~/Providers';+import { QueuedTurnPortalProvider } from './Steering/QueuedTurnPortal';import ApprovalProvider from './Messages/Content/ApprovalContext';import ConversationStarters from './Input/ConversationStarters';import { pendingApprovalActionFamily } from './approval/state';@@ -161,19 +162,20 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProje<ChatContext.Provider value={chatHelpers}><AddedChatContext.Provider value={addedChatHelpers}><ApprovalProvider pendingAction={pendingAction}>- <Presentation>- <TraceSurface conversationId={conversationId}>- <h1 className="sr-only">{pageHeading}</h1>- <Header- parentConversationId={parentConversationId}- readOnly={isSubagentThreadReadOnly}- />- <>- <div- className={cn(- 'flex flex-col',- isLandingPage- ? /* The gutter is reserved once per state, wherever the+ <QueuedTurnPortalProvider>+ <Presentation>+ <TraceSurface conversationId={conversationId}>+ <h1 className="sr-only">{pageHeading}</h1>+ <Header+ parentConversationId={parentConversationId}+ readOnly={isSubagentThreadReadOnly}+ />+ <>+ <div+ className={cn(+ 'flex flex-col',+ isLandingPage+ ? /* The gutter is reserved once per state, wherever thecentring happens. A conversation centres the composerinside the band below, against a message column thatholds the scrollbar band back; the landing page centres@@ -181,51 +183,52 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProjetogether, so it holds the same band back here. Withoutit the composer lands 4px right of where a conversationputs it and slides sideways on the way in. */- 'scrollbar-gutter-spacer flex-1 items-center justify-end sm:justify-center'- : 'h-full overflow-y-auto',- )}- >- {content}- {/* Named + opaque so a view transition (the ask_user_question+ 'scrollbar-gutter-spacer flex-1 items-center justify-end sm:justify-center'+ : 'h-full overflow-y-auto',+ )}+ >+ {content}+ {/* Named + opaque so a view transition (the ask_user_questionpopover ⇄ chat-card morph) paints the whole composer bandover the travelling card instead of letting it showthrough below the composer. The background matches thepage, so normal rendering is unchanged. */}- <div- className={cn(- 'w-full bg-presentation [view-transition-name:chat-form]',- !isLandingPage && 'scrollbar-gutter-spacer',- isLandingPage && 'max-w-3xl transition-all duration-200 xl:max-w-4xl',- )}- >- {isLandingPage && <ConversationStarters />}- {isSubagentThreadReadOnly ? (- <div- className="mx-auto w-full max-w-3xl px-4 py-3 text-center text-sm text-text-secondary xl:max-w-4xl"- role="note"- >- {localize('com_ui_subagent_thread_read_only')}- </div>- ) : (- <ChatForm- index={index}- placeholder={chatFormPlaceholder}- project={isProjectLandingPage ? project : undefined}- isLandingPage={isLandingPage}- footerBelow={footerBelow}- centerFormOnLanding={centerFormOnLanding}- />- )}- {/* The generic disclaimer is the welcome screen's; a+ <div+ className={cn(+ 'w-full bg-presentation [view-transition-name:chat-form]',+ !isLandingPage && 'scrollbar-gutter-spacer',+ isLandingPage && 'max-w-3xl transition-all duration-200 xl:max-w-4xl',+ )}+ >+ {isLandingPage && <ConversationStarters />}+ {isSubagentThreadReadOnly ? (+ <div+ className="mx-auto w-full max-w-3xl px-4 py-3 text-center text-sm text-text-secondary xl:max-w-4xl"+ role="note"+ >+ {localize('com_ui_subagent_thread_read_only')}+ </div>+ ) : (+ <ChatForm+ index={index}+ placeholder={chatFormPlaceholder}+ project={isProjectLandingPage ? project : undefined}+ isLandingPage={isLandingPage}+ footerBelow={footerBelow}+ centerFormOnLanding={centerFormOnLanding}+ />+ )}+ {/* The generic disclaimer is the welcome screen's; adeployment's own footer, privacy policy and termsstay with the conversation that always showed them. */}- {!isLandingPage && configuredFooter && <Footer configuredOnly />}+ {!isLandingPage && configuredFooter && <Footer configuredOnly />}+ </div></div>- </div>- {isLandingPage && <Footer />}- </>- </TraceSurface>- </Presentation>+ {isLandingPage && <Footer />}+ </>+ </TraceSurface>+ </Presentation>+ </QueuedTurnPortalProvider></ApprovalProvider></AddedChatContext.Provider></ChatContext.Provider>diff --git a/client/src/components/Chat/Input/PendingSteerChips.tsx b/client/src/components/Chat/Input/PendingSteerChips.tsxindex 2467a7e588..b18f527069 100644--- a/client/src/components/Chat/Input/PendingSteerChips.tsx+++ b/client/src/components/Chat/Input/PendingSteerChips.tsx@@ -1,6 +1,7 @@import { memo, useMemo, useRef, useState, useCallback } from 'react';import { useAtomValue } from 'jotai';import { useRecoilValue } from 'recoil';+import { createPortal } from 'react-dom';import { TooltipAnchor, useToastContext } from '@librechat/client';import {X,@@ -15,6 +16,7 @@ import {TriangleAlert,} from 'lucide-react';import type { TMessage } from 'librechat-data-provider';+import type { ReactNode } from 'react';import type { SteeringControls, QueuedMessageContext } from '~/hooks/Chat/useSteering';import type { PendingSteer, QueuedMessage } from '~/store/families';import type { RestoreToComposer } from './InFlightSteers';@@ -27,6 +29,7 @@ import {useDefaultToggleEntry,useInterruptToggleEntry,} from './SteerMenu';+import { useQueuedTurnPortal } from '~/components/Chat/Steering/QueuedTurnPortal';import { escalatingSteerFamily, revealedQueuedTurnFamily } from '~/store/steer';import { QUEUE_ICON, STEER_ICON } from '~/components/Chat/Steering/identity';import { useLocalize } from '~/hooks';@@ -109,7 +112,10 @@ function QueuedRow({steering,conversationId,interruptPending,- revealed,+ inTurn = false,+ starting = false,+ actionPending,+ afterDiscard,onEditToComposer,onRestoreToComposer,}: {@@ -117,8 +123,11 @@ function QueuedRow({steering: SteeringControls;conversationId: string;interruptPending: boolean;- /** Shown as the next user turn already; only removal remains meaningful. */- revealed?: boolean;+ /** A visible pending turn takes the place of this queue row. */+ inTurn?: boolean;+ starting?: boolean;+ actionPending: boolean;+ afterDiscard: (message: QueuedMessage, action: () => boolean) => void;onEditToComposer: (text: string,files?: TMessage['files'],@@ -151,92 +160,102 @@ function QueuedRow({message.server == null ||message.server.status === 'rejected' ||(message.server.id != null && message.server.status === 'queued');- const actionPendingRef = useRef(false);- const [actionPending, setActionPending] = useState(false);- /** A recovered item has a replayable parked source. Edit/remove must first- * cancel that source by receipt; local-only rows settle synchronously through- * the same control. The ref closes the pre-render double-click window. */- const afterDiscard = useCallback(- (action: () => boolean) => {- if (actionPendingRef.current) {- return;- }- actionPendingRef.current = true;- setActionPending(true);- void (async () => {- let discarded = false;- try {- discarded = await steering.discardQueued(message);- } catch {- // The steering hook reports request failures and leaves the row in- // place. Keep this guard for test/custom control implementations.- }- if (!discarded) {- actionPendingRef.current = false;- setActionPending(false);- return;- }- if (!action()) {- actionPendingRef.current = false;- setActionPending(false);- }- })();- },- [message, steering],- );// A recovered item is consumed atomically only when it starts a normal// generation. Re-steering it would leave or duplicate the parked source;// Edit/remove are safe because `afterDiscard` tombstones that source first.const canSteerNow = steering.duringRunActive && steering.canSteer && !isRecovered;const showPrimary =- revealed !== true &&+ !starting &&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 =- revealed !== true &&+ !starting &&!isRecovered &&(steering.pausedOnApproval || (steering.duringRunActive && steering.canSteer));+ const edit = () => {+ const context = { quotes: message.quotes, manualSkills: message.manualSkills };+ if (!requiresDiscard) {+ steering.removeQueued(message.id);+ onEditToComposer(message.text, message.files, context);+ return;+ }+ afterDiscard(message, () => {+ const restored = onRestoreToComposer(message.text, message.files, context, conversationId);+ if (!restored) {+ showToast({ message: localize('com_ui_steer_edit_queued'), status: 'info' });+ return false;+ }+ steering.removeQueued(message.id);+ return true;+ });+ };+ const remove = () => {+ if (isUnconfirmed) {+ steering.removeQueued(message.id);+ return;+ }+ const finish = () => {+ onRestoreToComposer(+ message.text,+ message.files,+ { quotes: message.quotes, manualSkills: message.manualSkills },+ conversationId,+ );+ steering.removeQueued(message.id);+ return true;+ };+ if (!requiresDiscard) {+ finish();+ return;+ }+ afterDiscard(message, finish);+ };+ const removeDisabled =+ actionPending ||+ (!serverActionable &&+ !isUnconfirmed &&+ !(message.server?.id != null && message.server.status === 'claimed'));+ if (inTurn) {+ const actionClass = cn(ICON_BTN_CLASS, 'disabled:cursor-not-allowed disabled:opacity-50');+ return (+ <>+ {message.server?.status === 'queued' && (+ <button+ type="button"+ className={actionClass}+ aria-label={localize('com_ui_edit_message')}+ disabled={actionPending}+ onClick={edit}+ >+ <Pencil className="h-4 w-4" aria-hidden="true" />+ </button>+ )}+ {!removeDisabled || actionPending ? (+ <button+ type="button"+ className={actionClass}+ aria-label={localize('com_ui_remove_queued')}+ disabled={removeDisabled}+ onClick={remove}+ >+ <Trash2 className="h-4 w-4" aria-hidden="true" />+ </button>+ ) : null}+ </>+ );+ }+const entries: MenuEntry[] = [{key: 'edit',label: localize('com_ui_edit_message'),icon: <Pencil className="h-4 w-4" aria-hidden="true" />,disabled: actionPending || !serverActionable,- onClick: () => {- const context = {- quotes: message.quotes,- manualSkills: message.manualSkills,- };- if (!requiresDiscard) {- steering.removeQueued(message.id);- onEditToComposer(message.text, message.files, {- quotes: message.quotes,- manualSkills: message.manualSkills,- });- return;- }- afterDiscard(() => {- const restored = onRestoreToComposer(- message.text,- message.files,- context,- conversationId,- );- if (!restored) {- showToast({- message: localize('com_ui_steer_edit_queued'),- status: 'info',- });- return false;- }- steering.removeQueued(message.id);- return true;- });- },+ onClick: edit,},];const preferences: MenuEntry[] = [toggleEntry, interruptToggle];@@ -263,11 +282,6 @@ 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 && (<buttontype="button"@@ -303,47 +317,17 @@ function QueuedRow({aria-label={localize(isUnconfirmed ? 'com_ui_dismiss_unconfirmed_delivery' : 'com_ui_remove_queued',)}- disabled={- actionPending ||- (!serverActionable &&- !isUnconfirmed &&- !(message.server?.id != null && message.server.status === 'claimed'))- }- onClick={() => {- if (isUnconfirmed) {- steering.removeQueued(message.id);- return;- }- const remove = () => {- /* Same safety net as the in-flight cancel: once removal is safely- * settled, return the words to the composer when it is free (the- * gated restore refuses rather than clobber a draft). */- onRestoreToComposer(- message.text,- message.files,- { quotes: message.quotes, manualSkills: message.manualSkills },- conversationId,- );- steering.removeQueued(message.id);- return true;- };- if (!requiresDiscard) {- remove();- return;- }- afterDiscard(remove);- }}+ disabled={removeDisabled}+ onClick={remove}className={ICON_BTN_CLASS}><Trash2 className="h-4 w-4" aria-hidden="true" /></button>- {revealed !== true && (- <RowMenu- label={localize('com_ui_more_options')}- entries={entries}- preferences={preferences}- />- )}+ <RowMenu+ label={localize('com_ui_more_options')}+ entries={entries}+ preferences={preferences}+ /></div>);}@@ -491,9 +475,31 @@ 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 portal = useQueuedTurnPortal();+ const actionLocks = useRef(new Set<string>());+ const [pendingActions, setPendingActions] = useState<ReadonlySet<string>>(new Set());+ /** The lock lives with the composer, not the row: reparenting an action+ * during a cancellation cannot open a second request window. */+ const afterDiscard = useCallback(+ (message: QueuedMessage, action: () => boolean) => {+ const key = `${steering.queueKey}\u0000${message.id}`;+ if (actionLocks.current.has(key)) return;+ actionLocks.current.add(key);+ setPendingActions(new Set(actionLocks.current));+ void (async () => {+ try {+ if (await steering.discardQueued(message)) action();+ } catch {+ // The steering hook reports failures; leave the row available for retry.+ } finally {+ actionLocks.current.delete(key);+ setPendingActions(new Set(actionLocks.current));+ }+ })();+ },+ [steering],+ );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@@ -505,43 +511,68 @@ function PendingSteerChips({[escalating, steers],);- if (failedSteers.length === 0 && queued.length === 0) {+ const queuedRows: ReactNode[] = [];+ const portaledActions: ReactNode[] = [];+ const target = portal?.target;+ for (const message of queued) {+ const starting =+ revealed != null &&+ message.clientRequestId != null &&+ revealed.clientRequestId === message.clientRequestId;+ const inTurn =+ starting &&+ target != null &&+ target.conversationId === conversationId &&+ target.clientRequestId === message.clientRequestId;+ const actionKey = `${steering.queueKey}\u0000${message.id}`;+ const row = (+ <QueuedRow+ key={message.id}+ message={message}+ steering={steering}+ conversationId={conversationId}+ interruptPending={interruptPending}+ starting={starting}+ inTurn={inTurn}+ actionPending={pendingActions.has(actionKey)}+ afterDiscard={afterDiscard}+ onEditToComposer={onEditToComposer}+ onRestoreToComposer={onRestoreToComposer}+ />+ );+ if (inTurn && target != null) {+ portaledActions.push(createPortal(row, target.element, message.id));+ } else {+ queuedRows.push(row);+ }+ }+ if (failedSteers.length === 0 && queuedRows.length === 0 && portaledActions.length === 0) {return null;}return (- <div className="flex flex-col gap-1.5 px-2 pt-2" data-testid="pending-steer-chips">- <div- className="flex flex-col gap-1.5"- role="list"- aria-label={localize('com_ui_queued_messages')}- >- {failedSteers.map((steer) => (- <FailedSteerRow- key={steer.steerId}- steer={steer}- steering={steering}- onEditToComposer={onEditToComposer}- />- ))}- {queued.map((message) => (- <QueuedRow- key={message.id}- message={message}- steering={steering}- conversationId={conversationId}- interruptPending={interruptPending}- revealed={- revealed != null &&- message.clientRequestId != null &&- revealed.clientRequestId === message.clientRequestId- }- onEditToComposer={onEditToComposer}- onRestoreToComposer={onRestoreToComposer}- />- ))}- </div>- </div>+ <>+ {(failedSteers.length > 0 || queuedRows.length > 0) && (+ <div className="flex flex-col gap-1.5 px-2 pt-2" data-testid="pending-steer-chips">+ <div+ className="flex flex-col gap-1.5"+ role="list"+ aria-label={localize('com_ui_queued_messages')}+ >+ {failedSteers.map((steer) => (+ <FailedSteerRow+ key={steer.steerId}+ steer={steer}+ steering={steering}+ onEditToComposer={onEditToComposer}+ />+ ))}+ {queuedRows}+ </div>+ </div>+ )}+ {portaledActions}+ </>);}diff --git a/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsx b/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsxindex 76bb6bfa34..d7cfa83430 100644--- a/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsx+++ b/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsx@@ -731,7 +731,7 @@ describe('PendingSteerChips — revealed queued turn', () => {server: { id: `server-${clientRequestId}`, status: 'queued', revision: 1 },});- it('reduces the row shown as the next turn to its remove action', () => {+ it('keeps an ordinary queue row when no matching pending message is visible', () => {getDefaultStore().set(revealedFamily(), {clientRequestId: 'req-1',parentMessageId: 'response-1',@@ -744,8 +744,10 @@ describe('PendingSteerChips — revealed queued turn', () => {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(rows[0]).not.toHaveTextContent('com_ui_queued_turn_starting');+ expect(+ within(rows[0]).getByRole('button', { name: 'com_ui_more_options' }),+ ).toBeInTheDocument();expect(within(rows[0]).getByRole('button', { name: /com_ui_remove/ })).toBeInTheDocument();expect(rows[1]).not.toHaveTextContent('com_ui_queued_turn_starting');expect(diff --git a/client/src/components/Chat/Input/__tests__/QueuedTurnPortal.spec.tsx b/client/src/components/Chat/Input/__tests__/QueuedTurnPortal.spec.tsxnew file mode 100644index 0000000000..2fa54aaa93--- /dev/null+++ b/client/src/components/Chat/Input/__tests__/QueuedTurnPortal.spec.tsx@@ -0,0 +1,250 @@+import React from 'react';+import { RecoilRoot, useSetRecoilState } from 'recoil';+import { EModelEndpoint } from 'librechat-data-provider';+import { Provider as JotaiProvider, createStore } from 'jotai';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import type { TConversation, TMessage } from 'librechat-data-provider';+import type { SteeringControls } from '~/hooks/Chat/useSteering';+import type { RevealedQueuedTurn } from '~/store/steer';+import type { QueuedMessage } from '~/store/families';+import { QueuedTurnPortalProvider } from '~/components/Chat/Steering/QueuedTurnPortal';+import PendingTurn from '~/components/Chat/Messages/PendingTurn';+import { revealedQueuedTurnFamily } from '~/store/steer';+import PendingSteerChips from '../PendingSteerChips';+import { ChatContext } from '~/Providers';+import store from '~/store';++const CONVO_ID = 'convo-queued-turn';+const RESPONSE_ID = 'completed-response';+const removeQueued = jest.fn();+const discardQueued = jest.fn(async (_message: QueuedMessage) => true);+const restoreToComposer = jest.fn(() => true);+const editToComposer = jest.fn();+const sendQueuedNow = jest.fn();+const mockShowToast = jest.fn();++jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key }));+jest.mock('~/hooks/AuthContext', () => ({+ useAuthContext: () => ({ user: { name: 'Danny' } }),+}));+jest.mock('~/components/Chat/Messages/MessageIcon', () => ({+ __esModule: true,+ default: () => <span data-testid="message-icon" />,+}));+jest.mock('~/components/Chat/Messages/Content/Container', () => ({+ __esModule: true,+ default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+}));+jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({+ __esModule: true,+ default: ({ content }: { content: string }) => <span>{content}</span>,+}));+jest.mock('@librechat/client', () => {+ const { createSteerMorphIconMock } = jest.requireActual('~/../test/mockMorphIcon');+ return {+ useToastContext: () => ({ showToast: mockShowToast }),+ TooltipAnchor: jest.requireActual('@librechat/client').TooltipAnchor,+ MorphIcon: createSteerMorphIconMock(),+ };+});++const conversation = {+ conversationId: CONVO_ID,+ endpoint: EModelEndpoint.agents,+ model: 'gpt-x',+} as TConversation;++const serverRow = (requestId: string, status: 'queued' | 'claimed' = 'queued'): QueuedMessage => ({+ id: `row-${requestId}`,+ text: `queued ${requestId}`,+ createdAt: 1,+ clientRequestId: requestId,+ server: { id: `server-${requestId}`, status, revision: 1 },+});++const reveal = (requestId: string): RevealedQueuedTurn => ({+ clientRequestId: requestId,+ parentMessageId: RESPONSE_ID,+ text: `queued ${requestId}`,+ revealedAt: '2026-09-14T00:00:00.000Z',+});++function QueueState({ onSet }: { onSet: (setter: (id: string) => void) => void }) {+ const setQueue = useSetRecoilState(store.queuedMessagesByConvoId(CONVO_ID));+ onSet((id) => setQueue((items) => items.filter((item) => item.id !== id)));+ return null;+}++function renderQueue(rows: QueuedMessage[], latestMessageId = RESPONSE_ID) {+ const jotaiStore = createStore();+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const steering = {+ queueKey: CONVO_ID,+ defaultAction: 'steer',+ duringRunActive: false,+ canSendQueuedNow: true,+ canSteer: false,+ pausedOnApproval: false,+ removeQueued,+ discardQueued,+ sendQueuedNow,+ setDefaultAction: jest.fn(),+ } as unknown as SteeringControls;+ let setQueueById: (id: string) => void = () => undefined;+ removeQueued.mockImplementation((id: string) => setQueueById(id));+ const view = (tail: string, messages?: TMessage[]) => (+ <QueryClientProvider client={queryClient}>+ <RecoilRoot initializeState={({ set }) => set(store.queuedMessagesByConvoId(CONVO_ID), rows)}>+ <JotaiProvider store={jotaiStore}>+ <ChatContext.Provider+ value={+ { conversation, latestMessageId: tail, index: 0 } as React.ContextType<+ typeof ChatContext+ >+ }+ >+ <QueuedTurnPortalProvider>+ <PendingTurn messages={messages} />+ <PendingSteerChips+ conversationId={CONVO_ID}+ steering={steering}+ onEditToComposer={editToComposer}+ onRestoreToComposer={restoreToComposer}+ />+ <QueueState onSet={(setter) => (setQueueById = setter)} />+ </QueuedTurnPortalProvider>+ </ChatContext.Provider>+ </JotaiProvider>+ </RecoilRoot>+ </QueryClientProvider>+ );+ const result = render(view(latestMessageId));+ return {+ jotaiStore,+ renderView: (tail: string, messages?: TMessage[]) => result.rerender(view(tail, messages)),+ };+}++describe('queued starting turn controls', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ });++ it('replaces only the matching queue row with a user turn carrying Edit and Remove', () => {+ const { jotaiStore } = renderQueue([serverRow('first'), serverRow('second')]);+ expect(screen.getAllByTestId('queued-message-row')).toHaveLength(2);++ act(() => jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), reveal('first')));++ const turn = screen.getByTestId('pending-turn');+ expect(turn).toHaveTextContent('queued first');+ expect(within(turn).getByRole('status')).toHaveTextContent('com_ui_queued_turn_starting');+ expect(within(turn).getByRole('button', { name: 'com_ui_edit_message' })).toBeEnabled();+ expect(within(turn).getByRole('button', { name: 'com_ui_remove_queued' })).toBeEnabled();+ expect(within(turn).queryByRole('button', { name: 'com_ui_send_now' })).toBeNull();+ expect(screen.getAllByTestId('queued-message-row')).toHaveLength(1);+ expect(screen.getByTestId('queued-message-row')).toHaveTextContent('queued second');+ expect(screen.getAllByText('queued first')).toHaveLength(1);+ });++ it('edits a starting turn only after cancelling its durable copy', async () => {+ const row = {+ ...serverRow('first'),+ files: [{ file_id: 'file-1' }],+ quotes: ['quote'],+ manualSkills: ['skill'],+ };+ const { jotaiStore } = renderQueue([row]);+ act(() => jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), reveal('first')));+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_edit_message' }));++ await waitFor(() => expect(discardQueued).toHaveBeenCalledWith(row));+ await waitFor(() => expect(removeQueued).toHaveBeenCalledWith(row.id));+ expect(restoreToComposer).toHaveBeenCalledWith(+ row.text,+ row.files,+ { quotes: ['quote'], manualSkills: ['skill'] },+ CONVO_ID,+ );+ expect(editToComposer).not.toHaveBeenCalled();+ });++ it('keeps a claimed turn removable but never offers edit or a second send', () => {+ const { jotaiStore } = renderQueue([serverRow('first', 'claimed')]);+ act(() => jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), reveal('first')));++ const turn = screen.getByTestId('pending-turn');+ expect(within(turn).queryByRole('button', { name: 'com_ui_edit_message' })).toBeNull();+ expect(within(turn).getByRole('button', { name: 'com_ui_remove_queued' })).toBeEnabled();+ expect(screen.queryByTestId('pending-steer-chips')).toBeNull();+ expect(sendQueuedNow).not.toHaveBeenCalled();+ });++ it('does not lose the in-flight cancellation lock when the row moves to the turn', async () => {+ let finish: (accepted: boolean) => void = () => undefined;+ discardQueued.mockImplementationOnce(+ () => new Promise<boolean>((resolve) => (finish = resolve)),+ );+ const { jotaiStore } = renderQueue([serverRow('first')]);+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_remove_queued' }));+ expect(discardQueued).toHaveBeenCalledTimes(1);++ act(() => jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), reveal('first')));+ const turn = screen.getByTestId('pending-turn');+ expect(within(turn).getByRole('button', { name: 'com_ui_remove_queued' })).toBeDisabled();+ expect(within(turn).getByRole('button', { name: 'com_ui_edit_message' })).toBeDisabled();+ fireEvent.click(within(turn).getByRole('button', { name: 'com_ui_remove_queued' }));+ expect(discardQueued).toHaveBeenCalledTimes(1);++ await act(async () => finish(false));+ expect(within(turn).getByRole('button', { name: 'com_ui_remove_queued' })).toBeEnabled();+ expect(removeQueued).not.toHaveBeenCalled();+ expect(restoreToComposer).not.toHaveBeenCalled();+ });++ it('restores the full context after confirmed removal, never on failed cancellation', async () => {+ const row = {+ ...serverRow('first'),+ files: [{ file_id: 'file-1' }],+ quotes: ['q'],+ manualSkills: ['s'],+ };+ discardQueued.mockResolvedValueOnce(false).mockResolvedValueOnce(true);+ const { jotaiStore } = renderQueue([row]);+ act(() => jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), reveal('first')));+ const remove = screen.getByRole('button', { name: 'com_ui_remove_queued' });++ fireEvent.click(remove);+ await waitFor(() => expect(remove).toBeEnabled());+ expect(restoreToComposer).not.toHaveBeenCalled();+ expect(removeQueued).not.toHaveBeenCalled();++ fireEvent.click(remove);+ await waitFor(() => expect(removeQueued).toHaveBeenCalledWith(row.id));+ expect(restoreToComposer).toHaveBeenCalledWith(+ row.text,+ row.files,+ { quotes: ['q'], manualSkills: ['s'] },+ CONVO_ID,+ );+ act(() => jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), null));+ expect(screen.queryByTestId('pending-turn')).toBeNull();+ expect(screen.queryByTestId('queued-message-row')).toBeNull();+ });++ it('returns the queue row when the bubble is hidden by a different tail or real successor', () => {+ const { jotaiStore, renderView } = renderQueue([serverRow('first')]);+ act(() => jotaiStore.set(revealedQueuedTurnFamily(CONVO_ID), reveal('first')));+ expect(screen.queryByTestId('queued-message-row')).toBeNull();++ renderView('another-response');+ expect(screen.queryByTestId('pending-turn')).toBeNull();+ expect(screen.getByTestId('queued-message-row')).toHaveTextContent('queued first');++ renderView(RESPONSE_ID, [{ messageId: 'real-user', parentMessageId: RESPONSE_ID } as TMessage]);+ expect(screen.queryByTestId('pending-turn')).toBeNull();+ expect(screen.getByTestId('queued-message-row')).toHaveTextContent('queued first');+ expect(sendQueuedNow).not.toHaveBeenCalled();+ });+});diff --git a/client/src/components/Chat/Messages/PendingTurn.tsx b/client/src/components/Chat/Messages/PendingTurn.tsxindex f04f1cdc55..6a977cdf23 100644--- a/client/src/components/Chat/Messages/PendingTurn.tsx+++ b/client/src/components/Chat/Messages/PendingTurn.tsx@@ -1,10 +1,11 @@-import { useEffect, useMemo, useRef } from 'react';+import { useCallback, 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 { useQueuedTurnPortal } from '~/components/Chat/Steering/QueuedTurnPortal';import { getHeaderPrefixForScreenReader, getMessageAriaLabel } from '~/utils';import { messageFooterClasses } from '~/components/Chat/Messages/styles';import MessageRow from '~/components/Chat/Messages/ui/MessageRow';@@ -25,9 +26,9 @@ 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`).+ * after the completed response it follows. It is not persisted: its actions+ * come from the composer that owns the queue, and it leaves as soon as the+ * thread gains a turn after that response.*/export default function PendingTurn({scrollableRef,@@ -43,6 +44,8 @@ export default function PendingTurn({const { conversation, latestMessageId } = useChatContext();const conversationId = conversation?.conversationId ?? '';const reveal = useAtomValue(revealedQueuedTurnFamily(conversationId));+ const setPortalTarget = useQueuedTurnPortal()?.setTarget;+ const clientRequestId = reveal?.clientRequestId;const usernameDisplay = useRecoilValue(store.UsernameDisplay);const enableUserMsgMarkdown = useRecoilValue(store.enableUserMsgMarkdown);const rowRef = useRef<HTMLDivElement | null>(null);@@ -59,6 +62,16 @@ export default function PendingTurn({reveal != null &&reveal.parentMessageId === latestMessageId &&!successorSeen;+ const setActionsTarget = useCallback(+ (element: HTMLSpanElement | null) => {+ setPortalTarget?.(+ element == null || clientRequestId == null+ ? null+ : { element, conversationId, clientRequestId },+ );+ },+ [setPortalTarget, conversationId, clientRequestId],+ );/** 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.@@ -108,10 +121,13 @@ export default function PendingTurn({isCreatedByUserfullWidth={maximizeChatSpace}footer={- <SubRow classes={cn(messageFooterClasses, 'justify-end')}>+ <SubRow+ classes={cn(messageFooterClasses, 'flex-wrap items-center justify-end gap-1.5')}+ ><span className="text-xs text-text-secondary" role="status">{localize('com_ui_queued_turn_starting')}</span>+ <span ref={setActionsTarget} className="flex items-center gap-1" /></SubRow>}>diff --git a/client/src/components/Chat/Steering/QueuedTurnPortal.tsx b/client/src/components/Chat/Steering/QueuedTurnPortal.tsxnew file mode 100644index 0000000000..d163156584--- /dev/null+++ b/client/src/components/Chat/Steering/QueuedTurnPortal.tsx@@ -0,0 +1,35 @@+import { createContext, useCallback, useContext, useMemo, useState } from 'react';+import type { ReactNode } from 'react';++type QueuedTurnTarget = {+ conversationId: string;+ clientRequestId: string;+ element: HTMLSpanElement;+};++type QueuedTurnPortalContextValue = {+ target: QueuedTurnTarget | null;+ setTarget: (target: QueuedTurnTarget | null) => void;+};++const QueuedTurnPortalContext = createContext<QueuedTurnPortalContextValue | null>(null);++/** The composer owns queue actions; the transcript only supplies their mount point. */+export function QueuedTurnPortalProvider({ children }: { children: ReactNode }) {+ const [target, setTargetState] = useState<QueuedTurnTarget | null>(null);+ const setTarget = useCallback((next: QueuedTurnTarget | null) => {+ setTargetState((current) =>+ current?.element === next?.element &&+ current?.conversationId === next?.conversationId &&+ current?.clientRequestId === next?.clientRequestId+ ? current+ : next,+ );+ }, []);+ const value = useMemo(() => ({ target, setTarget }), [target, setTarget]);+ return (+ <QueuedTurnPortalContext.Provider value={value}>{children}</QueuedTurnPortalContext.Provider>+ );+}++export const useQueuedTurnPortal = () => useContext(QueuedTurnPortalContext);diff --git a/client/src/components/Chat/Subagents/SubagentActivity.test.tsx b/client/src/components/Chat/Subagents/SubagentActivity.test.tsxindex af5f68541e..c62c42f1a2 100644--- a/client/src/components/Chat/Subagents/SubagentActivity.test.tsx+++ b/client/src/components/Chat/Subagents/SubagentActivity.test.tsx@@ -411,7 +411,11 @@ describe('SubagentActivity', () => {expect(screen.getByText('com_ui_subagent_control_message_truncated')).toBeInTheDocument();expect(screen.getByText('com_ui_subagent_control_reason_task_completed')).toBeInTheDocument();- fireEvent.click(screen.getByRole('button', { name: 'com_ui_subagent_control_withdraw' }));+ const accepted = screen.getByText('com_ui_subagent_control_status_accepted');+ const withdraw = screen.getByRole('button', { name: 'com_ui_subagent_control_withdraw' });+ expect(accepted.parentElement).toContainElement(withdraw);+ expect(screen.queryByText('com_ui_queued_turn_starting')).toBeNull();+ fireEvent.click(withdraw);expect(onCancelControl).toHaveBeenCalledWith('control-1');});diff --git a/client/src/components/Chat/Subagents/SubagentActivity.tsx b/client/src/components/Chat/Subagents/SubagentActivity.tsxindex e3ec2fca4e..c9f579991c 100644--- a/client/src/components/Chat/Subagents/SubagentActivity.tsx+++ b/client/src/components/Chat/Subagents/SubagentActivity.tsx@@ -80,12 +80,27 @@ function SubagentControlHistory({key={control.invocationId}className="rounded-lg border border-border-light bg-surface-secondary px-3 py-2 text-sm">- <div className="flex items-center gap-2">+ <div className="flex flex-wrap items-center gap-2"><StatusIcon size={14} aria-hidden className="shrink-0 text-text-secondary" />- <span className="font-medium">{localize(CONTROL_ACTION_LABELS[control.action])}</span>- <span className="ml-auto text-xs text-text-secondary" aria-live="polite">+ <span className="min-w-0 flex-1 font-medium">+ {localize(CONTROL_ACTION_LABELS[control.action])}+ </span>+ <span className="ml-auto shrink-0 text-xs text-text-secondary" aria-live="polite">{localize(CONTROL_STATUS_LABELS[control.status])}</span>+ {control.status === 'accepted' &&+ control.controlId != null &&+ onCancelControl != null && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ className="h-7 shrink-0 px-2 text-xs"+ onClick={() => onCancelControl(control.controlId as string)}+ >+ {localize('com_ui_subagent_control_withdraw')}+ </Button>+ )}</div>{control.message != null && control.message !== '' && (<div className="mt-1 break-words text-text-secondary">@@ -105,19 +120,6 @@ function SubagentControlHistory({)}</div>)}- {control.status === 'accepted' &&- control.controlId != null &&- onCancelControl != null && (- <Button- type="button"- variant="ghost"- size="sm"- className="mt-1 h-7 px-2 text-xs"- onClick={() => onCancelControl(control.controlId as string)}- >- {localize('com_ui_subagent_control_withdraw')}- </Button>- )}</div>);})}diff --git a/e2e/specs/mock/queued-reveal.spec.ts b/e2e/specs/mock/queued-reveal.spec.tsindex ce6e07dda5..7401fe4b06 100644--- a/e2e/specs/mock/queued-reveal.spec.ts+++ b/e2e/specs/mock/queued-reveal.spec.ts@@ -169,10 +169,13 @@ test.describe('server-queued follow-up reveal', () => {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();+ /** One visible copy: actions follow the user turn, not a duplicate chip+ * below the composer. Other queued turns still use their ordinary rows. */+ await expect(row).toHaveCount(0);+ const pending = page.getByTestId('pending-turn');+ await expect(pending).toContainText('Starting as the next turn');+ await expect(pending.getByRole('button', { name: 'Send now' })).toHaveCount(0);+ await expect(pending.getByRole('button', { name: 'Remove message' })).toBeVisible();const nextQueueText = `Queued during handoff ${label}`;await messageInput(page).fill(nextQueueText);@@ -185,6 +188,8 @@ test.describe('server-queued follow-up reveal', () => {messageInput(page).press('Enter'),]);expect(handoffEnqueue.ok()).toBeTruthy();+ await expect(queuedRows(page).filter({ hasText: nextQueueText })).toBeVisible();+ await expect(queuedRows(page).filter({ hasText: queueText })).toHaveCount(0);const originalQueue = enqueued.request().postDataJSON();expect(handoffEnqueue.request().postDataJSON()).toMatchObject({parentMessageId: originalQueue.parentMessageId,