diff --git a/client/src/Providers/MessagesHostContext.tsx b/client/src/Providers/MessagesHostContext.tsx index 12cc88541d..631bec5951 100644 --- a/client/src/Providers/MessagesHostContext.tsx +++ b/client/src/Providers/MessagesHostContext.tsx @@ -1,6 +1,7 @@ import { useCallback, useMemo, useRef } from 'react'; import { useAtomValue } from 'jotai'; import { useRecoilState, useRecoilValue } from 'recoil'; +import { EventSubagentActivityGroup } from '@librechat/chat/components'; import { setDefaultMessagesHost, revealedQueuedTurnFamily } from '@librechat/chat/react'; import type { ForkEvents, @@ -22,8 +23,10 @@ import { import useConversationSeen from '~/hooks/Conversations/useConversationSeen'; import useMessageScrolling from '~/hooks/Messages/useMessageScrolling'; import { useOptionalMessagesOperations } from './MessagesViewContext'; +import ThreadMessage from '~/components/Chat/Messages/Thread/Message'; import MessageAudio from '~/components/Chat/Messages/MessageAudio'; import MessageIcon from '~/components/Chat/Messages/MessageIcon'; +import { useFileMapContext } from '~/Providers/FileMapContext'; import Files from '~/components/Chat/Messages/Content/Files'; import { useScreenshot } from '~/hooks/ScreenshotContext'; import { useForkConvoMutation } from '~/data-provider'; @@ -107,9 +110,10 @@ function AppMessageAudio(props: MessageAudioProps) { } /** What the message list reads from the app: the viewer's clock format and fork defaults, the - * fork request, the rich-text copy, its scrolling, screenshot and seen reporting, and the row - * pieces that still live here. Registered as the default when this module loads, so rows read it - * on every route, the shared view included. */ + * fork request, the rich-text copy, its scrolling, screenshot and seen reporting, the thread's + * file map, and the row pieces that still live here: the message body and the subagent activity + * group. Registered as the default when this module loads, so rows read it on every route, the + * shared view included. */ export const appMessagesHost: MessagesHost = { useHour12: useClockFormat, renderFiles: (message) => , @@ -124,6 +128,9 @@ export const appMessagesHost: MessagesHost = { useAutoScroll: () => useAtomValue(autoScrollAtom), useConversationSeen, renderMessageIcon: (props) => , + renderMessageRow: (props) => , + renderActivity: (props) => , + useFileMap: useFileMapContext, }; setDefaultMessagesHost(appMessagesHost); diff --git a/client/src/components/Chat/Messages/MessagesView.tsx b/client/src/components/Chat/Messages/MessagesView.tsx index 882fde0cbe..e1b60b7a11 100644 --- a/client/src/components/Chat/Messages/MessagesView.tsx +++ b/client/src/components/Chat/Messages/MessagesView.tsx @@ -1,46 +1,14 @@ import { useChatSurface } from '@librechat/chat/react'; import { MessagesView as MessagesList } from '@librechat/chat/components'; -import type { MessagesThreadProps } from '@librechat/chat/components'; import type { TMessage } from 'librechat-data-provider'; import { MessagePartsHostProvider, appMessagePartsHost } from '~/Providers/MessagePartsHostContext'; -import { MessagesViewProvider, useFileMapContext } from '~/Providers'; -import useThreadRows from '~/hooks/Messages/useThreadRows'; import PendingSteers from './Content/Parts/PendingSteers'; -import { FLAT_THREAD, ThreadList } from './Thread'; -import MultiMessage from './MultiMessage'; +import { MessagesViewProvider } from '~/Providers'; import ScrollButton from './ScrollButton'; import PendingTurn from './PendingTurn'; +import { FLAT_THREAD } from './Thread'; import MessageNav from './MessageNav'; -/** The flat thread renderer by default, the recursive one when the flag turns it off. */ -function Thread({ - messagesTree, - messages, - conversationId, - currentEditId, - setCurrentEditId, -}: MessagesThreadProps) { - const fileMap = useFileMapContext(); - const threadRows = useThreadRows(FLAT_THREAD ? messages : null, conversationId, fileMap); - if (FLAT_THREAD && threadRows) { - return ( - - ); - } - return ( - - ); -} - function MessagesViewContent({ messagesTree, messages, @@ -55,7 +23,7 @@ function MessagesViewContent({ messages={messages} showScrollButton={showScrollButton} maximizeChatSpace={maximizeChatSpace} - renderThread={(props) => } + flatThread={FLAT_THREAD} renderPendingTurn={(props) => } renderPendingSteers={(props) => } renderScrollButton={(props) => } diff --git a/client/src/components/Chat/Messages/Thread/Message.tsx b/client/src/components/Chat/Messages/Thread/Message.tsx new file mode 100644 index 0000000000..f01211b74b --- /dev/null +++ b/client/src/components/Chat/Messages/Thread/Message.tsx @@ -0,0 +1,17 @@ +import { isAssistantsEndpoint } from 'librechat-data-provider'; +import type { MessageRowSlotProps } from '@librechat/chat/react'; +import MessageContent from '~/components/Messages/MessageContent'; +import MessageParts from '../MessageParts'; +import Message from '../Message'; + +/** The app's message row for the thread: assistants parts, content parts, or plain text. */ +export default function ThreadMessage(props: MessageRowSlotProps) { + const { message } = props; + if (isAssistantsEndpoint(message.endpoint) && message.content) { + return ; + } + if (message.content) { + return ; + } + return ; +} diff --git a/client/src/components/Chat/Messages/Thread/Row.tsx b/client/src/components/Chat/Messages/Thread/Row.tsx deleted file mode 100644 index 0a64534306..0000000000 --- a/client/src/components/Chat/Messages/Thread/Row.tsx +++ /dev/null @@ -1,76 +0,0 @@ -import { memo, useCallback } from 'react'; -import { useSetAtom } from 'jotai'; -import { hasParallelLanes } from '@librechat/chat'; -import { isAssistantsEndpoint } from 'librechat-data-provider'; -import { EventSubagentActivityGroup } from '@librechat/chat/components'; -import type { ThreadRow } from '@librechat/chat'; -import type { TMessageProps } from '~/common'; -import MessageContent from '~/components/Messages/MessageContent'; -import MessageParts from '../MessageParts'; -import { siblingIdxFamily } from './state'; -import Message from '../Message'; - -type RowProps = { - row: ThreadRow; - currentEditId: TMessageProps['currentEditId']; - setCurrentEditId: TMessageProps['setCurrentEditId']; -}; - -/** One visible row of the flat thread: the message plus its activity group. */ -function Row({ row, currentEditId, setCurrentEditId }: RowProps) { - const { message, siblingIdx, siblingCount, parentKey } = row; - const setSiblingIdx = useSetAtom(siblingIdxFamily(parentKey)); - const setSiblingIdxRev = useCallback( - (value: number) => { - setSiblingIdx(siblingCount - value - 1); - }, - [siblingCount, setSiblingIdx], - ); - - const sharedProps = { - message, - currentEditId, - setCurrentEditId, - siblingIdx: siblingCount - siblingIdx - 1, - siblingCount, - setSiblingIdx: setSiblingIdxRev, - }; - - let content: JSX.Element; - if (isAssistantsEndpoint(message.endpoint) && message.content) { - content = ; - } else if (message.content) { - content = ; - } else { - content = ; - } - - let activityParentMessageIds: string[] = []; - if (message.isCreatedByUser) { - if (row.childCount === 0) activityParentMessageIds = [message.messageId]; - } else { - activityParentMessageIds = [message.messageId, message.parentMessageId].filter( - (id): id is string => typeof id === 'string' && id.length > 0, - ); - } - const isEditingActivityAnchor = - typeof currentEditId === 'string' && activityParentMessageIds.includes(currentEditId); - const hasParallelContent = !message.isCreatedByUser && hasParallelLanes(message.content); - - return ( - <> - {content} - {!isEditingActivityAnchor && activityParentMessageIds.length > 0 ? ( -
- -
- ) : null} - - ); -} - -export default memo(Row); diff --git a/client/src/components/Chat/Messages/Thread/index.ts b/client/src/components/Chat/Messages/Thread/index.ts index ade2061285..8b1eb34874 100644 --- a/client/src/components/Chat/Messages/Thread/index.ts +++ b/client/src/components/Chat/Messages/Thread/index.ts @@ -1,2 +1 @@ -export { default as ThreadList } from './List'; export { FLAT_THREAD } from './flag'; diff --git a/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx b/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx index 3ee68e73f9..38e96b73ed 100644 --- a/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx +++ b/client/src/components/Chat/Messages/__tests__/MessagesView.spec.tsx @@ -1,13 +1,9 @@ import React from 'react'; -import { Provider, createStore } from 'jotai'; -import { ChatContext } from '@librechat/chat/react'; -import { resolveThreadRows } from '@librechat/chat'; import { render, screen } from '@testing-library/react'; -import type { ChatContract } from '@librechat/chat/react'; +import { ChatContext, setDefaultMessagesHost } from '@librechat/chat/react'; +import type { ChatContract, MessagesHost } from '@librechat/chat/react'; import type { TMessage } from 'librechat-data-provider'; import type { ReactElement } from 'react'; -import { siblingIdxFamily } from '~/components/Chat/Messages/Thread/state'; -import useThreadRows from '~/hooks/Messages/useThreadRows'; let mockMessagesKey = 'convo-1'; let mockMaximizeChatSpace = false; @@ -29,11 +25,6 @@ jest.mock('~/Providers', () => ({ useFileMapContext: () => ({}), })); -jest.mock('~/hooks/Messages/useThreadRows', () => ({ - __esModule: true, - default: jest.fn(() => []), -})); - jest.mock('@librechat/chat/react', () => ({ ...jest.requireActual('@librechat/chat/react'), useChatSurface: () => ({ showScrollButton: false, maximizeChatSpace: mockMaximizeChatSpace }), @@ -48,14 +39,6 @@ jest.mock('../Thread', () => ({ get FLAT_THREAD() { return mockFlatThread; }, - ThreadList: () =>
, -})); - -jest.mock('../MultiMessage', () => ({ - __esModule: true, - default: ({ messageId }: { messageId: string | null }) => ( -
- ), })); jest.mock('../Content/Parts/PendingSteers', () => ({ @@ -93,13 +76,46 @@ jest.mock('../MessageNav', () => { import MessagesView from '../MessagesView'; -/** The thread helpers are package exports, which cannot be spied on in place; wrap the real - * resolver so calls are recorded and rows still resolve. */ -jest.mock('@librechat/chat', () => { - const actual = jest.requireActual('@librechat/chat'); - return { ...actual, resolveThreadRows: jest.fn(actual.resolveThreadRows) }; +/** Rows render as their message id, so a spec can tell which messages the thread rendered. */ +const host: MessagesHost = { + useHour12: () => undefined, + renderFiles: () => null, + useForkPreferences: () => ({ + option: '', + setOption: () => undefined, + splitAtTarget: false, + setSplitAtTarget: () => undefined, + rememberOption: false, + setRememberOption: () => undefined, + }), + useForkConversation: () => null, + useMessageCopy: () => ({ copyToClipboard: () => undefined, canCopy: false }), + useGetMessages: () => () => undefined, + useHasPendingTurn: () => false, + renderMessageAudio: () => null, + useScrolling: () => ({ + contentRef: { current: null }, + scrollableRef: { current: null }, + messagesEndRef: { current: null }, + handleSmoothToRef: () => undefined, + debouncedHandleScroll: () => undefined, + handleNearBottomChange: () => undefined, + }), + useScreenshotTarget: () => undefined, + useAutoScroll: () => false, + useConversationSeen: () => () => undefined, + renderMessageIcon: () => null, + renderMessageRow: ({ message }) =>
{message.messageId}
, + renderActivity: () => null, + useFileMap: () => undefined, +}; + +beforeAll(() => { + setDefaultMessagesHost(host); }); +const renderedRows = () => screen.queryAllByTestId('row').map((row) => row.textContent); + /** The pane's chat contract, as far as the list reads it: the pane and the routed key. */ const withChat = (ui: ReactElement) => ( { mockMessagesKey = 'convo-1'; mockMaximizeChatSpace = false; mockFlatThread = false; - jest.mocked(useThreadRows).mockReset().mockReturnValue([]); }); it('keeps the failed-steer surface mounted in the recursive renderer', () => { render(withChat()); - expect(screen.getByTestId('multi-message')).toBeInTheDocument(); + expect(renderedRows()).toEqual(['assistant-1']); expect(screen.getByTestId('pending-steers')).toHaveAttribute('data-conversation-id', 'convo-1'); - expect(screen.queryByTestId('flat-thread')).not.toBeInTheDocument(); + }); + + it.each([ + [true, 'from-messages'], + [false, 'from-tree'], + ])('renders the package thread with FLAT_THREAD %s', (flat, rendered) => { + mockFlatThread = flat; + const tree = [{ ...messageTree[0], messageId: 'from-tree' }]; + const messages = [{ ...messageTree[0], messageId: 'from-messages' }]; + render(withChat()); + + expect(renderedRows()).toEqual([rendered]); }); it.each([false, true])( @@ -157,9 +183,8 @@ describe('MessagesView pending steers', () => { mockFlatThread = true; render(withChat()); - expect(screen.getByTestId('flat-thread')).toBeInTheDocument(); + expect(renderedRows()).toEqual(['assistant-1']); expect(screen.getByTestId('pending-steers')).toHaveAttribute('data-full-width', 'true'); - expect(screen.queryByTestId('multi-message')).not.toBeInTheDocument(); }); it('keys the pending surface to the rendered tree, not the lagging context', () => { @@ -175,66 +200,13 @@ describe('MessagesView pending steers', () => { expect(screen.getByTestId('pending-steers')).toHaveAttribute('data-conversation-id', 'convo-2'); }); - it('does not reuse outgoing rows while the conversation context still names the source', () => { - mockFlatThread = true; - jest - .mocked(useThreadRows) - .mockImplementation(jest.requireActual('~/hooks/Messages/useThreadRows').default); - const resolve = jest.mocked(resolveThreadRows); - resolve.mockClear(); - const large = Array.from({ length: 12_000 }, (_, index) => ({ - ...messageTree[0], - messageId: `large-${index}`, - parentMessageId: index === 0 ? null : `large-${index - 1}`, - })); - const view = render(withChat()); - const small = [{ ...messageTree[0], conversationId: 'convo-2', messageId: 'small' }]; - view.rerender(withChat()); - - expect(resolve).toHaveBeenLastCalledWith(expect.anything(), 'convo-2', expect.anything(), null); - view.unmount(); - jest.mocked(useThreadRows).mockReset().mockReturnValue([]); - }); - - it('preserves the destination root branch while the context still names the source', () => { - mockFlatThread = true; - jest - .mocked(useThreadRows) - .mockImplementation(jest.requireActual('~/hooks/Messages/useThreadRows').default); - const resolve = jest.mocked(resolveThreadRows); - resolve.mockClear(); - const jotaiStore = createStore(); - jotaiStore.set(siblingIdxFamily('convo-2'), 1); - const destination = [ - { ...messageTree[0], messageId: 'older-root', conversationId: 'convo-2' }, - { ...messageTree[0], messageId: 'newer-root', conversationId: 'convo-2' }, - ]; - render( - - {withChat()} - , - ); - - expect(resolve.mock.results.at(-1)?.value[0].source.messageId).toBe('older-root'); - expect(jotaiStore.get(siblingIdxFamily('convo-2'))).toBe(1); - expect(screen.getByTestId('message-nav')).toHaveAttribute('data-conversation-id', 'convo-2'); - }); - - it('uses the rendered owner for recursive root sibling choices too', () => { - const destination = [{ ...messageTree[0], conversationId: 'convo-2' }]; - render(withChat()); - - expect(screen.getByTestId('multi-message')).toHaveAttribute('data-parent-id', 'convo-2'); - }); - it('shows the empty note instead of a thread while the destination tree is empty', () => { mockFlatThread = true; mockMessagesKey = 'convo-2'; render(withChat()); expect(screen.getByText('Nothing found')).toBeInTheDocument(); - expect(screen.queryByTestId('flat-thread')).not.toBeInTheDocument(); - expect(useThreadRows).not.toHaveBeenCalled(); + expect(renderedRows()).toEqual([]); }); it('pins the screenshot identity to the rendered transcript and replaces it on navigation', () => { diff --git a/e2e/specs/mock/scenarios/thread-rows.spec.ts b/e2e/specs/mock/scenarios/thread-rows.spec.ts new file mode 100644 index 0000000000..2d95286c2e --- /dev/null +++ b/e2e/specs/mock/scenarios/thread-rows.spec.ts @@ -0,0 +1,275 @@ +import { randomUUID } from 'crypto'; +import { expect, test } from '@playwright/test'; +import type { Locator, Page } from '@playwright/test'; +import { + withMongo, + seedMessages, + seedConversations, + deleteConversations, + deleteMessagesByConversation, +} from '../db'; +import { getE2EUser } from '../../../setup/user'; +import { messagesView } from '../helpers'; + +/** + * The thread rows the message list renders from `@librechat/chat`: the sibling switch of a + * branched reply, the subagent activity group anchored after the reply to the request that + * launched it, and the group stepping aside while that request is edited. The sibling switch runs + * through both renderers. + */ + +const ROOT = '00000000-0000-0000-0000-000000000000'; + +const messageRow = (page: Page, text: string): Locator => + messagesView(page).locator('.message-render').filter({ hasText: text }).last(); + +const siblingCounter = (row: Locator): Locator => row.locator('nav [role="status"]'); + +async function clickSibling(row: Locator, direction: 'Previous' | 'Next') { + await row.scrollIntoViewIfNeeded(); + await row.hover(); + await row.getByRole('button', { name: `${direction} sibling message` }).click(); +} + +/** A question with two replies, the newer one last. */ +async function seedBranchedChat(label: string): Promise { + const conversationId = randomUUID(); + const { email } = getE2EUser(); + await seedConversations(email, [ + { conversationId, title: `Branched ${label}`, updatedAt: new Date() }, + ]); + const question = randomUUID(); + await seedMessages(email, conversationId, [ + { + messageId: question, + parentMessageId: ROOT, + text: `Question ${label}`, + isCreatedByUser: true, + sender: 'User', + }, + { + messageId: randomUUID(), + parentMessageId: question, + text: `Older reply ${label}`, + isCreatedByUser: false, + sender: 'Mock Provider A', + }, + { + messageId: randomUUID(), + parentMessageId: question, + text: `Newer reply ${label}`, + isCreatedByUser: false, + sender: 'Mock Provider A', + }, + ]); + return conversationId; +} + +async function expectSiblingSwitch(page: Page, label: string) { + const newer = messageRow(page, `Newer reply ${label}`); + await expect(newer).toBeVisible({ timeout: 15_000 }); + await expect(siblingCounter(newer)).toHaveText('2 / 2'); + await expect(messagesView(page).getByText(`Older reply ${label}`)).toHaveCount(0); + + await clickSibling(newer, 'Previous'); + const older = messageRow(page, `Older reply ${label}`); + await expect(older).toBeVisible(); + await expect(siblingCounter(older)).toHaveText('1 / 2'); + await expect(messagesView(page).getByText(`Newer reply ${label}`)).toHaveCount(0); + await expect(older.getByRole('button', { name: 'Previous sibling message' })).toBeDisabled(); + + await clickSibling(older, 'Next'); + await expect(messageRow(page, `Newer reply ${label}`)).toBeVisible(); + await expect(siblingCounter(messageRow(page, `Newer reply ${label}`))).toHaveText('2 / 2'); + await expect(messagesView(page).getByText(`Question ${label}`)).toBeVisible(); +} + +type ActivityChat = { conversationId: string; childConversationId: string }; + +/** + * Two agent turns, with one event-bound child thread persisted against the FIRST request: the + * shape an external event leaves behind, which the thread shows after that request's reply. + */ +async function seedActivityChat(label: string): Promise { + const conversationId = randomUUID(); + const childConversationId = randomUUID(); + const firstRequest = randomUUID(); + const firstReply = randomUUID(); + const secondRequest = randomUUID(); + const { email } = getE2EUser(); + const turns = [ + { messageId: firstRequest, parentMessageId: ROOT, text: `First request ${label}`, user: true }, + { + messageId: firstReply, + parentMessageId: firstRequest, + text: `First reply ${label}`, + user: false, + }, + { + messageId: secondRequest, + parentMessageId: firstReply, + text: `Second request ${label}`, + user: true, + }, + { + messageId: randomUUID(), + parentMessageId: secondRequest, + text: `Second reply ${label}`, + user: false, + }, + ]; + await withMongo(async (db) => { + const owner = await db.collection('users').findOne({ email }); + if (!owner) { + throw new Error(`E2E seed: user "${email}" not found`); + } + const user = owner._id.toString(); + const now = Date.now(); + await db.collection('conversations').insertMany([ + { + conversationId, + title: `Activity ${label}`, + user, + endpoint: 'agents', + isArchived: false, + createdAt: new Date(now), + updatedAt: new Date(now), + __v: 0, + }, + { + conversationId: childConversationId, + title: `Event child ${label}`, + user, + endpoint: 'agents', + isArchived: false, + subagentThread: { + rootConversationId: conversationId, + parentConversationId: conversationId, + parentMessageId: firstRequest, + parentToolCallId: `event-binding:${label}`, + subagentType: 'e2e-event', + subagentKind: 'agent', + depth: 1, + }, + agentEventBinding: { + bindingId: `binding-${label}`, + sourceKeyId: `source-${label}`, + actorId: `actor-${label}`, + }, + createdAt: new Date(now), + updatedAt: new Date(now), + __v: 0, + }, + ]); + await db.collection('messages').insertMany( + turns.map((turn, index) => ({ + messageId: turn.messageId, + parentMessageId: turn.parentMessageId, + conversationId, + text: turn.text, + isCreatedByUser: turn.user, + sender: turn.user ? 'User' : 'Mock Agent', + user, + endpoint: 'agents', + error: false, + unfinished: false, + createdAt: new Date(now + index * 1000), + updatedAt: new Date(now + index * 1000), + __v: 0, + })), + ); + }); + return { conversationId, childConversationId }; +} + +const activityGroup = (page: Page): Locator => + messagesView(page).getByRole('region', { name: 'Agent activity' }); + +test.describe('thread rows', () => { + let conversationIds: string[] = []; + + test.afterEach(async () => { + if (conversationIds.length === 0) { + return; + } + await deleteMessagesByConversation(conversationIds); + await deleteConversations(conversationIds); + conversationIds = []; + }); + + test('a branched reply switches siblings with both arrows and the counter @scenario:thread-sibling-switch', async ({ + page, + }) => { + const label = `siblings-${Date.now().toString(36)}`; + const conversationId = await seedBranchedChat(label); + conversationIds.push(conversationId); + await page.goto(`/c/${conversationId}`, { timeout: 15_000 }); + await expectSiblingSwitch(page, label); + }); + + test('the recursive renderer switches siblings the same way @scenario:thread-sibling-switch-recursive', async ({ + page, + }) => { + const label = `siblings-tree-${Date.now().toString(36)}`; + const conversationId = await seedBranchedChat(label); + conversationIds.push(conversationId); + await page.addInitScript(() => { + localStorage.setItem('LC_FLAT_THREAD', 'false'); + }); + await page.goto(`/c/${conversationId}`, { timeout: 15_000 }); + await expectSiblingSwitch(page, label); + }); + + test('subagent activity sits after the reply to the request that launched it, ahead of the next turn @scenario:thread-activity-under-parent', async ({ + page, + }) => { + const label = `rows-anchor-${Date.now().toString(36)}`; + const chat = await seedActivityChat(label); + conversationIds.push(chat.conversationId, chat.childConversationId); + await page.goto(`/c/${chat.conversationId}`, { timeout: 15_000 }); + await expect(activityGroup(page)).toHaveCount(1, { timeout: 15_000 }); + + const order = await page.evaluate((labelText) => { + const view = document.querySelector('[data-testid="messages-view"]'); + const group = view?.querySelector('section[data-event-subagent-group]'); + const rows = Array.from(view?.querySelectorAll('.message-render') ?? []); + if (!group) { + return null; + } + return rows.map((row) => ({ + text: ['First request', 'First reply', 'Second request', 'Second reply'].find((prefix) => + row.textContent?.includes(`${prefix} ${labelText}`), + ), + beforeGroup: Boolean(row.compareDocumentPosition(group) & Node.DOCUMENT_POSITION_FOLLOWING), + })); + }, label); + expect(order).toEqual([ + { text: 'First request', beforeGroup: true }, + { text: 'First reply', beforeGroup: true }, + { text: 'Second request', beforeGroup: false }, + { text: 'Second reply', beforeGroup: false }, + ]); + }); + + test('editing the request hides its activity group and cancelling restores it @scenario:thread-edit-hides-activity', async ({ + page, + }) => { + const label = `rows-edit-${Date.now().toString(36)}`; + const chat = await seedActivityChat(label); + conversationIds.push(chat.conversationId, chat.childConversationId); + await page.goto(`/c/${chat.conversationId}`, { timeout: 15_000 }); + await expect(activityGroup(page)).toBeVisible({ timeout: 15_000 }); + + const request = messageRow(page, `First request ${label}`); + await request.scrollIntoViewIfNeeded(); + await request.hover(); + await request.getByRole('button', { name: 'Edit', exact: true }).last().click(); + const editor = messagesView(page).getByRole('region', { name: 'Edit message' }); + await expect(editor).toBeVisible(); + await expect(activityGroup(page)).toHaveCount(0); + + await editor.getByRole('button', { name: 'Cancel' }).click(); + await expect(editor).toHaveCount(0); + await expect(activityGroup(page)).toBeVisible(); + }); +}); diff --git a/packages/chat/src/__fixtures__/messagesHost.ts b/packages/chat/src/__fixtures__/messagesHost.ts index 13c7b1c532..93f763d555 100644 --- a/packages/chat/src/__fixtures__/messagesHost.ts +++ b/packages/chat/src/__fixtures__/messagesHost.ts @@ -31,6 +31,9 @@ export function createMessagesHost(overrides: Partial = {}): Messa useAutoScroll: () => false, useConversationSeen: () => () => undefined, renderMessageIcon: () => null, + renderMessageRow: () => null, + renderActivity: () => null, + useFileMap: () => undefined, ...overrides, }; } diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts index 4f9a2140c0..e9e2a4a8a3 100644 --- a/packages/chat/src/components.ts +++ b/packages/chat/src/components.ts @@ -156,6 +156,7 @@ export type { ChatPaneChrome } from './components/pane/chrome'; /** Message list root: the scroll container, mount window and pending tail around the thread. */ export { default as MessagesView } from './components/messages/MessagesView'; +export { default as MessagesThread } from './components/messages/thread/Thread'; export type { MessagesViewProps, MessagesThreadProps, diff --git a/packages/chat/src/components/messages/MessagesView.tsx b/packages/chat/src/components/messages/MessagesView.tsx index 1440efce8f..e3f4236a1b 100644 --- a/packages/chat/src/components/messages/MessagesView.tsx +++ b/packages/chat/src/components/messages/MessagesView.tsx @@ -1,15 +1,9 @@ import { useState, useCallback, useEffect } from 'react'; import { Constants } from 'librechat-data-provider'; import { cn, useLocalize } from '@librechat/client'; -import type { - Dispatch, - RefObject, - ReactNode, - MouseEvent, - ReactElement, - SetStateAction, -} from 'react'; +import type { RefObject, ReactNode, MouseEvent, ReactElement } from 'react'; import type { TMessage } from 'librechat-data-provider'; +import type { MessagesThreadProps } from './thread/Thread'; import { RowMountProvider, useProgressiveRowMount, @@ -18,16 +12,9 @@ import useScrollbarGutter from '../../react/messages/useScrollbarGutter'; import { useMessagesHost } from '../../react/messages/host'; import { useChatContext } from '../../react/chat/context'; import { useMessagePartsHost } from '../../react/host'; +import Thread from './thread/Thread'; -/** What the thread slot renders the conversation from. */ -export type MessagesThreadProps = { - messagesTree?: TMessage[]; - messages?: TMessage[] | null; - /** The conversation that owns the rendered tree. */ - conversationId?: string | null; - currentEditId: string | number | null; - setCurrentEditId: Dispatch>; -}; +export type { MessagesThreadProps }; /** What the scroll-to-bottom slot needs to watch the end marker and scroll to it. */ export type MessagesScrollButtonProps = { @@ -47,8 +34,10 @@ export type MessagesViewProps = { showScrollButton: boolean; /** The viewer's chat-width preference. */ maximizeChatSpace: boolean; - /** Renders the conversation's rows. */ - renderThread: (props: MessagesThreadProps) => ReactNode; + /** Renders the thread as a flat row list (the default) or, when `false`, as a recursive tree. */ + flatThread?: boolean; + /** Renders the conversation's rows; the package thread by default. */ + renderThread?: (props: MessagesThreadProps) => ReactNode; /** Renders the turn the reader just sent, ahead of its reply, at the thread's tail. */ renderPendingTurn?: (props: { scrollableRef: RefObject; @@ -70,6 +59,8 @@ export type MessagesViewProps = { }) => ReactNode; }; +const renderDefaultThread = (props: MessagesThreadProps): ReactNode => ; + /** * 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, @@ -80,7 +71,8 @@ export default function MessagesView({ messages, showScrollButton, maximizeChatSpace, - renderThread, + flatThread = true, + renderThread = renderDefaultThread, renderPendingTurn, renderPendingSteers, renderScrollButton, @@ -215,6 +207,7 @@ export default function MessagesView({ messagesTree, messages, conversationId: treeConversationId, + flat: flatThread, currentEditId, setCurrentEditId, })} diff --git a/client/src/components/Chat/Messages/Thread/List.tsx b/packages/chat/src/components/messages/thread/List.tsx similarity index 64% rename from client/src/components/Chat/Messages/Thread/List.tsx rename to packages/chat/src/components/messages/thread/List.tsx index 08909b6ab1..d01632ecc0 100644 --- a/client/src/components/Chat/Messages/Thread/List.tsx +++ b/packages/chat/src/components/messages/thread/List.tsx @@ -1,13 +1,12 @@ import { memo } from 'react'; -import { useRowMountWindow } from '@librechat/chat/react'; -import type { ThreadRow } from '@librechat/chat'; -import type { TMessageProps } from '~/common'; +import type { NamedExoticComponent, ReactElement } from 'react'; +import type { MessageRowSlotProps } from '../../../react/messages/host'; +import type { ThreadRow } from '../../../core/thread'; +import { useRowMountWindow } from '../../../react/messages/useProgressiveRowMount'; import Row from './Row'; -type ListProps = { +type ListProps = Pick & { rows: ThreadRow[]; - currentEditId: TMessageProps['currentEditId']; - setCurrentEditId: TMessageProps['setCurrentEditId']; }; /** @@ -16,7 +15,7 @@ type ListProps = { * lifecycle, while a row's position does not, so the streaming row keeps its * component instance and a sibling switch reuses the instances below it. */ -function List({ rows, currentEditId, setCurrentEditId }: ListProps) { +function List({ rows, currentEditId, setCurrentEditId }: ListProps): ReactElement { const mountWindow = useRowMountWindow(); return ( <> @@ -34,4 +33,6 @@ function List({ rows, currentEditId, setCurrentEditId }: ListProps) { ); } -export default memo(List); +const MemoizedList: NamedExoticComponent = memo(List); + +export default MemoizedList; diff --git a/client/src/components/Chat/Messages/MultiMessage.tsx b/packages/chat/src/components/messages/thread/MultiMessage.tsx similarity index 75% rename from client/src/components/Chat/Messages/MultiMessage.tsx rename to packages/chat/src/components/messages/thread/MultiMessage.tsx index c32ccf0a82..8324543331 100644 --- a/client/src/components/Chat/Messages/MultiMessage.tsx +++ b/packages/chat/src/components/messages/thread/MultiMessage.tsx @@ -1,16 +1,19 @@ import { memo, useEffect, useRef, useCallback } from 'react'; import { useAtom } from 'jotai'; -import { hasParallelLanes } from '@librechat/chat'; -import { useRowMountWindow } from '@librechat/chat/react'; -import { isAssistantsEndpoint } from 'librechat-data-provider'; -import { EventSubagentActivityGroup } from '@librechat/chat/components'; +import type { NamedExoticComponent, ReactElement, ReactNode } from 'react'; import type { TMessage } from 'librechat-data-provider'; -import type { ReactElement } from 'react'; -import type { TMessageProps } from '~/common'; -import MessageContent from '~/components/Messages/MessageContent'; -import { siblingIdxFamily, siblingKey } from './Thread/state'; -import MessageParts from './MessageParts'; -import Message from './Message'; +import type { MessageRowSlotProps } from '../../../react/messages/host'; +import { useRowMountWindow } from '../../../react/messages/useProgressiveRowMount'; +import { siblingIdxFamily, siblingKey } from '../../../react/thread'; +import { activityParentMessageIds } from '../../../core/activity'; +import { useMessagesHost } from '../../../react/messages/host'; +import { hasParallelLanes } from '../../../core/lanes'; + +type MultiMessageProps = Pick & { + /** The parent whose children this level picks one of; the conversation id at the root. */ + messageId?: string | null; + messagesTree?: TMessage[]; +}; /** First-run sentinel for `parentRef`: `messageId` itself may legitimately be * null/undefined at the root level, so those can't mark "not yet bound". */ @@ -22,7 +25,8 @@ function MultiMessage({ messagesTree, currentEditId, setCurrentEditId, -}: TMessageProps) { +}: MultiMessageProps): ReactElement | null { + const { renderMessageRow, renderActivity } = useMessagesHost(); const [siblingIdx, setSiblingIdx] = useAtom(siblingIdxFamily(siblingKey(messageId))); const mountWindow = useRowMountWindow(); @@ -47,15 +51,15 @@ function MultiMessage({ * by identity instead of blanket-resetting: * * - An APPENDED newest child means a submission landed here (send, - * regenerate, edit-resubmit all append) — follow it, the long-standing + * regenerate, edit-resubmit all append): follow it, the long-standing * behavior. An append is a newest-id change where the prior newest still * exists; when it vanished instead, the same row was RE-KEYED (streaming - * ids hydrate to durable ids at finalize — the legacy regenerate path + * ids hydrate to durable ids at finalize; the legacy regenerate path * mints a new UUID for `_`-suffixed ids), and following it would yank a * user who paged away mid-stream. * - Otherwise the change is background churn (an abandoned preempt sibling * restored at finalize, a refetch merge dropping an optimistic row, id - * hydration) — keep the message the user was viewing, recomputing its + * hydration): keep the message the user was viewing, recomputing its * reversed index from its new position. Only when it no longer exists * does the selection fall back to the newest. * @@ -107,7 +111,7 @@ function MultiMessage({ * previous array) while the prior newest survived. A changed last id * alone can also be a same-membership REORDER (sibling `createdAt` ties * have no sort tie-breaker) or a RE-KEY (a streaming id hydrating to its - * durable id at finalize) — neither is a new branch to follow. */ + * durable id at finalize); neither is a new branch to follow. */ const appendedNewest = previous.newestId == null || (newestId !== previous.newestId && @@ -147,7 +151,7 @@ function MultiMessage({ } /** - * No explicit key — React uses positional reconciliation since MultiMessage + * No explicit key: React uses positional reconciliation since MultiMessage * always renders exactly one row at this position. * * Both messageId and parentMessageId change during the SSE lifecycle @@ -176,30 +180,12 @@ function MultiMessage({ mountWindow == null || ((message.depth ?? 0) >= mountWindow.start && (message.depth ?? 0) <= mountWindow.end); - let row: ReactElement | null = null; - if (!rowMounted) { - row = null; - } else if (isAssistantsEndpoint(message.endpoint) && message.content) { - row = ; - } else if (message.content) { - row = ; - } else { - row = ; - } - /** Event children may be persisted against the user request that launched - * the Director. Once its assistant response exists, present that activity - * after the response instead of interrupting the turn between user and - * assistant rows. Exact assistant-owned children remain in the same group. */ - let activityParentMessageIds: string[] = []; - if (message.isCreatedByUser) { - if (!message.children?.length) activityParentMessageIds = [message.messageId]; - } else { - activityParentMessageIds = [message.messageId, message.parentMessageId].filter( - (id): id is string => typeof id === 'string' && id.length > 0, - ); - } - const isEditingActivityAnchor = - typeof currentEditId === 'string' && activityParentMessageIds.includes(currentEditId); + const row: ReactNode = rowMounted ? renderMessageRow(sharedProps) : null; + const activityIds = activityParentMessageIds( + message, + (message.children?.length ?? 0) > 0, + currentEditId, + ); const hasParallelContent = !message.isCreatedByUser && hasParallelLanes(message.content); /** @@ -212,13 +198,13 @@ function MultiMessage({ return ( <> {row} - {rowMounted && !isEditingActivityAnchor && activityParentMessageIds.length > 0 ? ( + {rowMounted && activityIds.length > 0 ? (
- + {renderActivity({ + conversationId: message.conversationId ?? '', + parentMessageIds: activityIds, + hasParallelContent, + })}
) : null} = memo(MultiMessage); export default MemoizedMultiMessage; diff --git a/packages/chat/src/components/messages/thread/Row.tsx b/packages/chat/src/components/messages/thread/Row.tsx new file mode 100644 index 0000000000..cf07575bfb --- /dev/null +++ b/packages/chat/src/components/messages/thread/Row.tsx @@ -0,0 +1,55 @@ +import { memo, useCallback } from 'react'; +import { useSetAtom } from 'jotai'; +import type { NamedExoticComponent, ReactElement } from 'react'; +import type { MessageRowSlotProps } from '../../../react/messages/host'; +import type { ThreadRow } from '../../../core/thread'; +import { activityParentMessageIds } from '../../../core/activity'; +import { useMessagesHost } from '../../../react/messages/host'; +import { siblingIdxFamily } from '../../../react/thread'; +import { hasParallelLanes } from '../../../core/lanes'; + +type RowProps = Pick & { + row: ThreadRow; +}; + +/** One visible row of the flat thread: the message plus its activity group. */ +function Row({ row, currentEditId, setCurrentEditId }: RowProps): ReactElement { + const { renderMessageRow, renderActivity } = useMessagesHost(); + const { message, siblingIdx, siblingCount, parentKey } = row; + const setSiblingIdx = useSetAtom(siblingIdxFamily(parentKey)); + const setSiblingIdxRev = useCallback( + (value: number) => { + setSiblingIdx(siblingCount - value - 1); + }, + [siblingCount, setSiblingIdx], + ); + + const activityIds = activityParentMessageIds(message, row.childCount > 0, currentEditId); + const hasParallelContent = !message.isCreatedByUser && hasParallelLanes(message.content); + + return ( + <> + {renderMessageRow({ + message, + currentEditId, + setCurrentEditId, + siblingIdx: siblingCount - siblingIdx - 1, + siblingCount, + setSiblingIdx: setSiblingIdxRev, + })} + {activityIds.length > 0 ? ( +
+ {renderActivity({ + conversationId: message.conversationId ?? '', + parentMessageIds: activityIds, + hasParallelContent, + })} +
+ ) : null} + + ); +} + +const MemoizedRow: NamedExoticComponent = memo(Row); + +export default MemoizedRow; diff --git a/packages/chat/src/components/messages/thread/Thread.tsx b/packages/chat/src/components/messages/thread/Thread.tsx new file mode 100644 index 0000000000..52c65aac7d --- /dev/null +++ b/packages/chat/src/components/messages/thread/Thread.tsx @@ -0,0 +1,45 @@ +import type { Dispatch, ReactElement, SetStateAction } from 'react'; +import type { TMessage } from 'librechat-data-provider'; +import { useMessagesHost } from '../../../react/messages/host'; +import useThreadRows from '../../../react/messages/rows'; +import MultiMessage from './MultiMessage'; +import List from './List'; + +/** What the thread slot renders the conversation from. */ +export type MessagesThreadProps = { + messagesTree?: TMessage[]; + messages?: TMessage[] | null; + /** The conversation that owns the rendered tree. */ + conversationId?: string | null; + /** Renders the flat row list; `false` renders the recursive tree. */ + flat: boolean; + currentEditId: string | number | null; + setCurrentEditId: Dispatch>; +}; + +/** + * The message list's default thread: the flat row list, or the recursive renderer when the + * view turns the flat one off. Each row's message and activity render through the host's slots. + */ +export default function Thread({ + flat, + messagesTree, + messages, + conversationId, + currentEditId, + setCurrentEditId, +}: MessagesThreadProps): ReactElement { + const fileMap = useMessagesHost().useFileMap(); + const rows = useThreadRows(flat ? messages : null, conversationId, fileMap); + if (flat && rows) { + return ; + } + return ( + + ); +} diff --git a/client/src/components/Chat/Messages/__tests__/MultiMessage.spec.tsx b/packages/chat/src/components/messages/thread/__tests__/MultiMessage.spec.tsx similarity index 75% rename from client/src/components/Chat/Messages/__tests__/MultiMessage.spec.tsx rename to packages/chat/src/components/messages/thread/__tests__/MultiMessage.spec.tsx index fffbaafab6..c02900b6bc 100644 --- a/client/src/components/Chat/Messages/__tests__/MultiMessage.spec.tsx +++ b/packages/chat/src/components/messages/thread/__tests__/MultiMessage.spec.tsx @@ -1,54 +1,59 @@ -import React from 'react'; -import { RecoilRoot } from 'recoil'; +/** + * @jest-environment jsdom + */ import { Provider as JotaiProvider } from 'jotai'; import { fireEvent, render, screen } from '@testing-library/react'; import type { TMessage } from 'librechat-data-provider'; +import type { MessageRowSlotProps, MessagesHost } from '../../../../react/messages/host'; +import { RowMountProvider } from '../../../../react/messages/useProgressiveRowMount'; +import { setDefaultMessagesHost } from '../../../../react/messages/host'; import MultiMessage from '../MultiMessage'; -type RowProps = { - message: TMessage; - siblingIdx?: number; - setSiblingIdx?: (value: number) => void; -}; +const RowStub = ({ message, siblingIdx, setSiblingIdx }: MessageRowSlotProps) => ( +
+
{message.messageId}
+
+); -/** Row stub exposing the sibling switcher contract (display-order index). */ -const createRowStub = () => { - const { createElement } = jest.requireActual('react'); - return ({ message, siblingIdx = 0, setSiblingIdx }: RowProps) => - createElement( - 'div', - null, - createElement('div', { 'data-testid': 'row' }, message.messageId), - createElement( - 'button', - { 'data-testid': 'prev', onClick: () => setSiblingIdx?.(siblingIdx - 1) }, - 'prev', - ), - ); -}; - -jest.mock('~/components/Messages/MessageContent', () => ({ - __esModule: true, - default: createRowStub(), -})); -jest.mock('../MessageParts', () => ({ __esModule: true, default: createRowStub() })); -jest.mock('../Message', () => ({ __esModule: true, default: createRowStub() })); -jest.mock('@librechat/chat/components', () => ({ - ...jest.requireActual('@librechat/chat/components'), - EventSubagentActivityGroup: ({ - parentMessageIds, - hasParallelContent, - }: { - parentMessageIds: string[]; - hasParallelContent?: boolean; - }) => ( +/** A host whose message slot exposes the sibling switcher contract (display-order index). */ +const host: MessagesHost = { + useHour12: () => undefined, + renderFiles: () => null, + useForkPreferences: () => ({ + option: '', + setOption: () => undefined, + splitAtTarget: false, + setSplitAtTarget: () => undefined, + rememberOption: false, + setRememberOption: () => undefined, + }), + useForkConversation: () => null, + useMessageCopy: () => ({ copyToClipboard: () => undefined, canCopy: false }), + useGetMessages: () => () => undefined, + useHasPendingTurn: () => false, + renderMessageAudio: () => null, + useScrolling: () => { + throw new Error('not used by the thread'); + }, + useScreenshotTarget: () => undefined, + useAutoScroll: () => false, + useConversationSeen: () => () => undefined, + renderMessageIcon: () => null, + renderMessageRow: (props) => , + renderActivity: ({ parentMessageIds, hasParallelContent }) => (
), -})); + useFileMap: () => undefined, +}; + +beforeAll(() => { + setDefaultMessagesHost(host); +}); const msg = (messageId: string): TMessage => ({ @@ -65,14 +70,12 @@ const tree = (ids: string[]) => ids.map((id) => msg(id)); const treeElement = (ids: string[]) => ( - - - + ); @@ -83,14 +86,12 @@ describe('MultiMessage sibling selection', () => { const structured = msg('structured'); const legacy = { ...msg('legacy'), content: undefined } as TMessage; const view = render( - - - , + , ); expect(screen.getByTestId('event-subagent-activity')).toHaveAttribute( @@ -99,14 +100,12 @@ describe('MultiMessage sibling selection', () => { ); view.rerender( - - - , + , ); expect(screen.getByTestId('event-subagent-activity')).toHaveAttribute( 'data-parent-message-ids', @@ -125,14 +124,12 @@ describe('MultiMessage sibling selection', () => { assistant.parentMessageId = 'user'; render( - - - , + , ); expect(screen.getAllByTestId('event-subagent-activity')).toHaveLength(1); @@ -157,14 +154,12 @@ describe('MultiMessage sibling selection', () => { } as TMessage; render( - - - , + , ); expect(screen.queryByTestId('event-subagent-activity')).not.toBeInTheDocument(); @@ -181,14 +176,12 @@ describe('MultiMessage sibling selection', () => { } as unknown as TMessage; render( - - - , + , ); expect(screen.getByTestId('event-subagent-activity')).toHaveAttribute( @@ -210,14 +203,12 @@ describe('MultiMessage sibling selection', () => { } as unknown as TMessage; render( - - - , + , ); expect(screen.getByTestId('event-subagent-activity')).toHaveAttribute( @@ -233,14 +224,12 @@ describe('MultiMessage sibling selection', () => { } as unknown as TMessage; render( - - - , + , ); expect(screen.getByTestId('row')).toHaveTextContent('assistant'); @@ -308,7 +297,7 @@ describe('MultiMessage sibling selection', () => { * Regression: streaming ids hydrate to durable ids at finalize (the legacy * regenerate path mints a new UUID for `_`-suffixed preliminary ids). The * newest child's id changing WITHOUT the prior newest surviving is a - * re-key of the same row, not an append — it must not yank a user who + * re-key of the same row, not an append; it must not yank a user who * paged to an older sibling mid-stream. */ it('keeps the viewed older branch when the newest sibling is re-keyed at finalize', () => { @@ -342,7 +331,7 @@ describe('MultiMessage sibling selection', () => { /** * Regression: sibling `createdAt` ties have no sort tie-breaker, so a * refetch can return the same membership in a different order. A changed - * last id without a NEW member is a reorder, not an append — the viewed + * last id without a NEW member is a reorder, not an append; the viewed * message must stay selected by identity. */ it('treats a same-membership reorder as churn, not an append', () => { @@ -357,19 +346,17 @@ describe('MultiMessage sibling selection', () => { /** * Regression: the recursive instance is deliberately unkeyed and gets * reused across parents when an ancestor's branch switches. The - * reconciliation refs then describe the previous parent's children — + * reconciliation refs then describe the previous parent's children, so * reconciling against them wiped the returned-to branch's saved selection. */ it("preserves each parent's saved selection when the instance is reused across parents", () => { const treeFor = (messageId: string, ids: string[]) => ( - - - + ); const view = render(treeFor('parent-a', ['a1', 'a2'])); @@ -385,9 +372,6 @@ describe('MultiMessage sibling selection', () => { }); describe('MultiMessage row mount window', () => { - const { RowMountProvider } = - jest.requireActual('@librechat/chat/react'); - const chain = (): TMessage => { const leaf = { ...msg('m2'), parentMessageId: 'm1', depth: 2 } as TMessage; const mid = { ...msg('m1'), parentMessageId: 'm0', depth: 1, children: [leaf] } as TMessage; @@ -395,16 +379,14 @@ describe('MultiMessage row mount window', () => { }; const windowedTree = (mountWindow: { start: number; end: number } | null) => ( - - - - - + + + ); it('renders every row without a window', () => { diff --git a/packages/chat/src/components/messages/thread/__tests__/Thread.spec.tsx b/packages/chat/src/components/messages/thread/__tests__/Thread.spec.tsx new file mode 100644 index 0000000000..4f4b055e1b --- /dev/null +++ b/packages/chat/src/components/messages/thread/__tests__/Thread.spec.tsx @@ -0,0 +1,229 @@ +/** + * @jest-environment jsdom + */ +import { Provider, createStore } from 'jotai'; +import { fireEvent, render, screen, within } from '@testing-library/react'; +import type { TFile, TMessage } from 'librechat-data-provider'; +import type { MessagesHost } from '../../../../react/messages/host'; +import type { ChatContract } from '../../../../react/chat/contract'; +import type { MessagePartsHost } from '../../../../react/host'; +import type { MessagesViewProps } from '../../MessagesView'; +import { createMessagesHost } from '../../../../__fixtures__/messagesHost'; +import { MessagesHostProvider } from '../../../../react/messages/host'; +import { MessagePartsHostProvider } from '../../../../react/host'; +import { ChatContext } from '../../../../react/chat/context'; +import { initEnglish } from '../../../../__fixtures__/i18n'; +import { resolveThreadRows } from '../../../../core/thread'; +import { siblingIdxFamily } from '../../../../react/thread'; +import MessagesView from '../../MessagesView'; + +/** Wrap the real resolver so calls are recorded and rows still resolve. */ +jest.mock('../../../../core/thread', () => { + const actual = jest.requireActual('../../../../core/thread'); + return { ...actual, resolveThreadRows: jest.fn(actual.resolveThreadRows) }; +}); + +beforeAll(initEnglish); + +const ROOT = '00000000-0000-0000-0000-000000000000'; + +function message(messageId: string, parentMessageId: string, extra: Partial = {}) { + return { + messageId, + parentMessageId, + conversationId: 'convo-1', + text: messageId, + isCreatedByUser: messageId.startsWith('u'), + ...extra, + } as TMessage; +} + +/** u1 -> (a1-old, a1): one branched reply. */ +const branched = (): TMessage[] => [ + message('u1', ROOT), + message('a1-old', 'u1'), + message('a1', 'u1'), +]; + +/** The same conversation as the nested tree the recursive renderer reads. */ +const branchedTree = (): TMessage[] => { + const [user, older, newer] = branched(); + return [{ ...user, children: [older, newer] }]; +}; + +const partsHost = { useFontSize: () => 'text-base' } as unknown as MessagePartsHost; + +const renderActivity = jest.fn>(() => null); + +function createHost(overrides: Partial = {}): MessagesHost { + return createMessagesHost({ + renderMessageRow: ({ + message: row, + siblingIdx, + siblingCount, + setSiblingIdx, + setCurrentEditId, + }) => ( +
+ {row.files?.map((file) => file.filename).join(',')} +
+ ), + renderActivity: (props) => { + renderActivity(props); + return