diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsx index 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 - - -

{pageHeading}

-
- <> -
+ + +

{pageHeading}

+
+ <> +
- {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_question popover ⇄ chat-card morph) paints the whole composer band over the travelling card instead of letting it show through below the composer. The background matches the page, so normal rendering is unchanged. */} -
- {isLandingPage && } - {isSubagentThreadReadOnly ? ( -
- {localize('com_ui_subagent_thread_read_only')} -
- ) : ( - - )} - {/* The generic disclaimer is the welcome screen's; a +
+ {isLandingPage && } + {isSubagentThreadReadOnly ? ( +
+ {localize('com_ui_subagent_thread_read_only')} +
+ ) : ( + + )} + {/* The generic disclaimer is the welcome screen's; a deployment's own footer, privacy policy and terms stay with the conversation that always showed them. */} - {!isLandingPage && configuredFooter &&
} + {!isLandingPage && configuredFooter &&
} +
-
- {isLandingPage &&
} - - - + {isLandingPage &&
} + + + + diff --git a/client/src/components/Chat/Input/PendingSteerChips.tsx b/client/src/components/Chat/Input/PendingSteerChips.tsx index 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' && ( + + )} + {!removeDisabled || actionPending ? ( + + ) : null} + + ); + } + const entries: MenuEntry[] = [ { key: 'edit', label: localize('com_ui_edit_message'), icon:
); } @@ -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()); + const [pendingActions, setPendingActions] = useState>(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 = ( + + ); + 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 ( -
-
- {failedSteers.map((steer) => ( - - ))} - {queued.map((message) => ( - - ))} -
-
+ <> + {(failedSteers.length > 0 || queuedRows.length > 0) && ( +
+
+ {failedSteers.map((steer) => ( + + ))} + {queuedRows} +
+
+ )} + {portaledActions} + ); } diff --git a/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsx b/client/src/components/Chat/Input/__tests__/PendingSteerChips.test.tsx index 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.tsx new file mode 100644 index 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: () => , +})); +jest.mock('~/components/Chat/Messages/Content/Container', () => ({ + __esModule: true, + default: ({ children }: { children: React.ReactNode }) =>
{children}
, +})); +jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({ + __esModule: true, + default: ({ content }: { content: string }) => {content}, +})); +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[]) => ( + + set(store.queuedMessagesByConvoId(CONVO_ID), rows)}> + + + } + > + + + + (setQueueById = setter)} /> + + + + + + ); + 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((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.tsx index 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(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({ isCreatedByUser fullWidth={maximizeChatSpace} footer={ - + {localize('com_ui_queued_turn_starting')} + } > diff --git a/client/src/components/Chat/Steering/QueuedTurnPortal.tsx b/client/src/components/Chat/Steering/QueuedTurnPortal.tsx new file mode 100644 index 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(null); + +/** The composer owns queue actions; the transcript only supplies their mount point. */ +export function QueuedTurnPortalProvider({ children }: { children: ReactNode }) { + const [target, setTargetState] = useState(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 ( + {children} + ); +} + +export const useQueuedTurnPortal = () => useContext(QueuedTurnPortalContext); diff --git a/client/src/components/Chat/Subagents/SubagentActivity.test.tsx b/client/src/components/Chat/Subagents/SubagentActivity.test.tsx index 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.tsx index 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" > -
+
- {localize(CONTROL_ACTION_LABELS[control.action])} - + + {localize(CONTROL_ACTION_LABELS[control.action])} + + {localize(CONTROL_STATUS_LABELS[control.status])} + {control.status === 'accepted' && + control.controlId != null && + onCancelControl != null && ( + + )}
{control.message != null && control.message !== '' && (
@@ -105,19 +120,6 @@ function SubagentControlHistory({ )}
)} - {control.status === 'accepted' && - control.controlId != null && - onCancelControl != null && ( - - )}
); })} diff --git a/e2e/specs/mock/queued-reveal.spec.ts b/e2e/specs/mock/queued-reveal.spec.ts index 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,