mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-21 23:43:35 +00:00
🪜 refactor: Move the Thread Renderers Into @librechat/chat as the Default Thread (#17661)
* refactor: Render Thread Rows Through MessagesHost Slots * refactor: Move the Thread Renderers Into @librechat/chat as the Default MessagesView Thread * test: Verify Sibling Switching, Activity Anchors and Editing on the Package Thread
This commit is contained in:
parent
7cebb55d96
commit
d70280a1cd
24 changed files with 1033 additions and 414 deletions
|
|
@ -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) => <Files message={message} />,
|
||||
|
|
@ -124,6 +128,9 @@ export const appMessagesHost: MessagesHost = {
|
|||
useAutoScroll: () => useAtomValue(autoScrollAtom),
|
||||
useConversationSeen,
|
||||
renderMessageIcon: (props) => <MessageIcon {...props} />,
|
||||
renderMessageRow: (props) => <ThreadMessage {...props} />,
|
||||
renderActivity: (props) => <EventSubagentActivityGroup {...props} />,
|
||||
useFileMap: useFileMapContext,
|
||||
};
|
||||
|
||||
setDefaultMessagesHost(appMessagesHost);
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<ThreadList
|
||||
rows={threadRows}
|
||||
setCurrentEditId={setCurrentEditId}
|
||||
currentEditId={currentEditId ?? null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<MultiMessage
|
||||
messagesTree={messagesTree}
|
||||
messageId={conversationId ?? null}
|
||||
setCurrentEditId={setCurrentEditId}
|
||||
currentEditId={currentEditId ?? null}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function MessagesViewContent({
|
||||
messagesTree,
|
||||
messages,
|
||||
|
|
@ -55,7 +23,7 @@ function MessagesViewContent({
|
|||
messages={messages}
|
||||
showScrollButton={showScrollButton}
|
||||
maximizeChatSpace={maximizeChatSpace}
|
||||
renderThread={(props) => <Thread {...props} />}
|
||||
flatThread={FLAT_THREAD}
|
||||
renderPendingTurn={(props) => <PendingTurn {...props} />}
|
||||
renderPendingSteers={(props) => <PendingSteers {...props} />}
|
||||
renderScrollButton={(props) => <ScrollButton {...props} />}
|
||||
|
|
|
|||
17
client/src/components/Chat/Messages/Thread/Message.tsx
Normal file
17
client/src/components/Chat/Messages/Thread/Message.tsx
Normal file
|
|
@ -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 <MessageParts {...props} />;
|
||||
}
|
||||
if (message.content) {
|
||||
return <MessageContent {...props} />;
|
||||
}
|
||||
return <Message {...props} />;
|
||||
}
|
||||
|
|
@ -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 = <MessageParts {...sharedProps} />;
|
||||
} else if (message.content) {
|
||||
content = <MessageContent {...sharedProps} />;
|
||||
} else {
|
||||
content = <Message {...sharedProps} />;
|
||||
}
|
||||
|
||||
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 ? (
|
||||
<div className="w-full border-0 bg-transparent">
|
||||
<EventSubagentActivityGroup
|
||||
conversationId={message.conversationId ?? ''}
|
||||
parentMessageIds={activityParentMessageIds}
|
||||
hasParallelContent={hasParallelContent}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default memo(Row);
|
||||
|
|
@ -1,2 +1 @@
|
|||
export { default as ThreadList } from './List';
|
||||
export { FLAT_THREAD } from './flag';
|
||||
|
|
|
|||
|
|
@ -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: () => <div data-testid="flat-thread" />,
|
||||
}));
|
||||
|
||||
jest.mock('../MultiMessage', () => ({
|
||||
__esModule: true,
|
||||
default: ({ messageId }: { messageId: string | null }) => (
|
||||
<div data-testid="multi-message" data-parent-id={messageId} />
|
||||
),
|
||||
}));
|
||||
|
||||
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 }) => <div data-testid="row">{message.messageId}</div>,
|
||||
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) => (
|
||||
<ChatContext.Provider
|
||||
|
|
@ -128,15 +144,25 @@ describe('MessagesView pending steers', () => {
|
|||
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(<MessagesView messagesTree={messageTree} messages={messageTree} />));
|
||||
|
||||
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(<MessagesView messagesTree={tree} messages={messages} />));
|
||||
|
||||
expect(renderedRows()).toEqual([rendered]);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
|
|
@ -157,9 +183,8 @@ describe('MessagesView pending steers', () => {
|
|||
mockFlatThread = true;
|
||||
render(withChat(<MessagesView messagesTree={messageTree} messages={messageTree} />));
|
||||
|
||||
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(<MessagesView messagesTree={large} messages={large} />));
|
||||
const small = [{ ...messageTree[0], conversationId: 'convo-2', messageId: 'small' }];
|
||||
view.rerender(withChat(<MessagesView messagesTree={small} messages={small} />));
|
||||
|
||||
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(
|
||||
<Provider store={jotaiStore}>
|
||||
{withChat(<MessagesView messagesTree={destination} messages={destination} />)}
|
||||
</Provider>,
|
||||
);
|
||||
|
||||
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(<MessagesView messagesTree={destination} messages={destination} />));
|
||||
|
||||
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(<MessagesView messagesTree={[]} messages={[]} />));
|
||||
|
||||
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', () => {
|
||||
|
|
|
|||
275
e2e/specs/mock/scenarios/thread-rows.spec.ts
Normal file
275
e2e/specs/mock/scenarios/thread-rows.spec.ts
Normal file
|
|
@ -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<string> {
|
||||
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<ActivityChat> {
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
|
@ -31,6 +31,9 @@ export function createMessagesHost(overrides: Partial<MessagesHost> = {}): Messa
|
|||
useAutoScroll: () => false,
|
||||
useConversationSeen: () => () => undefined,
|
||||
renderMessageIcon: () => null,
|
||||
renderMessageRow: () => null,
|
||||
renderActivity: () => null,
|
||||
useFileMap: () => undefined,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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<SetStateAction<string | number | null>>;
|
||||
};
|
||||
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<HTMLDivElement>;
|
||||
|
|
@ -70,6 +59,8 @@ export type MessagesViewProps = {
|
|||
}) => ReactNode;
|
||||
};
|
||||
|
||||
const renderDefaultThread = (props: MessagesThreadProps): ReactNode => <Thread {...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,
|
||||
|
|
@ -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,
|
||||
})}
|
||||
|
|
|
|||
|
|
@ -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<MessageRowSlotProps, 'currentEditId' | 'setCurrentEditId'> & {
|
||||
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<ListProps> = memo(List);
|
||||
|
||||
export default MemoizedList;
|
||||
|
|
@ -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<MessageRowSlotProps, 'currentEditId' | 'setCurrentEditId'> & {
|
||||
/** 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 = <MessageParts {...sharedProps} />;
|
||||
} else if (message.content) {
|
||||
row = <MessageContent {...sharedProps} />;
|
||||
} else {
|
||||
row = <Message {...sharedProps} />;
|
||||
}
|
||||
/** 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 ? (
|
||||
<div className="w-full border-0 bg-transparent">
|
||||
<EventSubagentActivityGroup
|
||||
conversationId={message.conversationId ?? ''}
|
||||
parentMessageIds={activityParentMessageIds}
|
||||
hasParallelContent={hasParallelContent}
|
||||
/>
|
||||
{renderActivity({
|
||||
conversationId: message.conversationId ?? '',
|
||||
parentMessageIds: activityIds,
|
||||
hasParallelContent,
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
<MemoizedMultiMessage
|
||||
|
|
@ -231,6 +217,6 @@ function MultiMessage({
|
|||
);
|
||||
}
|
||||
|
||||
const MemoizedMultiMessage = memo(MultiMessage);
|
||||
const MemoizedMultiMessage: NamedExoticComponent<MultiMessageProps> = memo(MultiMessage);
|
||||
|
||||
export default MemoizedMultiMessage;
|
||||
55
packages/chat/src/components/messages/thread/Row.tsx
Normal file
55
packages/chat/src/components/messages/thread/Row.tsx
Normal file
|
|
@ -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<MessageRowSlotProps, 'currentEditId' | 'setCurrentEditId'> & {
|
||||
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 ? (
|
||||
<div className="w-full border-0 bg-transparent">
|
||||
{renderActivity({
|
||||
conversationId: message.conversationId ?? '',
|
||||
parentMessageIds: activityIds,
|
||||
hasParallelContent,
|
||||
})}
|
||||
</div>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const MemoizedRow: NamedExoticComponent<RowProps> = memo(Row);
|
||||
|
||||
export default MemoizedRow;
|
||||
45
packages/chat/src/components/messages/thread/Thread.tsx
Normal file
45
packages/chat/src/components/messages/thread/Thread.tsx
Normal file
|
|
@ -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<SetStateAction<string | number | null>>;
|
||||
};
|
||||
|
||||
/**
|
||||
* 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 <List rows={rows} currentEditId={currentEditId} setCurrentEditId={setCurrentEditId} />;
|
||||
}
|
||||
return (
|
||||
<MultiMessage
|
||||
messagesTree={messagesTree}
|
||||
messageId={conversationId ?? null}
|
||||
currentEditId={currentEditId}
|
||||
setCurrentEditId={setCurrentEditId}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
@ -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) => (
|
||||
<div>
|
||||
<div data-testid="row">{message.messageId}</div>
|
||||
<button data-testid="prev" onClick={() => setSiblingIdx(siblingIdx - 1)} />
|
||||
</div>
|
||||
);
|
||||
|
||||
/** Row stub exposing the sibling switcher contract (display-order index). */
|
||||
const createRowStub = () => {
|
||||
const { createElement } = jest.requireActual<typeof React>('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) => <RowStub {...props} />,
|
||||
renderActivity: ({ parentMessageIds, hasParallelContent }) => (
|
||||
<div
|
||||
data-testid="event-subagent-activity"
|
||||
data-parent-message-ids={parentMessageIds.join(',')}
|
||||
data-has-parallel-content={String(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[]) => (
|
||||
<JotaiProvider>
|
||||
<RecoilRoot>
|
||||
<MultiMessage
|
||||
messageId="parent-1"
|
||||
messagesTree={tree(ids)}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>
|
||||
</RecoilRoot>
|
||||
<MultiMessage
|
||||
messageId="parent-1"
|
||||
messagesTree={tree(ids)}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>
|
||||
</JotaiProvider>
|
||||
);
|
||||
|
||||
|
|
@ -83,14 +86,12 @@ describe('MultiMessage sibling selection', () => {
|
|||
const structured = msg('structured');
|
||||
const legacy = { ...msg('legacy'), content: undefined } as TMessage;
|
||||
const view = render(
|
||||
<RecoilRoot>
|
||||
<MultiMessage
|
||||
messageId="parent-1"
|
||||
messagesTree={[structured]}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>
|
||||
</RecoilRoot>,
|
||||
<MultiMessage
|
||||
messageId="parent-1"
|
||||
messagesTree={[structured]}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('event-subagent-activity')).toHaveAttribute(
|
||||
|
|
@ -99,14 +100,12 @@ describe('MultiMessage sibling selection', () => {
|
|||
);
|
||||
|
||||
view.rerender(
|
||||
<RecoilRoot>
|
||||
<MultiMessage
|
||||
messageId="parent-1"
|
||||
messagesTree={[legacy]}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>
|
||||
</RecoilRoot>,
|
||||
<MultiMessage
|
||||
messageId="parent-1"
|
||||
messagesTree={[legacy]}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
expect(screen.getByTestId('event-subagent-activity')).toHaveAttribute(
|
||||
'data-parent-message-ids',
|
||||
|
|
@ -125,14 +124,12 @@ describe('MultiMessage sibling selection', () => {
|
|||
assistant.parentMessageId = 'user';
|
||||
|
||||
render(
|
||||
<RecoilRoot>
|
||||
<MultiMessage
|
||||
messageId="root"
|
||||
messagesTree={[user]}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>
|
||||
</RecoilRoot>,
|
||||
<MultiMessage
|
||||
messageId="root"
|
||||
messagesTree={[user]}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getAllByTestId('event-subagent-activity')).toHaveLength(1);
|
||||
|
|
@ -157,14 +154,12 @@ describe('MultiMessage sibling selection', () => {
|
|||
} as TMessage;
|
||||
|
||||
render(
|
||||
<RecoilRoot>
|
||||
<MultiMessage
|
||||
messageId="root"
|
||||
messagesTree={[user]}
|
||||
currentEditId="user"
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>
|
||||
</RecoilRoot>,
|
||||
<MultiMessage
|
||||
messageId="root"
|
||||
messagesTree={[user]}
|
||||
currentEditId="user"
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.queryByTestId('event-subagent-activity')).not.toBeInTheDocument();
|
||||
|
|
@ -181,14 +176,12 @@ describe('MultiMessage sibling selection', () => {
|
|||
} as unknown as TMessage;
|
||||
|
||||
render(
|
||||
<RecoilRoot>
|
||||
<MultiMessage
|
||||
messageId="parent-1"
|
||||
messagesTree={[assistant]}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>
|
||||
</RecoilRoot>,
|
||||
<MultiMessage
|
||||
messageId="parent-1"
|
||||
messagesTree={[assistant]}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('event-subagent-activity')).toHaveAttribute(
|
||||
|
|
@ -210,14 +203,12 @@ describe('MultiMessage sibling selection', () => {
|
|||
} as unknown as TMessage;
|
||||
|
||||
render(
|
||||
<RecoilRoot>
|
||||
<MultiMessage
|
||||
messageId="parent-1"
|
||||
messagesTree={[assistant]}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>
|
||||
</RecoilRoot>,
|
||||
<MultiMessage
|
||||
messageId="parent-1"
|
||||
messagesTree={[assistant]}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('event-subagent-activity')).toHaveAttribute(
|
||||
|
|
@ -233,14 +224,12 @@ describe('MultiMessage sibling selection', () => {
|
|||
} as unknown as TMessage;
|
||||
|
||||
render(
|
||||
<RecoilRoot>
|
||||
<MultiMessage
|
||||
messageId="parent-1"
|
||||
messagesTree={[assistant]}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>
|
||||
</RecoilRoot>,
|
||||
<MultiMessage
|
||||
messageId="parent-1"
|
||||
messagesTree={[assistant]}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
|
||||
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[]) => (
|
||||
<RecoilRoot>
|
||||
<MultiMessage
|
||||
messageId={messageId}
|
||||
messagesTree={tree(ids)}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>
|
||||
</RecoilRoot>
|
||||
<MultiMessage
|
||||
messageId={messageId}
|
||||
messagesTree={tree(ids)}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>
|
||||
);
|
||||
|
||||
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<typeof import('@librechat/chat/react')>('@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) => (
|
||||
<RecoilRoot>
|
||||
<RowMountProvider mountWindow={mountWindow}>
|
||||
<MultiMessage
|
||||
messageId="parent-1"
|
||||
messagesTree={[chain()]}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>
|
||||
</RowMountProvider>
|
||||
</RecoilRoot>
|
||||
<RowMountProvider mountWindow={mountWindow}>
|
||||
<MultiMessage
|
||||
messageId="parent-1"
|
||||
messagesTree={[chain()]}
|
||||
currentEditId={null}
|
||||
setCurrentEditId={jest.fn()}
|
||||
/>
|
||||
</RowMountProvider>
|
||||
);
|
||||
|
||||
it('renders every row without a window', () => {
|
||||
|
|
@ -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<TMessage> = {}) {
|
||||
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, Parameters<MessagesHost['renderActivity']>>(() => null);
|
||||
|
||||
function createHost(overrides: Partial<MessagesHost> = {}): MessagesHost {
|
||||
return createMessagesHost({
|
||||
renderMessageRow: ({
|
||||
message: row,
|
||||
siblingIdx,
|
||||
siblingCount,
|
||||
setSiblingIdx,
|
||||
setCurrentEditId,
|
||||
}) => (
|
||||
<article aria-label={row.messageId} data-sibling={`${siblingIdx + 1} / ${siblingCount}`}>
|
||||
<span>{row.files?.map((file) => file.filename).join(',')}</span>
|
||||
<button aria-label="Previous" onClick={() => setSiblingIdx(siblingIdx - 1)} />
|
||||
<button aria-label="Next" onClick={() => setSiblingIdx(siblingIdx + 1)} />
|
||||
<button aria-label="Edit" onClick={() => setCurrentEditId(row.messageId)} />
|
||||
<button aria-label="Cancel" onClick={() => setCurrentEditId(-1)} />
|
||||
</article>
|
||||
),
|
||||
renderActivity: (props) => {
|
||||
renderActivity(props);
|
||||
return <aside aria-label={`Activity ${props.parentMessageIds.join(',')}`} />;
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
const contract = {
|
||||
index: 0,
|
||||
isSubmitting: false,
|
||||
latestMessageDepth: 0,
|
||||
messagesKey: 'convo-1',
|
||||
} as ChatContract;
|
||||
|
||||
function renderThread(
|
||||
props: Partial<MessagesViewProps>,
|
||||
host: MessagesHost = createHost(),
|
||||
store = createStore(),
|
||||
) {
|
||||
const view = (next: Partial<MessagesViewProps>) => (
|
||||
<Provider store={store}>
|
||||
<ChatContext.Provider value={contract}>
|
||||
<MessagesHostProvider host={host}>
|
||||
<MessagePartsHostProvider host={partsHost}>
|
||||
<MessagesView showScrollButton={false} maximizeChatSpace={false} {...props} {...next} />
|
||||
</MessagePartsHostProvider>
|
||||
</MessagesHostProvider>
|
||||
</ChatContext.Provider>
|
||||
</Provider>
|
||||
);
|
||||
const result = render(view({}));
|
||||
return {
|
||||
...result,
|
||||
rerenderThread: (next: Partial<MessagesViewProps>) => result.rerender(view(next)),
|
||||
};
|
||||
}
|
||||
|
||||
const rows = () => screen.queryAllByRole('article').map((row) => row.getAttribute('aria-label'));
|
||||
const row = (id: string) => screen.getByRole('article', { name: id });
|
||||
|
||||
beforeEach(() => {
|
||||
renderActivity.mockClear();
|
||||
jest.mocked(resolveThreadRows).mockClear();
|
||||
});
|
||||
|
||||
describe('MessagesView default thread', () => {
|
||||
it('renders the flat rows from the messages by default', () => {
|
||||
renderThread({ messages: branched(), messagesTree: [message('from-tree', ROOT)] });
|
||||
expect(rows()).toEqual(['u1', 'a1']);
|
||||
});
|
||||
|
||||
it('renders the recursive tree when the flat thread is off', () => {
|
||||
renderThread({
|
||||
flatThread: false,
|
||||
messages: [message('from-messages', ROOT)],
|
||||
messagesTree: branchedTree(),
|
||||
});
|
||||
expect(rows()).toEqual(['u1', 'a1']);
|
||||
});
|
||||
|
||||
it.each([true, false])('switches siblings through the row slot (flat %s)', (flatThread) => {
|
||||
renderThread({ flatThread, messages: branched(), messagesTree: branchedTree() });
|
||||
expect(row('a1')).toHaveAttribute('data-sibling', '2 / 2');
|
||||
expect(row('u1')).toHaveAttribute('data-sibling', '1 / 1');
|
||||
|
||||
fireEvent.click(within(row('a1')).getByRole('button', { name: 'Previous' }));
|
||||
expect(rows()).toEqual(['u1', 'a1-old']);
|
||||
expect(row('a1-old')).toHaveAttribute('data-sibling', '1 / 2');
|
||||
|
||||
fireEvent.click(within(row('a1-old')).getByRole('button', { name: 'Next' }));
|
||||
expect(rows()).toEqual(['u1', 'a1']);
|
||||
expect(row('a1')).toHaveAttribute('data-sibling', '2 / 2');
|
||||
});
|
||||
|
||||
it.each([true, false])(
|
||||
'anchors activity after the reply and hides it while an anchor is edited (flat %s)',
|
||||
(flatThread) => {
|
||||
renderThread({ flatThread, messages: branched(), messagesTree: branchedTree() });
|
||||
expect(renderActivity).toHaveBeenLastCalledWith({
|
||||
conversationId: 'convo-1',
|
||||
parentMessageIds: ['a1', 'u1'],
|
||||
hasParallelContent: false,
|
||||
});
|
||||
expect(
|
||||
screen.getAllByRole('complementary').map((group) => group.getAttribute('aria-label')),
|
||||
).toEqual(['Activity a1,u1']);
|
||||
|
||||
fireEvent.click(within(row('u1')).getByRole('button', { name: 'Edit' }));
|
||||
expect(screen.queryByRole('complementary')).not.toBeInTheDocument();
|
||||
|
||||
fireEvent.click(within(row('u1')).getByRole('button', { name: 'Cancel' }));
|
||||
expect(screen.getByRole('complementary', { name: 'Activity a1,u1' })).toBeInTheDocument();
|
||||
},
|
||||
);
|
||||
|
||||
it('anchors activity on a user turn that has no reply yet', () => {
|
||||
renderThread({ messages: [message('u1', ROOT)] });
|
||||
expect(screen.getByRole('complementary', { name: 'Activity u1' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("hydrates a row's files from the host's file map", () => {
|
||||
const fileMap = { f1: { file_id: 'f1', filename: 'hydrated.txt' } as TFile };
|
||||
renderThread(
|
||||
{ messages: [message('u1', ROOT, { files: [{ file_id: 'f1' }] })] },
|
||||
createHost({ useFileMap: () => fileMap }),
|
||||
);
|
||||
expect(within(row('u1')).getByText('hydrated.txt')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not reuse outgoing rows while the conversation context still names the source', () => {
|
||||
const large = Array.from({ length: 12_000 }, (_, index) =>
|
||||
message(`large-${index}`, index === 0 ? ROOT : `large-${index - 1}`),
|
||||
);
|
||||
const view = renderThread({ messages: large, messagesTree: large });
|
||||
const small = [message('small', ROOT, { conversationId: 'convo-2' })];
|
||||
view.rerenderThread({ messages: small, messagesTree: small });
|
||||
|
||||
expect(resolveThreadRows).toHaveBeenLastCalledWith(
|
||||
expect.anything(),
|
||||
'convo-2',
|
||||
expect.anything(),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves the destination root branch while the context still names the source', () => {
|
||||
const store = createStore();
|
||||
store.set(siblingIdxFamily('convo-2'), 1);
|
||||
const destination = [
|
||||
message('older-root', ROOT, { conversationId: 'convo-2' }),
|
||||
message('newer-root', ROOT, { conversationId: 'convo-2' }),
|
||||
];
|
||||
renderThread({ messages: destination, messagesTree: destination }, createHost(), store);
|
||||
|
||||
expect(rows()).toEqual(['older-root']);
|
||||
expect(store.get(siblingIdxFamily('convo-2'))).toBe(1);
|
||||
});
|
||||
|
||||
it('keys the recursive root selection to the rendered conversation too', () => {
|
||||
const store = createStore();
|
||||
store.set(siblingIdxFamily('convo-2'), 1);
|
||||
const destination = [
|
||||
message('older-root', ROOT, { conversationId: 'convo-2' }),
|
||||
message('newer-root', ROOT, { conversationId: 'convo-2' }),
|
||||
];
|
||||
renderThread(
|
||||
{ flatThread: false, messages: destination, messagesTree: destination },
|
||||
createHost(),
|
||||
store,
|
||||
);
|
||||
|
||||
expect(rows()).toEqual(['older-root']);
|
||||
});
|
||||
});
|
||||
32
packages/chat/src/core/__tests__/activity.spec.ts
Normal file
32
packages/chat/src/core/__tests__/activity.spec.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import { activityParentMessageIds } from '../activity';
|
||||
|
||||
const user = { messageId: 'u1', parentMessageId: 'root', isCreatedByUser: true };
|
||||
const reply = { messageId: 'a1', parentMessageId: 'u1', isCreatedByUser: false };
|
||||
|
||||
describe('activityParentMessageIds', () => {
|
||||
it('anchors activity on a user row only until it has a reply', () => {
|
||||
expect(activityParentMessageIds(user, false, null)).toEqual(['u1']);
|
||||
expect(activityParentMessageIds(user, true, null)).toEqual([]);
|
||||
});
|
||||
|
||||
it('anchors a reply on itself and its request', () => {
|
||||
expect(activityParentMessageIds(reply, false, null)).toEqual(['a1', 'u1']);
|
||||
expect(activityParentMessageIds(reply, true, -1)).toEqual(['a1', 'u1']);
|
||||
});
|
||||
|
||||
it('drops an empty or missing parent id', () => {
|
||||
expect(activityParentMessageIds({ ...reply, parentMessageId: '' }, false, null)).toEqual([
|
||||
'a1',
|
||||
]);
|
||||
expect(activityParentMessageIds({ ...reply, parentMessageId: null }, false, null)).toEqual([
|
||||
'a1',
|
||||
]);
|
||||
});
|
||||
|
||||
it('shows no activity while one of its anchors is being edited', () => {
|
||||
expect(activityParentMessageIds(reply, false, 'a1')).toEqual([]);
|
||||
expect(activityParentMessageIds(reply, false, 'u1')).toEqual([]);
|
||||
expect(activityParentMessageIds(user, false, 'u1')).toEqual([]);
|
||||
expect(activityParentMessageIds(reply, false, 'other')).toEqual(['a1', 'u1']);
|
||||
});
|
||||
});
|
||||
28
packages/chat/src/core/activity.ts
Normal file
28
packages/chat/src/core/activity.ts
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
import type { TMessage } from 'librechat-data-provider';
|
||||
|
||||
/**
|
||||
* The messages whose background activity a thread row shows after itself, or none.
|
||||
*
|
||||
* Activity may be persisted against the user request that launched it. Once that request has a
|
||||
* reply, the activity shows after the reply instead of between the request and the reply, so a
|
||||
* user row anchors activity only while it has no children, and a reply anchors its own activity
|
||||
* and its request's. A row whose anchor is being edited shows none, so the editor stands alone.
|
||||
*/
|
||||
export function activityParentMessageIds(
|
||||
message: Pick<TMessage, 'messageId' | 'parentMessageId' | 'isCreatedByUser'>,
|
||||
hasChildren: boolean,
|
||||
currentEditId: string | number | null | undefined,
|
||||
): string[] {
|
||||
let ids: string[] = [];
|
||||
if (message.isCreatedByUser) {
|
||||
ids = hasChildren ? [] : [message.messageId];
|
||||
} else {
|
||||
ids = [message.messageId, message.parentMessageId].filter(
|
||||
(id): id is string => typeof id === 'string' && id.length > 0,
|
||||
);
|
||||
}
|
||||
if (typeof currentEditId === 'string' && ids.includes(currentEditId)) {
|
||||
return [];
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
|
@ -28,3 +28,4 @@ export * from './pane';
|
|||
export * from './documents';
|
||||
export * from './thread';
|
||||
export * from './lanes';
|
||||
export * from './activity';
|
||||
|
|
|
|||
|
|
@ -143,12 +143,14 @@ export type {
|
|||
MessageCopyInput,
|
||||
ForkPreferences,
|
||||
ForkConversation,
|
||||
ActivitySlotProps,
|
||||
MessagesScrolling,
|
||||
ReportNearBottom,
|
||||
MessageIconData,
|
||||
MessageIconProps,
|
||||
MessageAudioProps,
|
||||
MessageAudioButtonProps,
|
||||
MessageRowSlotProps,
|
||||
} from './react/messages/host';
|
||||
export {
|
||||
SoleToolContext,
|
||||
|
|
|
|||
|
|
@ -1,14 +1,16 @@
|
|||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import React from 'react';
|
||||
import { Provider, createStore } from 'jotai';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { resolveThreadRows } from '@librechat/chat';
|
||||
import type { TMessage } from 'librechat-data-provider';
|
||||
import useThreadRows from '../useThreadRows';
|
||||
import { resolveThreadRows } from '../../../core/thread';
|
||||
import useThreadRows from '../rows';
|
||||
|
||||
/** 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');
|
||||
/** 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) };
|
||||
});
|
||||
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
import { useRef, createContext, useContext } from 'react';
|
||||
import type {
|
||||
Agent,
|
||||
TFile,
|
||||
TMessage,
|
||||
Assistant,
|
||||
TConversation,
|
||||
|
|
@ -27,6 +28,26 @@ export type MessagesScrolling = {
|
|||
handleNearBottomChange: (isNearBottom: boolean) => void;
|
||||
};
|
||||
|
||||
/** What the message slot renders one visible row of the thread from. */
|
||||
export type MessageRowSlotProps = {
|
||||
message: TMessage;
|
||||
/** Position of the message among its siblings, oldest first. */
|
||||
siblingIdx: number;
|
||||
siblingCount: number;
|
||||
/** Shows the sibling at the given position, oldest first. */
|
||||
setSiblingIdx: (value: number) => void;
|
||||
currentEditId: string | number | null;
|
||||
setCurrentEditId: Dispatch<SetStateAction<string | number | null>>;
|
||||
};
|
||||
|
||||
/** What the activity slot renders the background activity of a row from. */
|
||||
export type ActivitySlotProps = {
|
||||
conversationId: string;
|
||||
/** The messages whose activity the group shows, in order. */
|
||||
parentMessageIds: string[];
|
||||
hasParallelContent: boolean;
|
||||
};
|
||||
|
||||
/** Reports, from the end marker's visibility, that the reader has seen the conversation. */
|
||||
export type ReportNearBottom = (isNearBottom: boolean) => void;
|
||||
|
||||
|
|
@ -154,6 +175,12 @@ export interface MessagesHost {
|
|||
|
||||
/** Renders a message author's icon with the app's endpoint and avatar icons. */
|
||||
renderMessageIcon: (props: MessageIconProps) => ReactNode;
|
||||
/** Renders one message of the thread: its header, body and controls. */
|
||||
renderMessageRow: (props: MessageRowSlotProps) => ReactNode;
|
||||
/** Renders the background activity (subagent runs) launched from a row. */
|
||||
renderActivity: (props: ActivitySlotProps) => ReactNode;
|
||||
/** The conversation's files by id, which hydrate the files of a thread row. */
|
||||
useFileMap: () => Record<string, TFile> | undefined;
|
||||
}
|
||||
|
||||
const noop = (): void => undefined;
|
||||
|
|
@ -204,6 +231,9 @@ const fallbackHost: MessagesHost = {
|
|||
useAutoScroll: () => false,
|
||||
useConversationSeen: () => ignoreNearBottom,
|
||||
renderMessageIcon: () => null,
|
||||
renderMessageRow: () => null,
|
||||
renderActivity: () => null,
|
||||
useFileMap: () => undefined,
|
||||
};
|
||||
|
||||
const MessagesHostContext = createContext<MessagesHost | null>(null);
|
||||
|
|
|
|||
|
|
@ -1,19 +1,15 @@
|
|||
import { useEffect, useMemo, useRef } from 'react';
|
||||
import { useStore } from 'jotai';
|
||||
import type { TFile, TMessage } from 'librechat-data-provider';
|
||||
import type { ThreadIndex, ThreadRow } from '../../core/thread';
|
||||
import {
|
||||
ROOT_KEY,
|
||||
buildThreadIndex,
|
||||
changedParentKeys,
|
||||
reconcileSiblingIdx,
|
||||
resolveThreadRows,
|
||||
} from '@librechat/chat';
|
||||
import type { TFile, TMessage } from 'librechat-data-provider';
|
||||
import type { ThreadIndex, ThreadRow } from '@librechat/chat';
|
||||
import {
|
||||
siblingIdxFamily,
|
||||
siblingKey,
|
||||
useSiblingIndexes,
|
||||
} from '~/components/Chat/Messages/Thread/state';
|
||||
} from '../../core/thread';
|
||||
import { siblingIdxFamily, siblingKey, useSiblingIndexes } from '../thread';
|
||||
|
||||
const EMPTY_KEYS: string[] = [];
|
||||
|
||||
|
|
@ -13,6 +13,8 @@ import {
|
|||
MentionPopover,
|
||||
ChatScreen,
|
||||
HoverButtons,
|
||||
MessagesView,
|
||||
SiblingSwitch,
|
||||
getHeaderHoverLabel,
|
||||
EventSubagentActivityGroup,
|
||||
} from '@librechat/chat/components';
|
||||
|
|
@ -234,6 +236,9 @@ const messagesHost: MessagesHost = {
|
|||
useAutoScroll: () => false,
|
||||
useConversationSeen: () => () => undefined,
|
||||
renderMessageIcon: () => null,
|
||||
renderMessageRow: () => null,
|
||||
renderActivity: () => null,
|
||||
useFileMap: () => undefined,
|
||||
};
|
||||
|
||||
const renderers: PartRenderers = {
|
||||
|
|
@ -570,4 +575,70 @@ describe('a consumer rendering subagent activity', () => {
|
|||
fireEvent.click(child as HTMLElement);
|
||||
expect(claimForeground).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('renders a branched conversation through the package message list and its default thread', () => {
|
||||
const root = '00000000-0000-0000-0000-000000000000';
|
||||
const base = { conversationId: 'convo', createdAt: new Date().toISOString() };
|
||||
const messages: TMessage[] = [
|
||||
{ ...base, messageId: 'u1', parentMessageId: root, isCreatedByUser: true, text: 'Question' },
|
||||
{ ...base, messageId: 'a1', parentMessageId: 'u1', isCreatedByUser: false, text: 'First' },
|
||||
{ ...base, messageId: 'a2', parentMessageId: 'u1', isCreatedByUser: false, text: 'Second' },
|
||||
];
|
||||
const threadHost: MessagesHost = {
|
||||
...messagesHost,
|
||||
renderMessageRow: ({ message, siblingIdx, siblingCount, setSiblingIdx }) => {
|
||||
const label = message.isCreatedByUser ? 'You' : 'Assistant';
|
||||
return (
|
||||
<MessageRow
|
||||
message={message}
|
||||
label={label}
|
||||
ariaLabel={label}
|
||||
icon={null}
|
||||
footer={
|
||||
<SiblingSwitch
|
||||
siblingIdx={siblingIdx}
|
||||
siblingCount={siblingCount}
|
||||
setSiblingIdx={setSiblingIdx}
|
||||
/>
|
||||
}
|
||||
isCreatedByUser={message.isCreatedByUser}
|
||||
>
|
||||
<p>{message.text}</p>
|
||||
</MessageRow>
|
||||
);
|
||||
},
|
||||
};
|
||||
const contract = {
|
||||
index: 0,
|
||||
isSubmitting: false,
|
||||
latestMessageDepth: 0,
|
||||
messagesKey: 'convo',
|
||||
} as ChatContract;
|
||||
render(
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<ChatContext.Provider value={contract}>
|
||||
<MessagesHostProvider host={threadHost}>
|
||||
<MessagePartsHostProvider host={host}>
|
||||
<MessagesView
|
||||
messages={messages}
|
||||
messagesTree={messages}
|
||||
showScrollButton={false}
|
||||
maximizeChatSpace={false}
|
||||
/>
|
||||
</MessagePartsHostProvider>
|
||||
</MessagesHostProvider>
|
||||
</ChatContext.Provider>
|
||||
</I18nextProvider>,
|
||||
);
|
||||
|
||||
const reply = screen.getByRole('group', { name: 'Assistant' });
|
||||
expect(screen.getByRole('group', { name: 'You' })).toHaveTextContent('Question');
|
||||
expect(reply).toHaveTextContent('Second');
|
||||
expect(within(reply).getByRole('status')).toHaveTextContent('2 / 2');
|
||||
|
||||
fireEvent.click(within(reply).getByRole('button', { name: 'com_ui_previous_sibling' }));
|
||||
const older = screen.getByRole('group', { name: 'Assistant' });
|
||||
expect(older).toHaveTextContent('First');
|
||||
expect(within(older).getByRole('status')).toHaveTextContent('1 / 2');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue