diff --git a/.github/guard-specs.json b/.github/guard-specs.json index 3de890b08e..64aea283bb 100644 --- a/.github/guard-specs.json +++ b/.github/guard-specs.json @@ -24,17 +24,22 @@ "client/src/__tests__/hosts.test.tsx": [ "client/src/App.jsx", "client/src/components/Chat/Messages/hosts.ts", - "client/src/components/Chat/Messages/slots.tsx", + "client/src/components/Chat/Messages/load.tsx", "client/src/components/Chat/Presentation.tsx", "client/src/routes/ShareRoute.tsx", "client/src/routes/Search.tsx" ], + "client/src/__tests__/messageContentCascade.spec.ts": [ + "client/src/style.css", + "packages/client/src/theme/parts.css" + ], "client/src/__tests__/loadingCanvas.spec.ts": ["client/index.html"], "client/src/__tests__/loadingSpinner.spec.tsx": ["client/index.html"], "client/src/components/Chat/Input/Composer/__tests__/semanticTokens.spec.ts": [ "client/src/components/Chat/", "client/src/hooks/Input/usePaletteEntries.tsx", - "packages/chat/src/components/composer/" + "packages/chat/src/components/composer/", + "packages/chat/src/components/messages/PendingSteers.tsx" ], "client/src/components/Chat/Input/__tests__/appearanceTokens.spec.ts": [ "client/src/components/Chat/Input/", @@ -79,6 +84,7 @@ ], "packages/client/src/components/__tests__/radixLayers.spec.ts": ["package-lock.json"], "packages/client/src/theme/defaults.spec.ts": ["packages/client/src/theme/defaults.css"], + "packages/client/src/theme/parts.spec.ts": ["packages/client/src/theme/parts.css"], "packages/client/src/theme/primitives.spec.ts": [ "eslint-suppressions.json", "packages/client/src/components/" diff --git a/client/src/Providers/MessagesHostContext.tsx b/client/src/Providers/MessagesHostContext.tsx index c9b5a75993..71885661d1 100644 --- a/client/src/Providers/MessagesHostContext.tsx +++ b/client/src/Providers/MessagesHostContext.tsx @@ -32,6 +32,7 @@ import useConversationSeenSource from '~/hooks/Conversations/seenSource'; import useGetAddedConvo from '~/hooks/Conversations/useGetAddedConvo'; import { useOptionalMessagesOperations } from './MessagesViewContext'; import { PrivateText } from '~/components/Chat/Messages/PrivateText'; +import { FLAT_THREAD } from '~/components/Chat/Messages/Thread/flag'; import MessageAudio from '~/components/Chat/Messages/MessageAudio'; import { useAssistantsMapContext } from './AssistantsMapContext'; import MessageIcon from '~/components/Chat/Messages/MessageIcon'; @@ -156,6 +157,7 @@ export const appMessagesHost: MessagesHost = { useSeenSource: useConversationSeenSource, renderMessageIcon: (props) => , useMaximizeChatSpace: () => useRecoilValue(store.maximizeChatSpace), + useFlatThread: () => FLAT_THREAD, useHideSelectedAuthor, useAgentsMap: useAgentsMapContext, renderMessageBody: (props) => , diff --git a/client/src/__tests__/hosts.test.tsx b/client/src/__tests__/hosts.test.tsx index bfccd3be51..ed7c5243d8 100644 --- a/client/src/__tests__/hosts.test.tsx +++ b/client/src/__tests__/hosts.test.tsx @@ -37,7 +37,7 @@ const ROW_HOSTS = [ ]; const ROW_HOSTS_MODULE = '~/components/Chat/Messages/hosts'; const ROW_SURFACES = [ - 'components/Chat/Messages/slots.tsx', + 'components/Chat/Messages/load.tsx', 'components/Chat/Presentation.tsx', 'routes/ShareRoute.tsx', 'routes/Search.tsx', @@ -68,6 +68,16 @@ describe('app host registration', () => { } }); + it('keeps the flat thread flag on the messages host', () => { + const { FLAT_THREAD } = jest.requireActual< + typeof import('~/components/Chat/Messages/Thread/flag') + >('~/components/Chat/Messages/Thread/flag'); + const { appMessagesHost } = jest.requireActual< + typeof import('~/Providers/MessagesHostContext') + >('~/Providers/MessagesHostContext'); + expect(appMessagesHost.useFlatThread()).toBe(FLAT_THREAD); + }); + it('registers the row hosts on every surface that draws message rows', () => { const hosts = readSource('components/Chat/Messages/hosts.ts'); for (const path of ROW_HOSTS) { diff --git a/client/src/__tests__/messageContentCascade.spec.ts b/client/src/__tests__/messageContentCascade.spec.ts new file mode 100644 index 0000000000..5cb855d448 --- /dev/null +++ b/client/src/__tests__/messageContentCascade.spec.ts @@ -0,0 +1,47 @@ +import fs from 'fs'; +import path from 'path'; +import postcss from 'postcss'; + +const read = (...segments: string[]) => + fs.readFileSync(path.resolve(__dirname, ...segments), 'utf8'); + +/** The library stylesheet loads before the app's, as `main.jsx` imports them. */ +const sheets = [read('../../../packages/client/src/theme/parts.css'), read('../style.css')]; + +const ELEMENT_CLASSES = new Set(['markdown', 'prose', 'message-content']); + +/** + * The declaration that wins for `property` on a `.markdown.prose.message-content` element. Every + * rule here is a single class selector at the top level, so specificity ties and source order + * decides: the last matching rule wins. + */ +function winner(property: string): string | undefined { + let value: string | undefined; + for (const css of sheets) { + postcss.parse(css).each((node) => { + if (node.type !== 'rule') { + return; + } + const matches = node.selectors.some( + (selector) => /^\.[\w-]+$/.test(selector) && ELEMENT_CLASSES.has(selector.slice(1)), + ); + if (!matches) { + return; + } + node.each((decl) => { + if (decl.type === 'decl' && decl.prop === property) { + value = decl.value.replace(/\s+/g, ' ').trim(); + } + }); + }); + } + return value; +} + +describe('message body cascade with the library styles first', () => { + it('keeps the message typography the app has always drawn', () => { + expect(winner('line-height')).toBe('1.6'); + expect(winner('font-size')).toBe('var(--markdown-font-size, var(--font-size-base))'); + expect(winner('max-width')).toBe('none'); + }); +}); diff --git a/client/src/components/Chat/Input/Composer/__tests__/semanticTokens.spec.ts b/client/src/components/Chat/Input/Composer/__tests__/semanticTokens.spec.ts index d18fb3fbb6..59d75a1e4b 100644 --- a/client/src/components/Chat/Input/Composer/__tests__/semanticTokens.spec.ts +++ b/client/src/components/Chat/Input/Composer/__tests__/semanticTokens.spec.ts @@ -28,7 +28,7 @@ const protectedModules = [ __dirname, '../../../../../../../packages/chat/src/components/composer/EscalateNowButton.tsx', ), - join(__dirname, '..', '..', '..', 'Messages', 'Content', 'Parts', 'PendingSteers.tsx'), + join(__dirname, '../../../../../../../packages/chat/src/components/messages/PendingSteers.tsx'), join(__dirname, '..', '..', '..', '..', '..', 'hooks', 'Input', 'usePaletteEntries.tsx'), ]; diff --git a/client/src/components/Chat/Input/__tests__/QueuedTurnPortal.spec.tsx b/client/src/components/Chat/Input/__tests__/QueuedTurnPortal.spec.tsx index 7d88d568dd..391c4bc8ad 100644 --- a/client/src/components/Chat/Input/__tests__/QueuedTurnPortal.spec.tsx +++ b/client/src/components/Chat/Input/__tests__/QueuedTurnPortal.spec.tsx @@ -4,9 +4,14 @@ import { EModelEndpoint } from 'librechat-data-provider'; import { act, render, screen } from '@testing-library/react'; import { Provider as JotaiProvider, createStore } from 'jotai'; import { revealedQueuedTurnFamily } from '@librechat/chat/react'; -import { QueuedTurnPortalProvider, useQueuedTurnPortal } from '@librechat/chat/components'; +import { MessagePartsHostProvider } from '@librechat/chat/react'; +import { + QueuedTurnPortalProvider, + PendingTurn, + useQueuedTurnPortal, +} from '@librechat/chat/components'; +import type { MessagePartsHost } from '@librechat/chat/react'; import type { TConversation } from 'librechat-data-provider'; -import PendingTurn from '~/components/Chat/Messages/PendingTurn'; import { ChatContext } from '~/Providers'; jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key })); @@ -19,6 +24,16 @@ jest.mock('@librechat/chat/components', () => ({ ...jest.requireActual('@librechat/chat/components'), Container: ({ children }: { children: React.ReactNode }) =>
{children}
, })); +const partsHost = { + useUser: () => ({ name: 'Danny' }), + useUserTextPreferences: () => ({ + enableUserMsgMarkdown: false, + collapseLongUserMessages: false, + usernameDisplay: false, + }), + renderMarkdown: ({ content }: { content: string }) => content, +} as unknown as MessagePartsHost; + const conversationId = 'convo-queued-turn'; const conversation = { conversationId, @@ -48,10 +63,12 @@ it('registers the revealed user turn action target only while it is visible', () { conversation, latestMessageId, index: 0 } as React.ContextType } > - - - - + + + + + + diff --git a/client/src/components/Chat/Messages/PendingTurn.tsx b/client/src/components/Chat/Messages/PendingTurn.tsx deleted file mode 100644 index 2a178bc55d..0000000000 --- a/client/src/components/Chat/Messages/PendingTurn.tsx +++ /dev/null @@ -1,63 +0,0 @@ -import { useRecoilValue } from 'recoil'; -import { PendingTurn as PackagePendingTurn, Container } from '@librechat/chat/components'; -import type { TMessage } from 'librechat-data-provider'; -import type { RefObject } from 'react'; -import type { TMessageIcon } from '~/common'; -import MessageIcon from '~/components/Chat/Messages/MessageIcon'; -import { useAuthContext } from '~/hooks/AuthContext'; -import MarkdownLite from './Content/MarkdownLite'; -import { useChatContext } from '~/Providers'; -import { useLocalize } from '~/hooks'; -import { cn } from '~/utils'; -import store from '~/store'; - -/** The app's side of the queued follow-up row: who sent it, their icon, and how the text reads. */ -export default function PendingTurn({ - scrollableRef, - messages, - maximizeChatSpace = false, -}: { - scrollableRef?: RefObject; - messages?: TMessage[] | null; - maximizeChatSpace?: boolean; -}) { - const localize = useLocalize(); - const { user } = useAuthContext(); - const { conversation, latestMessageId } = useChatContext(); - const usernameDisplay = useRecoilValue(store.UsernameDisplay); - const enableUserMsgMarkdown = useRecoilValue(store.enableUserMsgMarkdown); - - 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 ( - } - renderBody={(message, text) => ( - -
- {enableUserMsgMarkdown ? : text} -
-
- )} - /> - ); -} diff --git a/client/src/components/Chat/Messages/__tests__/PendingTurn.spec.tsx b/client/src/components/Chat/Messages/__tests__/PendingTurn.spec.tsx deleted file mode 100644 index 59d4c3ac5e..0000000000 --- a/client/src/components/Chat/Messages/__tests__/PendingTurn.spec.tsx +++ /dev/null @@ -1,125 +0,0 @@ -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 { revealedQueuedTurnFamily } from '@librechat/chat/react'; -import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; -import type { TConversation, TMessage } from 'librechat-data-provider'; -import type { RevealedQueuedTurn } from '@librechat/chat/react'; -import PendingTurn from '~/components/Chat/Messages/PendingTurn'; -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: () => , -})); - -jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({ - __esModule: true, - default: ({ content }: { content: string }) => {content}, -})); - -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 => ({ - 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( - - - - - - - - - , - ); - 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('Starting as the next turn'); - 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/Messages/__tests__/load.spec.tsx b/client/src/components/Chat/Messages/__tests__/load.spec.tsx index 705443406e..beb60637b0 100644 --- a/client/src/components/Chat/Messages/__tests__/load.spec.tsx +++ b/client/src/components/Chat/Messages/__tests__/load.spec.tsx @@ -4,19 +4,18 @@ import { render, screen } from '@testing-library/react'; import type { ChatScreenMessagesSlots } from '@librechat/chat/components'; const mockLoadScreenMessages = jest.fn(); -const mockSlots: ChatScreenMessagesSlots = { flatThread: true }; jest.mock('@librechat/chat/components', () => ({ loadScreenMessages: () => mockLoadScreenMessages(), })); -jest.mock('../slots', () => ({ messagesSlots: mockSlots })); +jest.mock('../hosts', () => ({})); type ListProps = { messages: unknown; slots?: ChatScreenMessagesSlots }; function PackageList({ messages, slots }: ListProps) { return (

- {String(messages)} {slots === mockSlots ? 'app slots' : 'no slots'} + {String(messages)} {slots == null ? 'package defaults' : 'app slots'}

); } @@ -34,7 +33,7 @@ describe('message list loader', () => { mockLoadScreenMessages.mockReset(); }); - it('draws the package list with the app slots once both have loaded', async () => { + it('draws the package list once its hosts have loaded', async () => { mockLoadScreenMessages.mockResolvedValue({ default: PackageList }); const { renderMessages } = loadModule(); @@ -45,7 +44,7 @@ describe('message list loader', () => { ); expect(screen.getByRole('status')).toBeInTheDocument(); - expect(await screen.findByText('null app slots')).toBeInTheDocument(); + expect(await screen.findByText('null package defaults')).toBeInTheDocument(); }); it('loads the list once for every caller', async () => { diff --git a/client/src/components/Chat/Messages/load.tsx b/client/src/components/Chat/Messages/load.tsx index 5a6d75c138..b022434e62 100644 --- a/client/src/components/Chat/Messages/load.tsx +++ b/client/src/components/Chat/Messages/load.tsx @@ -9,19 +9,14 @@ type MessagesModule = { default: ComponentType }; let pending: Promise | null = null; /** - * Loads the package message list together with the app's hosts and slots, once. A routed + * Loads the package message list together with the app's hosts, once. A routed * conversation and the composer start it early so the list is not fetched only after the * conversation's messages arrive; a failed load is dropped so the next attempt retries. + * The list renders its own pending turn, pending steers and thread mode from those hosts. */ export function preloadMessages(): Promise { pending ??= importWithRecovery(() => - Promise.all([loadScreenMessages(), import('./slots')]).then(([list, app]) => { - const ScreenMessages = list.default; - function AppScreenMessages(props: ChatScreenMessagesProps): ReactElement { - return ; - } - return { default: AppScreenMessages }; - }), + Promise.all([loadScreenMessages(), import('./hosts')]).then(([list]) => list), ).catch((error: unknown) => { pending = null; throw error; diff --git a/client/src/components/Chat/Messages/slots.tsx b/client/src/components/Chat/Messages/slots.tsx deleted file mode 100644 index aeeb0570ce..0000000000 --- a/client/src/components/Chat/Messages/slots.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import type { ChatScreenMessagesSlots } from '@librechat/chat/components'; -import PendingSteers from './Content/Parts/PendingSteers'; -import PendingTurn from './PendingTurn'; -import { FLAT_THREAD } from './Thread'; -import './hosts'; - -/** The app's pieces of the package message list, loaded with it. */ -export const messagesSlots: ChatScreenMessagesSlots = { - flatThread: FLAT_THREAD, - renderPendingTurn: (props) => , - renderPendingSteers: (props) => , -}; diff --git a/client/src/components/Chat/__tests__/ChatView.slots.spec.tsx b/client/src/components/Chat/__tests__/ChatView.slots.spec.tsx index 60dd57fbe5..8cac77ab09 100644 --- a/client/src/components/Chat/__tests__/ChatView.slots.spec.tsx +++ b/client/src/components/Chat/__tests__/ChatView.slots.spec.tsx @@ -1,20 +1,12 @@ -import React, { createRef, isValidElement } from 'react'; +import React from 'react'; import '@testing-library/jest-dom'; -import type { ChatScreenMessagesSlots, ChatScreenProps } from '@librechat/chat/components'; -import type { ReactElement, ReactNode } from 'react'; -import PendingSteers from '../Messages/Content/Parts/PendingSteers'; -import PendingTurn from '../Messages/PendingTurn'; -import { messagesSlots } from '../Messages/slots'; +import type { ChatScreenProps } from '@librechat/chat/components'; import { renderMessages } from '../Messages/load'; -import { FLAT_THREAD } from '../Messages/Thread'; import { render } from 'test/layout-test-utils'; import ChatView from '../ChatView'; const mockScreenProps = jest.fn(); -/** The row hosts import the whole message renderer; the slots under test do not need them. */ -jest.mock('../Messages/hosts', () => ({})); - jest.mock('react-router-dom', () => ({ ...jest.requireActual('react-router-dom'), useParams: () => ({ conversationId: 'convo-1' }), @@ -75,50 +67,11 @@ jest.mock('../Footer', () => ({ useLandingFooter: () => true, })); -/** The slots load with the list, so ChatView hands the screen the loader's renderer. */ -const screenSlots = (): ChatScreenMessagesSlots => messagesSlots; - -const scrollableRef = createRef(); - -/** A slot's output as an element, failing the test when the slot rendered nothing. */ -function element(node: ReactNode): ReactElement { - if (!isValidElement(node)) { - throw new Error('The slot did not render an element'); - } - return node; -} - -describe('ChatView message list slots', () => { - test('hands the screen the on-demand list instead of the slots', () => { +describe('ChatView message list', () => { + test('hands the screen the on-demand list and no message slots', () => { render(); const props = mockScreenProps.mock.calls.at(-1)?.[0]; expect(props?.renderMessages).toBe(renderMessages); expect(props?.messagesSlots).toBeUndefined(); }); - - test('leaves the list to ChatScreen and fills it with the app thread mode', () => { - expect(screenSlots().flatThread).toBe(FLAT_THREAD); - }); - - test('leaves the scroll control to the package list', () => { - expect(screenSlots().renderScrollButton).toBeUndefined(); - }); - - test('renders the app pending turn and steers with what the list passes', () => { - const slots = screenSlots(); - const turn = { scrollableRef, messages: null, maximizeChatSpace: true }; - const steers = { conversationId: 'convo-1', index: 0, fullWidth: false }; - - const turnElement = element(slots.renderPendingTurn?.(turn)); - const steersElement = element(slots.renderPendingSteers?.(steers)); - - expect(turnElement.type).toBe(PendingTurn); - expect(turnElement.props).toEqual(turn); - expect(steersElement.type).toBe(PendingSteers); - expect(steersElement.props).toEqual(steers); - }); - - test('leaves the navigation rail to the package list', () => { - expect(screenSlots().renderNav).toBeUndefined(); - }); }); diff --git a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx index 35ed6ede61..36aeae5c27 100644 --- a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx +++ b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx @@ -1,6 +1,8 @@ import React from 'react'; import { render, screen } from '@testing-library/react'; +import { SteerHostProvider } from '@librechat/chat/react'; import { MessagesHostTestProvider } from 'test/messagesHost'; +import { inertSteerHost } from 'test/inertSteerHost'; import { ChatSurfaceHarness } from 'test/harness'; import ChatView from '../ChatView'; /** The app registers its parts host at boot (App.jsx); the child's list reads it. */ @@ -80,9 +82,6 @@ jest.mock('~/data-provider', () => ({ })); jest.mock('../Input/ConversationStarters', () => () => null); -/** The package list renders the child's messages; the app's pieces of it are not under test. */ -jest.mock('../Messages/PendingTurn', () => () => null); -jest.mock('../Messages/Content/Parts/PendingSteers', () => () => null); jest.mock('../Presentation', () => ({ children }: { children: React.ReactNode }) => ( <>{children} )); @@ -130,7 +129,9 @@ describe('ChatView child-thread execution identity', () => { render( - + + + , ); diff --git a/client/src/style.css b/client/src/style.css index 759cfb0c38..1130c021c5 100644 --- a/client/src/style.css +++ b/client/src/style.css @@ -1832,6 +1832,9 @@ html { transform-origin: 50% 50%; } +/* `.message-content` is also published in @librechat/client (theme/parts.css) for other hosts. + * That stylesheet loads before this one, so `.prose` and `.markdown` above would win; keeping the + * rule here at its original place preserves the app's message line height and width. */ .message-content, .message-editor-text { font-size: var(--markdown-font-size, var(--font-size-base)); diff --git a/client/test/inertSteerHost.ts b/client/test/inertSteerHost.ts new file mode 100644 index 0000000000..1d88faabf3 --- /dev/null +++ b/client/test/inertSteerHost.ts @@ -0,0 +1,34 @@ +import type { SteerHost } from '@librechat/chat/react'; + +/** A steer host whose transport does nothing, for specs that mount the package list + * outside the app shell. */ +export const inertSteerHost: SteerHost = { + useSteerMessage: () => () => undefined, + useSteerMessageAsync: () => async () => ({ + status: 'queued', + steerId: 'steer-1', + position: 0, + conversationId: 'convo-1', + }), + useCancelSteer: () => async () => ({ removed: true }), + useArmSteer: () => async () => ({ armed: true }), + useMarkFilesUsage: () => () => undefined, + useEnqueueQueuedTurn: () => () => undefined, + useCancelQueuedTurn: () => async () => { + throw new Error('not queued'); + }, + useQueuedTurns: () => undefined, + useQueuedTurnCache: () => ({ read: () => ({}), subscribe: () => () => undefined }), + useFetchStreamStatus: () => async () => ({ active: false }), + useRouteConversationId: () => undefined, + useCodeApprovalInputs: () => ({ conversation: null, reachable: { agents: [], complete: true } }), + useLocalize: () => (key) => key, + useNotify: () => () => undefined, + useFileMap: () => undefined, + useClearFilesToDelete: () => () => undefined, + useSettings: () => ({ + duringRunDefaultAction: 'steer', + setDuringRunDefaultAction: () => undefined, + getPaneConversations: () => [], + }), +}; diff --git a/client/test/messagesHost.tsx b/client/test/messagesHost.tsx index 1f68c8e0ed..ccaac6bee5 100644 --- a/client/test/messagesHost.tsx +++ b/client/test/messagesHost.tsx @@ -36,6 +36,7 @@ export const testMessagesHost: MessagesHost = { }), renderMessageIcon: () => null, useMaximizeChatSpace: () => false, + useFlatThread: () => true, useHideSelectedAuthor: () => false, useAgentsMap: () => undefined, renderMessageBody: () => null, diff --git a/e2e/specs/mock/scenarios/lazy-surfaces.spec.ts b/e2e/specs/mock/scenarios/lazy-surfaces.spec.ts index 992baf7cba..b296510957 100644 --- a/e2e/specs/mock/scenarios/lazy-surfaces.spec.ts +++ b/e2e/specs/mock/scenarios/lazy-surfaces.spec.ts @@ -25,8 +25,8 @@ function recordOnDemandChunks(page: Page): string[] { return seen; } -/** The message list and the app's row hosts and slots, which the welcome screen never draws. */ -const MESSAGE_LIST_CHUNK = /\/assets\/(messages|slots|hosts)\.[^/"]+\.js/g; +/** The message list and the app's row hosts, which the welcome screen never draws. */ +const MESSAGE_LIST_CHUNK = /\/assets\/(messages|hosts)\.[^/"]+\.js/g; /** The mock fleet runs without the trace viewer, so the served config and availability turn it on. */ async function enableTraceViewer(page: Page): Promise { @@ -95,7 +95,7 @@ test.describe('surfaces that load on demand', () => { const seen = new Set(); page.on('request', (request) => { - const match = new URL(request.url()).pathname.match(/\/assets\/(messages|slots)\./); + const match = new URL(request.url()).pathname.match(/\/assets\/(messages|hosts)\./); if (match) { seen.add(match[1]); } @@ -104,7 +104,7 @@ test.describe('surfaces that load on demand', () => { await expect(messagesView(page).getByText(replyText('lazy-list-link'))).toBeVisible(); await expect(messagesView(page).getByText(replyPrompt('lazy-list-link'))).toBeVisible(); - expect([...seen].sort()).toEqual(['messages', 'slots']); + expect([...seen].sort()).toEqual(['hosts', 'messages']); }); test('the first message of a fresh chat appears in the list @scenario:first-message-draws-message-list', async ({ diff --git a/packages/chat/src/__fixtures__/messagesHost.ts b/packages/chat/src/__fixtures__/messagesHost.ts index 26b8fbda3f..2aff6d4631 100644 --- a/packages/chat/src/__fixtures__/messagesHost.ts +++ b/packages/chat/src/__fixtures__/messagesHost.ts @@ -34,6 +34,7 @@ export function createMessagesHost(overrides: Partial = {}): Messa }), renderMessageIcon: () => null, useMaximizeChatSpace: () => false, + useFlatThread: () => true, useHideSelectedAuthor: () => false, useAgentsMap: () => undefined, renderMessageBody: () => null, diff --git a/packages/chat/src/__fixtures__/steerHost.ts b/packages/chat/src/__fixtures__/steerHost.ts new file mode 100644 index 0000000000..e5643e1e82 --- /dev/null +++ b/packages/chat/src/__fixtures__/steerHost.ts @@ -0,0 +1,39 @@ +import type { SteerHost } from '../react/steer/host'; + +/** A steer host whose transport does nothing, for specs that mount the pending row. */ +export function createSteerHost(overrides: Partial = {}): SteerHost { + return { + useSteerMessage: () => () => undefined, + useSteerMessageAsync: () => async () => ({ + status: 'queued', + steerId: 'steer-1', + position: 0, + conversationId: 'convo-1', + }), + useCancelSteer: () => async () => ({ removed: true }), + useArmSteer: () => async () => ({ armed: true }), + useMarkFilesUsage: () => () => undefined, + useEnqueueQueuedTurn: () => () => undefined, + useCancelQueuedTurn: () => async () => { + throw new Error('not queued'); + }, + useQueuedTurns: () => undefined, + useQueuedTurnCache: () => ({ read: () => ({}), subscribe: () => () => undefined }), + useFetchStreamStatus: () => async () => ({ active: false }), + useRouteConversationId: () => undefined, + useCodeApprovalInputs: () => ({ + conversation: null, + reachable: { agents: [], complete: true }, + }), + useLocalize: () => (key) => key, + useNotify: () => () => undefined, + useFileMap: () => undefined, + useClearFilesToDelete: () => () => undefined, + useSettings: () => ({ + duringRunDefaultAction: 'steer', + setDuringRunDefaultAction: () => undefined, + getPaneConversations: () => [], + }), + ...overrides, + }; +} diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts index f1a9b088a1..dc3ba3e76b 100644 --- a/packages/chat/src/components.ts +++ b/packages/chat/src/components.ts @@ -105,6 +105,8 @@ export { default as MessageRow } from './components/messages/MessageRow'; export { default as WakeupRow } from './components/messages/WakeupRow'; export { default as PendingTurn } from './components/messages/PendingTurn'; export type { PendingTurnProps } from './components/messages/PendingTurn'; +export { default as PendingSteers } from './components/messages/PendingSteers'; +export type { PendingSteersProps } from './components/messages/PendingSteers'; export { default as MessageTimestamp } from './components/messages/MessageTimestamp'; export { getMessageRowWidthClass } from './components/messages/width'; export { isValidTimestamp, getMessageTimestamp } from './components/messages/time'; diff --git a/packages/chat/src/components/messages/MessagesView.tsx b/packages/chat/src/components/messages/MessagesView.tsx index 3552c364bf..d7b3f54e29 100644 --- a/packages/chat/src/components/messages/MessagesView.tsx +++ b/packages/chat/src/components/messages/MessagesView.tsx @@ -12,10 +12,13 @@ import { import useMessageScrolling from '../../react/messages/useMessageScrolling'; import useConversationSeen from '../../react/messages/useConversationSeen'; import useScrollbarGutter from '../../react/messages/useScrollbarGutter'; +import { useOptionalSteerHost } from '../../react/steer/host'; import { useMessagesHost } from '../../react/messages/host'; import { useChatContext } from '../../react/chat/context'; import { useMessagePartsHost } from '../../react/host'; +import PendingSteers from './PendingSteers'; import ScrollButton from './ScrollButton'; +import PendingTurn from './PendingTurn'; import MessageNav from './MessageNav'; import Thread from './thread/Thread'; @@ -65,25 +68,50 @@ const renderDefaultNav: NonNullable = ({ ); +const renderDefaultPendingTurn: NonNullable = ({ + scrollableRef, + messages, + maximizeChatSpace, +}) => ( + +); + +const renderDefaultPendingSteers: NonNullable = ( + props, +) => ; + /** * The message list: the scroll container, the rendered thread with its progressive mount - * window, the pending tail, and the end marker the scroll and seen reporting watch. The rows, - * the pending pieces, the scroll control and the navigation rail arrive as slots. + * window, the pending tail, and the end marker the scroll and seen reporting watch. The + * pending turn, pending steers, scroll control and navigation rail are the package's own + * unless a caller passes a slot. The pending rows stay unmounted when no steer host is + * present, so a shared page does not call the steer hooks. */ export default function MessagesView({ messagesTree, messages, showScrollButton, maximizeChatSpace, - flatThread = true, + flatThread, renderThread = renderDefaultThread, - renderPendingTurn, - renderPendingSteers, + renderPendingTurn: renderPendingTurnSlot, + renderPendingSteers: renderPendingSteersSlot, renderScrollButton = renderDefaultScrollButton, renderNav = renderDefaultNav, }: MessagesViewProps): ReactElement { const localize = useLocalize(); const host = useMessagesHost(); + const steerHost = useOptionalSteerHost(); + const renderPendingTurn = + renderPendingTurnSlot ?? (steerHost == null ? undefined : renderDefaultPendingTurn); + const renderPendingSteers = + renderPendingSteersSlot ?? (steerHost == null ? undefined : renderDefaultPendingSteers); + const hostFlatThread = host.useFlatThread(); + const flat = flatThread ?? hostFlatThread; const fontSize = useMessagePartsHost().useFontSize(); const screenshotTargetRef = host.useScreenshotTarget(); const [currentEditId, setCurrentEditId] = useState(-1); @@ -227,7 +255,7 @@ export default function MessagesView({ messagesTree, messages, conversationId: treeConversationId, - flat: flatThread, + flat, currentEditId, setCurrentEditId, })} diff --git a/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx b/packages/chat/src/components/messages/PendingSteers.tsx similarity index 72% rename from client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx rename to packages/chat/src/components/messages/PendingSteers.tsx index 8cb3f4b977..9d77b4f2d6 100644 --- a/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx +++ b/packages/chat/src/components/messages/PendingSteers.tsx @@ -1,45 +1,67 @@ import { memo, useMemo, useRef, useState } from 'react'; -import { hasLiveRunPause } from '@librechat/chat'; +import { useAtomValue } from 'jotai'; import { Clock, TextQuote, X } from 'lucide-react'; -import { useQueryClient } from '@tanstack/react-query'; -import { Button, TooltipAnchor } from '@librechat/client'; -import { QueryKeys, type TMessage } from 'librechat-data-provider'; -import { SteerPart, EscalateNowButton, getMessageRowWidthClass } from '@librechat/chat/components'; -import { - useSteerCancel, +import { Button, TooltipAnchor, useLocalize } from '@librechat/client'; +import type { ReactElement, NamedExoticComponent } from 'react'; +import type { TMessage } from 'librechat-data-provider'; +import type { SteerReceiptState } from '../composer/steering/Receipt'; +import useSteerCancel, { useSteerMoveToQueue, useSteerRehome, - useSteerEscalate, - useSteerRecovery, -} from '@librechat/chat/react'; -import type { SteerReceiptState } from '@librechat/chat/components'; -import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext'; -import { cn, isLegacyDeliveryUncertain } from '~/utils'; -import { useCachedMessages } from '~/data-provider'; -import { useLatestMessage } from '~/hooks/Messages'; -import { useLocalize } from '~/hooks'; +} from '../../react/steering/useSteerCancel'; +import { hasLiveRunPause, isLegacyDeliveryUncertain } from '../../core'; +import useSteerRecovery from '../../react/steering/useSteerRecovery'; +import useSteerEscalate from '../../react/steering/useSteerEscalate'; +import { pendingSteersByConvoId } from '../../react/steer/atoms'; +import EscalateNowButton from '../composer/EscalateNowButton'; +import { useMessagesHost } from '../../react/messages/host'; +import { useMessagePartsHost } from '../../react/host'; +import { useBranchTail } from '../../react/latest'; +import { getMessageRowWidthClass } from './width'; +import SteerPart from '../parts/SteerPart'; -/** - * Steers that have not been confirmed by the server yet, rendered at the tail - * of the streaming reply (the place the words will land) instead of in a - * floating overlay over the composer. Confirmation swaps them for the real - * `ContentTypes.STEER` part (`useResumableSSE` removes the pending entry), so - * the row's whole job is to hold the position and admit it is provisional. - */ -interface PendingSteersProps { +/** Steers the server has not confirmed, at the tail of the reply they will join. + * Confirmation swaps them for the real steer part, so the row holds the place + * and says it is provisional. */ +export interface PendingSteersProps { conversationId: string; - /** The pane rendering this tree: its sibling selection picks the branch the - * pause check reads, which another pane's selection would get wrong. */ + /** The pane rendering this tree. Its sibling selection is the branch the pause + * check reads; another pane's selection would get that wrong. */ index?: number; fullWidth?: boolean; } -function PendingSteers({ conversationId, index = 0, fullWidth = false }: PendingSteersProps) { +/** Whether escalation must stay off. A multi-message cache follows the branch on + * screen once this pane owns the conversation, and any branch until then. A + * one-message cache is that branch. */ +function resolvePaused( + cachedMessages: TMessage[], + paneConversationId: string | null, + conversationId: string, + latestMessage: TMessage | null, + fallbackPaused: boolean | undefined, +): boolean { + if (cachedMessages.length > 1) { + if (paneConversationId === conversationId && latestMessage != null) { + return hasLiveRunPause(latestMessage); + } + return cachedMessages.some((message) => hasLiveRunPause(message)); + } + if (fallbackPaused != null) { + return fallbackPaused; + } + return cachedMessages.length === 1 && hasLiveRunPause(cachedMessages[0]); +} + +function PendingSteers({ + conversationId, + index = 0, + fullWidth = false, +}: PendingSteersProps): ReactElement | null { const localize = useLocalize(); - const { useToast, usePendingSteers, useSteerEscalating, usePaneConversationId } = - useMessagePartsHost(); + const { useToast, useSteerEscalating, usePaneConversationId } = useMessagePartsHost(); const showToast = useToast(); - const steers = usePendingSteers(conversationId); + const steers = useAtomValue(pendingSteersByConvoId(conversationId)); const { retry, sendAsNew } = useSteerRecovery(conversationId); const cancelSteer = useSteerCancel(conversationId); const escalate = useSteerEscalate(conversationId); @@ -47,33 +69,14 @@ function PendingSteers({ conversationId, index = 0, fullWidth = false }: Pending const rehomeSteer = useSteerRehome(conversationId); const [movingId, setMovingId] = useState(null); const escalating = useSteerEscalating(conversationId); - /* Resolve the cache to the branch the user is viewing before applying the - shared pause predicate. The cache contains every sibling branch, while - `useLatestMessage` follows the same selection state as the message view. */ - const queryClient = useQueryClient(); - const cachedMessages = - queryClient.getQueryData([QueryKeys.messages, conversationId]) ?? []; - const latestMessage = useLatestMessage(index, conversationId); const paneConversationId = usePaneConversationId(index); - const { data: fallbackPaused } = useCachedMessages(conversationId, hasLiveRunPause); - /* A one-message cache is necessarily the active branch. Until the - conversation atom reaches useLatestMessage, retain the query's established - single-branch result so a live question cannot re-enable escalation. The - branch tail is keyed by the pane's conversation, which can still name the - previous chat while this one renders from cache; until the pane owns this - conversation, a pause on any branch keeps escalation off. */ - const resolvePaused = (): boolean => { - if (cachedMessages.length > 1) { - if (paneConversationId === conversationId && latestMessage != null) { - return hasLiveRunPause(latestMessage); - } - return cachedMessages.some((message) => hasLiveRunPause(message)); - } - if (fallbackPaused != null) { - return fallbackPaused; - } - return cachedMessages.length === 1 && hasLiveRunPause(cachedMessages[0]); - }; + const cached = useMessagesHost().useConversationMessages(conversationId, true); + const latestMessage = useBranchTail( + paneConversationId, + paneConversationId ? conversationId : null, + ); + const cachedMessages = cached ?? []; + const fallbackPaused = cached == null ? undefined : hasLiveRunPause(cached); /** Arming removes the control that was activated, so the row's Cancel button * (which survives the `preempt` flip) is where keyboard focus goes next. */ const cancelButtonRefs = useRef(new Map()); @@ -85,7 +88,13 @@ function PendingSteers({ conversationId, index = 0, fullWidth = false }: Pending if (steers.length === 0) { return null; } - const paused = resolvePaused(); + const paused = resolvePaused( + cachedMessages, + paneConversationId, + conversationId, + latestMessage, + fallbackPaused, + ); const queueSteer = async (steer: (typeof steers)[number]) => { if (movingId != null) { @@ -134,7 +143,7 @@ function PendingSteers({ conversationId, index = 0, fullWidth = false }: Pending
{steers.map((steer) => { @@ -266,4 +275,6 @@ function PendingSteers({ conversationId, index = 0, fullWidth = false }: Pending ); } -export default memo(PendingSteers); +const MemoizedPendingSteers: NamedExoticComponent = memo(PendingSteers); + +export default MemoizedPendingSteers; diff --git a/packages/chat/src/components/messages/PendingTurn.tsx b/packages/chat/src/components/messages/PendingTurn.tsx index 918379e659..93c6b33946 100644 --- a/packages/chat/src/components/messages/PendingTurn.tsx +++ b/packages/chat/src/components/messages/PendingTurn.tsx @@ -1,13 +1,17 @@ import { useCallback, useEffect, useMemo, useRef } from 'react'; import { useAtomValue } from 'jotai'; import { useLocalize } from '@librechat/client'; -import type { ReactElement, ReactNode, RefObject } from 'react'; import type { TMessage } from 'librechat-data-provider'; +import type { ReactElement, RefObject } from 'react'; import { hasRevealSuccessor, buildRevealedMessage } from '../../react/steering/useQueuedTurnReveal'; import { getHeaderPrefixForScreenReader, getMessageAriaLabel } from './labels'; import { useQueuedTurnPortal } from '../composer/steering/QueuedTurnPortal'; import { revealedQueuedTurnFamily } from '../../react/steer/rows'; +import { useMessagesHost } from '../../react/messages/host'; +import { useChatContext } from '../../react/chat/context'; +import { useMessagePartsHost } from '../../react/host'; import { messageFooterClasses } from './styles'; +import Container from '../parts/Container'; import MessageRow from './MessageRow'; import SubRow from './SubRow'; @@ -19,34 +23,28 @@ export type PendingTurnProps = { scrollableRef?: RefObject; messages?: TMessage[] | null; maximizeChatSpace?: boolean; - /** The routed conversation: its reveal is the turn drawn. */ - conversationId: string; - /** The thread's current tail; the turn is drawn only after the response it follows. */ - latestMessageId?: string; - /** Who the turn is attributed to. */ - label: string; - /** The author's icon. */ - icon: ReactNode; - /** The turn's text, drawn inside the row (the host decides markdown and wrappers). */ - renderBody: (message: TMessage, text: string) => ReactNode; }; /** * The queued follow-up the server is about to admit, drawn as the user turn 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. + * + * The pane context names the conversation, including while a warm navigation still shows the + * previous chat there. The label, icon and text come from the hosts. */ export default function PendingTurn({ scrollableRef, messages, maximizeChatSpace = false, - conversationId, - latestMessageId, - label, - icon, - renderBody, }: PendingTurnProps): ReactElement | null { const localize = useLocalize(); + const { conversation, latestMessageId } = useChatContext(); + const conversationId = conversation?.conversationId ?? ''; + const { useUser, useUserTextPreferences, renderMarkdown } = useMessagePartsHost(); + const renderMessageIcon = useMessagesHost().renderMessageIcon; + const user = useUser(); + const { usernameDisplay, enableUserMsgMarkdown } = useUserTextPreferences(); const reveal = useAtomValue(revealedQueuedTurnFamily(conversationId)); const setPortalTarget = useQueuedTurnPortal()?.setTarget; const clientRequestId = reveal?.clientRequestId; @@ -93,10 +91,28 @@ export default function PendingTurn({ row.scrollIntoView({ block: 'end', behavior: reduceMotion ? 'auto' : 'smooth' }); }, [shown, scrollableRef]); - if (!shown) { + if (!shown || message == null || reveal == null) { return null; } + const label = usernameDisplay + ? (user?.name ?? '') || (user?.username ?? '') + : localize('com_user_message'); + const icon = renderMessageIcon({ + iconData: { + endpoint: conversation?.endpoint, + model: conversation?.model ?? undefined, + modelLabel: label, + isCreatedByUser: true, + }, + }); + const bodyClass = [ + 'markdown prose message-content light text-text-primary w-full break-words', + enableUserMsgMarkdown ? '' : 'whitespace-pre-wrap', + ] + .filter((part) => part !== '') + .join(' '); + return (
} > - {renderBody(message, reveal.text)} + +
+ {enableUserMsgMarkdown + ? renderMarkdown({ + content: reveal.text, + variant: 'lite', + isLatestMessage: false, + }) + : reveal.text} +
+
diff --git a/packages/chat/src/components/messages/__tests__/MessagesView.spec.tsx b/packages/chat/src/components/messages/__tests__/MessagesView.spec.tsx index 7b42a90ad3..ab2aa989e2 100644 --- a/packages/chat/src/components/messages/__tests__/MessagesView.spec.tsx +++ b/packages/chat/src/components/messages/__tests__/MessagesView.spec.tsx @@ -1,7 +1,7 @@ /** * @jest-environment jsdom */ -import { useRef } from 'react'; +import { useRef, useState } from 'react'; import { QueryKeys } from 'librechat-data-provider'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; @@ -9,10 +9,12 @@ import type { TMessage } from 'librechat-data-provider'; import type { ConversationSeenSource, MessagesHost } from '../../../react/messages/host'; import type { MessagesScrollButtonProps, MessagesViewProps } from '../MessagesView'; import type { ChatContract } from '../../../react/chat/contract'; -import type { MessagePartsHost } from '../../../react/host'; +import { createMessagePartsHost } from '../../../__fixtures__/partsHost'; import { createMessagesHost } from '../../../__fixtures__/messagesHost'; import { MessagesHostProvider } from '../../../react/messages/host'; +import { createSteerHost } from '../../../__fixtures__/steerHost'; import { MessagePartsHostProvider } from '../../../react/host'; +import { SteerHostProvider } from '../../../react/steer/host'; import { ChatContext } from '../../../react/chat/context'; import { initEnglish } from '../../../__fixtures__/i18n'; import MessagesView from '../MessagesView'; @@ -21,7 +23,7 @@ beforeAll(initEnglish); const tree = [{ messageId: 'reply-1', conversationId: 'convo-1' }] as TMessage[]; -const partsHost = { useFontSize: () => 'text-base' } as unknown as MessagePartsHost; +const partsHost = createMessagePartsHost({ useFontSize: () => 'text-base' }); const RESPONDED_AT = '2026-11-03T10:00:00.000Z'; @@ -82,23 +84,25 @@ function renderView(props: Partial, host: MessagesHost, chat queryClient.setQueryData([QueryKeys.messages, 'convo-1'], tree); const view = (next: Partial) => ( - - - - ( -
    - )} - {...props} - {...next} - /> - - - + + + + + ( +
      + )} + {...props} + {...next} + /> + + + + ); const result = render(view({})); @@ -125,6 +129,26 @@ describe('MessagesView', () => { expect(renderThread).not.toHaveBeenCalled(); }); + it('takes the thread mode from the host unless the caller sets it', () => { + const renderThread = jest.fn((_props: { flat?: boolean }) => null); + const { rerenderView } = renderView( + { renderThread }, + createHost({ useFlatThread: () => false }).host, + ); + + expect(renderThread).toHaveBeenLastCalledWith(expect.objectContaining({ flat: false })); + + rerenderView({ flatThread: true }); + expect(renderThread).toHaveBeenLastCalledWith(expect.objectContaining({ flat: true })); + }); + + it('keeps the host hook order when the thread mode prop comes and goes', () => { + const host = createHost({ useFlatThread: () => useState(false)[0] }).host; + const { rerenderView } = renderView({ flatThread: true }, host); + + expect(() => rerenderView({ flatThread: undefined })).not.toThrow(); + }); + it('keys the thread and the rail to the rendered tree, not the lagging conversation', () => { const renderNav = jest.fn(() => null); const destination = [{ messageId: 'reply-2', conversationId: 'convo-2' }] as TMessage[]; diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/PendingSteers.test.tsx b/packages/chat/src/components/messages/__tests__/PendingSteers.spec.tsx similarity index 72% rename from client/src/components/Chat/Messages/Content/Parts/__tests__/PendingSteers.test.tsx rename to packages/chat/src/components/messages/__tests__/PendingSteers.spec.tsx index 7e01ef9400..494151c86a 100644 --- a/client/src/components/Chat/Messages/Content/Parts/__tests__/PendingSteers.test.tsx +++ b/packages/chat/src/components/messages/__tests__/PendingSteers.spec.tsx @@ -1,57 +1,59 @@ -import React from 'react'; -import { RecoilRoot } from 'recoil'; -import { MemoryRouter } from 'react-router-dom'; +/** + * @jest-environment jsdom + */ +import { useEffect } from 'react'; import { Provider as JotaiProvider, createStore } from 'jotai'; -import { pendingSteersByConvoId } from '@librechat/chat/react'; -import { hasLiveRunPause, applyPendingAction } from '@librechat/chat'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; import { Constants, ContentTypes, QueryKeys } from 'librechat-data-provider'; -import { render, screen, fireEvent, waitFor, act } from '@testing-library/react'; -import type { Agents, TConversation, TMessage } from 'librechat-data-provider'; -import type { PendingSteer } from '@librechat/chat'; -import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/state'; -import { setAppPartRenderers } from '../slots'; +import type { Agents, TMessage } from 'librechat-data-provider'; +import type { + PendingSteer, + ChatSteerResult, + ChatArmSteerResult, + ChatCancelSteerResult, +} from '../../../core'; +import type { RestoreToComposer } from '../../../react/steer/restore'; +import { + pendingSteersByConvoId, + activeGenerationCreatedAtByConvoId, + activeGenerationProtocolVersionByConvoId, +} from '../../../react/steer/atoms'; +import { ComposerRestoreProvider, useComposerRestoreHost } from '../../../react/steer/restore'; +import { createMessagePartsHost } from '../../../__fixtures__/partsHost'; +import { createMessagesHost } from '../../../__fixtures__/messagesHost'; +import { queuedMessagesByConvoId } from '../../../react/steer/queue'; +import { siblingIdxFamily, siblingKey } from '../../../react/thread'; +import { hasLiveRunPause, applyPendingAction } from '../../../core'; +import { MessagesHostProvider } from '../../../react/messages/host'; +import { createSteerHost } from '../../../__fixtures__/steerHost'; +import { MessagePartsHostProvider } from '../../../react/host'; +import { SteerHostProvider } from '../../../react/steer/host'; import PendingSteers from '../PendingSteers'; -import store from '~/store'; -const mockRetry = jest.fn(); -const mockSendAsNew = jest.fn(); -const mockEscalate = jest.fn(); -const mockMoveToQueue = jest.fn(); -const mockRehome = jest.fn(() => 'composer' as const); -const mockShowToast = jest.fn(); +const cancelSteer = jest.fn(async (): Promise => ({ removed: true })); +const armSteer = jest.fn(async (): Promise => ({ armed: true })); +const steerMessage = jest.fn( + (): Promise => new Promise(() => undefined), +); +const showToast = jest.fn(); jest.mock('@librechat/client', () => ({ ...jest.requireActual('@librechat/client'), useLocalize: () => (key: string) => key, - useToastContext: () => ({ showToast: mockShowToast }), })); -jest.mock('~/hooks', () => ({ - useLocalize: () => (key: string) => key, -})); - -jest.mock('@librechat/chat/react', () => ({ - ...jest.requireActual('@librechat/chat/react'), - useSteerEscalate: () => mockEscalate, - useSteerCancel: () => jest.fn(), - useSteerMoveToQueue: () => mockMoveToQueue, - useSteerRehome: () => mockRehome, - useSteerRecovery: () => ({ retry: mockRetry, sendAsNew: mockSendAsNew }), -})); - -jest.mock('~/Providers', () => ({ - useShareContext: () => ({}), - useFileMapContext: () => ({}), -})); - -/** The parts barrel registers the app's renderers; this spec loads PendingSteers alone. */ -setAppPartRenderers({ - renderMarkdown: ({ content }) => {content}, - renderAgentIcon: () => null, - renderImage: () => null, - renderFilePreview: () => null, -}); +function PublishRestore({ restore }: { restore?: RestoreToComposer }) { + const host = useComposerRestoreHost(); + useEffect(() => { + if (restore == null) { + return; + } + host.publish(restore); + return () => host.publish(null); + }, [host, restore]); + return null; +} const CONVO_ID = 'convo-1'; @@ -72,9 +74,8 @@ function renderPending( /** Pane 0 still names the previous chat while this one renders from cache. */ stalePaneConversationId?: string, fullWidth = false, + restore?: RestoreToComposer, ) { - /* The escalation control resolves the cache through the branch-aware - latest-message hook, using the same providers the chat view supplies. */ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity }, @@ -84,6 +85,8 @@ function renderPending( queryClient.setQueryData([QueryKeys.messages, CONVO_ID], messages ?? []); const jotaiStore = createStore(); jotaiStore.set(pendingSteersByConvoId(CONVO_ID), steers); + jotaiStore.set(activeGenerationCreatedAtByConvoId(CONVO_ID), 1); + jotaiStore.set(activeGenerationProtocolVersionByConvoId(CONVO_ID), 1); if (activeSiblingIndex != null) { jotaiStore.set( siblingIdxFamily( @@ -94,34 +97,54 @@ function renderPending( activeSiblingIndex, ); } - return render( - - - - { - set(store.conversationByIndex(0), { - conversationId: pane?.otherConversationId ?? stalePaneConversationId ?? CONVO_ID, - } as TConversation); - if (pane != null) { - set(store.conversationByIndex(pane.index), { - conversationId: CONVO_ID, - } as TConversation); - } - }} - > - - - - - , + const paneIds: Record = { + 0: pane?.otherConversationId ?? stalePaneConversationId ?? CONVO_ID, + }; + if (pane != null) { + paneIds[pane.index] = CONVO_ID; + } + const partsHost = createMessagePartsHost({ + useToast: () => showToast, + usePaneConversationId: (paneIndex) => paneIds[paneIndex] ?? null, + renderMarkdown: ({ content }) => {content}, + }); + const messagesHost = createMessagesHost({ + useConversationMessages: (id) => + queryClient.getQueryData([QueryKeys.messages, id ?? '']), + }); + const steerHost = createSteerHost({ + useCancelSteer: () => cancelSteer, + useArmSteer: () => armSteer, + useSteerMessageAsync: () => steerMessage, + }); + const view = render( + + + + + + + + + + + + + + , ); + return { ...view, jotaiStore }; } describe('PendingSteers', () => { beforeEach(() => { jest.clearAllMocks(); - mockMoveToQueue.mockResolvedValue('reclaimed'); + cancelSteer.mockResolvedValue({ removed: true }); + armSteer.mockResolvedValue({ armed: true }); }); it('renders nothing with no pending steers', () => { @@ -255,21 +278,29 @@ describe('PendingSteers', () => { it('reclaims an acknowledged steer before moving it to the queue', async () => { const steer = pending({ status: 'pending', steerId: 's-ack' }); - renderPending([steer]); + const { jotaiStore } = renderPending([steer]); fireEvent.click(screen.getByRole('button', { name: 'com_ui_convert_to_queue' })); - await waitFor(() => expect(mockMoveToQueue).toHaveBeenCalledWith(steer)); + await waitFor(() => + expect(cancelSteer).toHaveBeenCalledWith( + expect.objectContaining({ conversationId: CONVO_ID, steerId: steer.steerId }), + ), + ); + await waitFor(() => expect(screen.queryByRole('listitem')).not.toBeInTheDocument()); + expect(jotaiStore.get(queuedMessagesByConvoId(CONVO_ID)).map((item) => item.text)).toContain( + steer.text, + ); }); it('reports when a steer reached the agent before it could be reclaimed', async () => { - mockMoveToQueue.mockResolvedValue('applied'); + cancelSteer.mockResolvedValue({ removed: false }); renderPending([pending({ status: 'pending' })]); fireEvent.click(screen.getByRole('button', { name: 'com_ui_convert_to_queue' })); await waitFor(() => - expect(mockShowToast).toHaveBeenCalledWith({ + expect(showToast).toHaveBeenCalledWith({ message: 'com_ui_steer_already_applied', status: 'info', }), @@ -279,26 +310,50 @@ describe('PendingSteers', () => { it('retries the failed steer by id', () => { renderPending([pending({ status: 'failed', steerId: 's-failed' })]); fireEvent.click(screen.getByText('com_ui_retry')); - expect(mockRetry).toHaveBeenCalledWith('s-failed'); - expect(mockSendAsNew).not.toHaveBeenCalled(); + expect(steerMessage).toHaveBeenCalledWith( + expect.objectContaining({ + conversationId: CONVO_ID, + text: 'change of plan', + clientSteerId: 's-failed', + }), + ); }); it('sends the failed steer as new by id', () => { - renderPending([pending({ status: 'failed', steerId: 's-failed' })]); + const { jotaiStore } = renderPending([pending({ status: 'failed', steerId: 's-failed' })]); fireEvent.click(screen.getByText('com_ui_send_as_new')); - expect(mockSendAsNew).toHaveBeenCalledWith('s-failed'); - expect(mockRetry).not.toHaveBeenCalled(); + expect(steerMessage).not.toHaveBeenCalled(); + expect(screen.queryByText('com_ui_retry')).not.toBeInTheDocument(); + expect(jotaiStore.get(queuedMessagesByConvoId(CONVO_ID)).map((item) => item.text)).toContain( + 'change of plan', + ); }); it('returns a definitively failed steer whole so it can be corrected', () => { + const restore = jest.fn(() => true); const steer = pending({ status: 'failed', steerId: 's-failed', quotes: ['excerpt'] }); - renderPending([steer]); + renderPending([steer], undefined, undefined, undefined, undefined, false, restore); fireEvent.click(screen.getByText('com_ui_edit')); - /* Queued as a fallback it must wait for an explicit send: the server - refused this payload, so the run-end drain must not send it anyway. */ - expect(mockRehome).toHaveBeenCalledWith(steer, { rejectedByServer: true }); - expect(mockSendAsNew).not.toHaveBeenCalled(); - expect(mockRetry).not.toHaveBeenCalled(); + expect(restore).toHaveBeenCalledWith( + steer.text, + undefined, + expect.objectContaining({ quotes: ['excerpt'] }), + CONVO_ID, + ); + expect(showToast).not.toHaveBeenCalled(); + expect(steerMessage).not.toHaveBeenCalled(); + }); + + it('queues a rejected steer for an explicit send when the composer will not take it', () => { + const { jotaiStore } = renderPending([ + pending({ status: 'failed', steerId: 's-failed', quotes: ['excerpt'] }), + ]); + fireEvent.click(screen.getByText('com_ui_edit')); + expect(showToast).toHaveBeenCalledWith({ + message: 'com_ui_steer_moved_to_queue', + status: 'info', + }); + expect(jotaiStore.get(queuedMessagesByConvoId(CONVO_ID))[0]?.needsExplicitSend).toBe(true); }); /* An uncertain delivery may still be held by the server, so every action that @@ -317,30 +372,27 @@ describe('PendingSteers', () => { expect(screen.getByTestId('steer-escalate-now')).toBeEnabled(); }); - it('arms the steer by id, carrying its own generation', () => { + it('arms the steer by id, carrying its own generation', async () => { renderPending([pending({ status: 'pending', steerId: 's-ack', generationCreatedAt: 4141 })]); fireEvent.click(screen.getByTestId('steer-escalate-now')); - expect(mockEscalate).toHaveBeenCalledWith( - { + await waitFor(() => + expect(armSteer).toHaveBeenCalledWith({ + conversationId: CONVO_ID, steerId: 's-ack', generationCreatedAt: 4141, - }, - expect.any(Function), + }), ); }); /* Arming removes the control that was just activated, so a keyboard user would be dropped on the document body in the middle of the thread. */ - it('moves focus to the row`s cancel action once the arm is confirmed', () => { + it('moves focus to the row`s cancel action once the arm is confirmed', async () => { renderPending([pending({ status: 'pending', steerId: 's-ack' })]); fireEvent.click(screen.getByTestId('steer-escalate-now')); - const onArmed = mockEscalate.mock.calls[0][1] as () => void; - act(() => { - onArmed(); - }); - - expect(screen.getByRole('button', { name: 'com_ui_cancel' })).toHaveFocus(); + await waitFor(() => + expect(screen.getByRole('button', { name: 'com_ui_cancel' })).toHaveFocus(), + ); }); it.each([ diff --git a/packages/chat/src/components/messages/__tests__/PendingTurn.spec.tsx b/packages/chat/src/components/messages/__tests__/PendingTurn.spec.tsx index 74d033092a..1866a848fb 100644 --- a/packages/chat/src/components/messages/__tests__/PendingTurn.spec.tsx +++ b/packages/chat/src/components/messages/__tests__/PendingTurn.spec.tsx @@ -1,11 +1,20 @@ /** * @jest-environment jsdom */ +import { EModelEndpoint } from 'librechat-data-provider'; import { act, render, screen } from '@testing-library/react'; import { Provider as JotaiProvider, createStore } from 'jotai'; -import type { TMessage } from 'librechat-data-provider'; +import type { TConversation, TMessage } from 'librechat-data-provider'; +import type { ReactNode } from 'react'; +import type { MessagesHost } from '../../../react/messages/host'; +import type { ChatContract } from '../../../react/chat/contract'; import type { RevealedQueuedTurn } from '../../../react'; +import { createMessagePartsHost } from '../../../__fixtures__/partsHost'; +import { createMessagesHost } from '../../../__fixtures__/messagesHost'; import { revealedQueuedTurnFamily } from '../../../react/steer/rows'; +import { MessagesHostProvider } from '../../../react/messages/host'; +import { MessagePartsHostProvider } from '../../../react/host'; +import { ChatContext } from '../../../react/chat/context'; import PendingTurn from '../PendingTurn'; jest.mock('@librechat/client', () => ({ @@ -16,6 +25,12 @@ jest.mock('@librechat/client', () => ({ 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 => ({ clientRequestId: 'client-request-1', parentMessageId: RESPONSE_ID, @@ -28,28 +43,57 @@ function renderPendingTurn({ revealed, latestMessageId = RESPONSE_ID, messages, + usernameDisplay = false, + userName = 'Danny', + enableUserMsgMarkdown = false, + renderMarkdown = ({ content }: { content: string }) => ( + {content} + ), + renderMessageIcon = jest.fn(() => ), }: { revealed?: RevealedQueuedTurn | null; latestMessageId?: string; messages?: TMessage[]; -}) { + usernameDisplay?: boolean; + userName?: string; + enableUserMsgMarkdown?: boolean; + renderMarkdown?: (props: { content: string }) => ReactNode; + renderMessageIcon?: MessagesHost['renderMessageIcon']; +} = {}) { const store = createStore(); if (revealed != null) { store.set(revealedQueuedTurnFamily(CONVO_ID), revealed); } + const partsHost = createMessagePartsHost({ + useUser: () => ({ name: userName, username: 'danny' }), + useUserTextPreferences: () => ({ + enableUserMsgMarkdown, + collapseLongUserMessages: false, + usernameDisplay, + }), + renderMarkdown, + }); + const messagesHost = createMessagesHost({ renderMessageIcon }); const rendered = render( - } - renderBody={(_message, text) => {text}} - /> + + + + + + + , ); - return { ...rendered, store }; + return { ...rendered, store, renderMessageIcon }; } describe('PendingTurn', () => { @@ -59,11 +103,56 @@ describe('PendingTurn', () => { const row = screen.getByTestId('pending-turn'); expect(row.querySelector('.message-render')).not.toBeNull(); expect(row.querySelector('.user-turn')).not.toBeNull(); - expect(screen.getByTestId('body')).toHaveTextContent('queued follow-up'); + expect(row).toHaveTextContent('queued follow-up'); expect(screen.getByRole('status')).toHaveTextContent('com_ui_queued_turn_starting'); expect(container.querySelectorAll('button')).toHaveLength(0); }); + it('labels the turn with the signed-in name when the viewer asks for it', () => { + const { renderMessageIcon } = renderPendingTurn({ + revealed: reveal(), + usernameDisplay: true, + }); + + expect(screen.getByRole('heading', { level: 2 })).toHaveTextContent('Danny'); + expect(renderMessageIcon).toHaveBeenCalledWith({ + iconData: { + endpoint: EModelEndpoint.agents, + model: 'gpt-x', + modelLabel: 'Danny', + isCreatedByUser: true, + }, + }); + }); + + it('uses the generic user label when names are hidden', () => { + renderPendingTurn({ revealed: reveal(), usernameDisplay: false }); + + expect(screen.getByRole('heading', { level: 2 })).toHaveTextContent('com_user_message'); + }); + + it('renders plain text unless the viewer wants user markdown', () => { + const { container, renderMessageIcon: plainIcon } = renderPendingTurn({ + revealed: reveal(), + }); + expect(container.querySelector('.whitespace-pre-wrap')).not.toBeNull(); + expect(screen.queryByTestId('markdown')).toBeNull(); + expect(plainIcon).toHaveBeenCalled(); + + const markdown = jest.fn(({ content }: { content: string }) => ( + {content} + )); + renderPendingTurn({ + revealed: reveal(), + enableUserMsgMarkdown: true, + renderMarkdown: markdown, + }); + expect(screen.getByTestId('markdown')).toHaveTextContent('queued follow-up'); + expect(markdown).toHaveBeenCalledWith( + expect.objectContaining({ content: 'queued follow-up', variant: 'lite' }), + ); + }); + it('renders nothing without a reveal', () => { renderPendingTurn({ revealed: null }); expect(screen.queryByTestId('pending-turn')).toBeNull(); diff --git a/packages/chat/src/components/messages/__tests__/pendingDefaults.spec.tsx b/packages/chat/src/components/messages/__tests__/pendingDefaults.spec.tsx new file mode 100644 index 0000000000..ddda626877 --- /dev/null +++ b/packages/chat/src/components/messages/__tests__/pendingDefaults.spec.tsx @@ -0,0 +1,123 @@ +/** + * @jest-environment jsdom + */ +import { render, screen } from '@testing-library/react'; +import { Provider as JotaiProvider, createStore } from 'jotai'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import type { TMessage } from 'librechat-data-provider'; +import type { RevealedQueuedTurn } from '../../../react/steer/rows'; +import type { ChatContract } from '../../../react/chat/contract'; +import type { PendingSteer } from '../../../core'; +import { createMessagePartsHost } from '../../../__fixtures__/partsHost'; +import { createMessagesHost } from '../../../__fixtures__/messagesHost'; +import { revealedQueuedTurnFamily } from '../../../react/steer/rows'; +import { pendingSteersByConvoId } from '../../../react/steer/atoms'; +import { MessagesHostProvider } from '../../../react/messages/host'; +import { createSteerHost } from '../../../__fixtures__/steerHost'; +import { MessagePartsHostProvider } from '../../../react/host'; +import { SteerHostProvider } from '../../../react/steer/host'; +import { ChatContext } from '../../../react/chat/context'; +import { initEnglish } from '../../../__fixtures__/i18n'; +import MessagesView from '../MessagesView'; + +beforeAll(() => { + Element.prototype.scrollIntoView = () => undefined; + return initEnglish(); +}); + +const CONVO_ID = 'shared-convo'; +const RESPONSE_ID = 'reply-1'; + +const messages = [ + { messageId: RESPONSE_ID, conversationId: CONVO_ID, text: 'shared reply' }, +] as TMessage[]; + +const reveal: RevealedQueuedTurn = { + clientRequestId: 'queued-request', + parentMessageId: RESPONSE_ID, + text: 'queued follow-up', + revealedAt: '2026-09-14T00:00:00.000Z', +}; + +const steer: PendingSteer = { + steerId: 's1', + text: 'change of plan', + status: 'sending', + createdAt: 1, +}; + +const chat: ChatContract = Object.assign( + { + index: 0, + isSubmitting: false, + latestMessageId: RESPONSE_ID, + latestMessageDepth: 0, + messagesKey: CONVO_ID, + } as ChatContract, + { + abortScroll: false, + setAbortScroll: () => undefined, + conversation: { + conversationId: CONVO_ID, + endpoint: null, + title: null, + createdAt: '2026-09-14T00:00:00.000Z', + updatedAt: '2026-09-14T00:00:00.000Z', + }, + }, +); + +function renderList(withSteerHost: boolean) { + const store = createStore(); + store.set(pendingSteersByConvoId(CONVO_ID), [steer]); + store.set(revealedQueuedTurnFamily(CONVO_ID), reveal); + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const list = ( + + + + + + ( +
        + {messagesTree?.map((message) => ( +
      1. {message.text}
      2. + ))} +
      + )} + /> +
      +
      +
      +
      +
      + ); + return render( + withSteerHost ? {list} : list, + ); +} + +describe('MessagesView pending defaults', () => { + it('renders the thread and no pending rows when no steer host is mounted', () => { + renderList(false); + + expect(screen.getByText('shared reply')).toBeInTheDocument(); + expect(screen.queryByTestId('pending-turn')).not.toBeInTheDocument(); + expect(screen.queryByTestId('pending-steers')).not.toBeInTheDocument(); + }); + + it('renders the pending turn and pending steers when a steer host is mounted', () => { + renderList(true); + + expect(screen.getByText('shared reply')).toBeInTheDocument(); + expect(screen.getByTestId('pending-turn')).toHaveTextContent('queued follow-up'); + expect(screen.getByTestId('pending-steers')).toHaveTextContent('change of plan'); + }); +}); diff --git a/packages/chat/src/components/messages/thread/__tests__/Thread.spec.tsx b/packages/chat/src/components/messages/thread/__tests__/Thread.spec.tsx index a7a6345fa8..4b227b76e2 100644 --- a/packages/chat/src/components/messages/thread/__tests__/Thread.spec.tsx +++ b/packages/chat/src/components/messages/thread/__tests__/Thread.spec.tsx @@ -12,7 +12,9 @@ import type { MessagePartsHost } from '../../../../react/host'; import type { MessagesViewProps } from '../../MessagesView'; import { createMessagesHost } from '../../../../__fixtures__/messagesHost'; import { MessagesHostProvider } from '../../../../react/messages/host'; +import { createSteerHost } from '../../../../__fixtures__/steerHost'; import { MessagePartsHostProvider } from '../../../../react/host'; +import { SteerHostProvider } from '../../../../react/steer/host'; import { ChatContext } from '../../../../react/chat/context'; import { initEnglish } from '../../../../__fixtures__/i18n'; import { resolveThreadRows } from '../../../../core/thread'; @@ -115,18 +117,20 @@ function renderThread( const view = (next: Partial) => ( - - - - - - - + + + + + + + + + ); diff --git a/packages/chat/src/components/pane/__tests__/messages.spec.tsx b/packages/chat/src/components/pane/__tests__/messages.spec.tsx index 52b7bdb97f..cd84aec871 100644 --- a/packages/chat/src/components/pane/__tests__/messages.spec.tsx +++ b/packages/chat/src/components/pane/__tests__/messages.spec.tsx @@ -37,9 +37,8 @@ function MessageNav({ conversationId }: { conversationId?: string | null }) { return
      ; } -/** The app's slots, the way ChatView fills them, with each piece reduced to what it was handed. */ +/** A host's optional replacements. Flat thread mode comes from the messages host. */ const slots = (): ChatScreenMessagesSlots => ({ - flatThread: mockFlatThread, renderPendingTurn: () => null, renderPendingSteers: ({ conversationId, fullWidth }) => (
      null, useMaximizeChatSpace: () => false, + useFlatThread: () => mockFlatThread, useHideSelectedAuthor: () => false, useAgentsMap: () => undefined, renderMessageBody: ({ message }) =>
      {message.messageId}
      , diff --git a/packages/chat/src/components/pane/messages.tsx b/packages/chat/src/components/pane/messages.tsx index 3388b6a100..8970575b71 100644 --- a/packages/chat/src/components/pane/messages.tsx +++ b/packages/chat/src/components/pane/messages.tsx @@ -5,15 +5,12 @@ import { MessagesViewProvider } from '../../react/messages/view'; import { useChatSurface } from '../../react/subagents/surface'; import MessagesView from '../messages/MessagesView'; -/** The list's slots the app fills: thread mode, pending pieces, scroll control and rail. */ +/** The list's slots a host may replace: the thread, pending pieces, scroll control and rail. + * Flat thread mode is a host setting (`useFlatThread`), and the pending pieces render + * themselves when a slot is absent. */ export type ChatScreenMessagesSlots = Pick< MessagesViewProps, - | 'flatThread' - | 'renderThread' - | 'renderPendingTurn' - | 'renderPendingSteers' - | 'renderScrollButton' - | 'renderNav' + 'renderThread' | 'renderPendingTurn' | 'renderPendingSteers' | 'renderScrollButton' | 'renderNav' >; /** What the message list receives: the session's messages and the tree built from them. */ diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.ts index 3c238e6c34..46957ec9de 100644 --- a/packages/chat/src/react.ts +++ b/packages/chat/src/react.ts @@ -78,7 +78,7 @@ export { abortScrollFamily, launchedConversationFamily, } from './react/generation'; -export { SteerHostProvider, useSteerHost } from './react/steer/host'; +export { SteerHostProvider, useOptionalSteerHost, useSteerHost } from './react/steer/host'; export type { SteerHost, SteerPane, diff --git a/packages/chat/src/react/messages/host.tsx b/packages/chat/src/react/messages/host.tsx index 0ff6257a9f..9e3658ac15 100644 --- a/packages/chat/src/react/messages/host.tsx +++ b/packages/chat/src/react/messages/host.tsx @@ -232,6 +232,9 @@ export interface MessagesHost { renderMessageIcon: (props: MessageIconProps) => ReactNode; /** Whether rows drop the reading-width cap and fill the pane. */ useMaximizeChatSpace: () => boolean; + /** Whether the thread renders as a flat row list. The flat renderer is the default; + * an app turns it off for the recursive tree. */ + useFlatThread: () => boolean; /** Whether a response by the agent the header's model selector shows drops its avatar and name * (`interface.messageAuthor: whenDifferent`). */ useHideSelectedAuthor: () => boolean; @@ -297,6 +300,7 @@ const fallbackHost: MessagesHost = { useMessageFeedback: () => noFeedback, renderMessageIcon: () => null, useMaximizeChatSpace: () => false, + useFlatThread: () => true, useHideSelectedAuthor: () => false, useAgentsMap: () => undefined, renderMessageBody: () => null, diff --git a/packages/chat/src/react/steer/__tests__/host.spec.tsx b/packages/chat/src/react/steer/__tests__/host.spec.tsx index 58371fb4ab..37b5510700 100644 --- a/packages/chat/src/react/steer/__tests__/host.spec.tsx +++ b/packages/chat/src/react/steer/__tests__/host.spec.tsx @@ -4,7 +4,7 @@ import { renderHook } from '@testing-library/react'; import type { ReactNode } from 'react'; import type { SteerHost } from '../host'; -import { SteerHostProvider, useSteerHost } from '../host'; +import { SteerHostProvider, useOptionalSteerHost, useSteerHost } from '../host'; const createHost = (label: string): SteerHost => ({ useSteerMessage: () => () => undefined, @@ -57,4 +57,18 @@ describe('useSteerHost', () => { ); consoleError.mockRestore(); }); + + it('returns null from the optional lookup when no provider is mounted', () => { + const { result } = renderHook(() => useOptionalSteerHost()); + expect(result.current).toBeNull(); + }); + + it('returns the provided host from the optional lookup', () => { + const host = createHost('provided'); + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + const { result } = renderHook(() => useOptionalSteerHost(), { wrapper }); + expect(result.current).toBe(host); + }); }); diff --git a/packages/chat/src/react/steer/host.tsx b/packages/chat/src/react/steer/host.tsx index b1b7f1c1d8..c64b637cf7 100644 --- a/packages/chat/src/react/steer/host.tsx +++ b/packages/chat/src/react/steer/host.tsx @@ -149,8 +149,14 @@ export function SteerHostProvider({ return {children}; } +/** The nearest steer host, or null when this tree has none. A surface that can render without + * steering, such as a shared conversation, uses this and leaves the pending rows unmounted. */ +export function useOptionalSteerHost(): SteerHost | null { + return useContext(SteerHostContext); +} + export function useSteerHost(): SteerHost { - const host = useContext(SteerHostContext); + const host = useOptionalSteerHost(); if (host == null) { throw new Error('The steer hooks need a SteerHostProvider above them.'); } diff --git a/packages/chat/test/consumer.spec.tsx b/packages/chat/test/consumer.spec.tsx index aec125886c..4acfa64da2 100644 --- a/packages/chat/test/consumer.spec.tsx +++ b/packages/chat/test/consumer.spec.tsx @@ -33,10 +33,12 @@ import { MessagePartIndex, StreamHostProvider, ChatSurfaceProvider, + SteerHostProvider, MessagesHostProvider, MessagePartsHostProvider, ParentSubagentsProvider, } from '@librechat/chat/react'; +import { createSteerHost } from '../src/__fixtures__/steerHost'; import type { ChatEvent, TMessage, @@ -246,6 +248,7 @@ const messagesHost: MessagesHost = { }), renderMessageIcon: () => null, useMaximizeChatSpace: () => false, + useFlatThread: () => true, useHideSelectedAuthor: () => false, useAgentsMap: () => undefined, renderMessageBody: () => null, @@ -670,16 +673,18 @@ describe('a consumer rendering subagent activity', () => { - - - - - + + + + + + + , diff --git a/packages/client/src/theme/parts.css b/packages/client/src/theme/parts.css index 20f88a5928..6f12649f90 100644 --- a/packages/client/src/theme/parts.css +++ b/packages/client/src/theme/parts.css @@ -174,3 +174,14 @@ font-size: inherit; line-height: inherit; } + +/** + * Message body typography for the package's message text, steers and queued turns. Following the + * chat font setting, it ships here so a consumer with only `@librechat/client/style.css` gets it. + */ +.message-content { + font-size: var(--markdown-font-size, var(--font-size-base, 1rem)); + line-height: 1.6; + /* `.prose` sets max-width: 65ch; fill the message column instead. */ + max-width: none; +} diff --git a/packages/client/src/theme/parts.spec.ts b/packages/client/src/theme/parts.spec.ts new file mode 100644 index 0000000000..2f112bd9bd --- /dev/null +++ b/packages/client/src/theme/parts.spec.ts @@ -0,0 +1,15 @@ +import fs from 'fs'; +import path from 'path'; + +const stylesheet = fs.readFileSync(path.resolve(__dirname, 'parts.css'), 'utf8'); + +describe('shared message body typography', () => { + it('ships the message-content rule with the published styles', () => { + const rule = stylesheet.match(/^\.message-content \{([^}]*)\}/m); + expect(rule).not.toBeNull(); + const body = rule?.[1] ?? ''; + expect(body).toMatch(/font-size:\s*var\(--markdown-font-size/); + expect(body).toMatch(/line-height:\s*1\.6/); + expect(body).toMatch(/max-width:\s*none/); + }); +});