From d70280a1cd6e9fce5b4ce7fbc0a6960f62b18f1d Mon Sep 17 00:00:00 2001
From: Marco Beretta <81851188+berry-13@users.noreply.github.com>
Date: Mon, 2 Nov 2026 00:42:51 +0100
Subject: [PATCH] =?UTF-8?q?=F0=9F=AA=9C=20refactor:=20Move=20the=20Thread?=
=?UTF-8?q?=20Renderers=20Into=20@librechat/chat=20as=20the=20Default=20Th?=
=?UTF-8?q?read=20(#17661)?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
* 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
---
client/src/Providers/MessagesHostContext.tsx | 13 +-
.../components/Chat/Messages/MessagesView.tsx | 38 +--
.../Chat/Messages/Thread/Message.tsx | 17 ++
.../components/Chat/Messages/Thread/Row.tsx | 76 -----
.../components/Chat/Messages/Thread/index.ts | 1 -
.../Messages/__tests__/MessagesView.spec.tsx | 138 ++++-----
e2e/specs/mock/scenarios/thread-rows.spec.ts | 275 ++++++++++++++++++
.../chat/src/__fixtures__/messagesHost.ts | 3 +
packages/chat/src/components.ts | 1 +
.../src/components/messages/MessagesView.tsx | 33 +--
.../src/components/messages/thread}/List.tsx | 17 +-
.../messages/thread}/MultiMessage.tsx | 80 +++--
.../src/components/messages/thread/Row.tsx | 55 ++++
.../src/components/messages/thread/Thread.tsx | 45 +++
.../thread}/__tests__/MultiMessage.spec.tsx | 236 +++++++--------
.../messages/thread/__tests__/Thread.spec.tsx | 229 +++++++++++++++
.../chat/src/core/__tests__/activity.spec.ts | 32 ++
packages/chat/src/core/activity.ts | 28 ++
packages/chat/src/core/index.ts | 1 +
packages/chat/src/react.ts | 2 +
.../react/messages/__tests__/rows.spec.tsx | 14 +-
packages/chat/src/react/messages/host.tsx | 30 ++
.../chat/src/react/messages/rows.ts | 12 +-
packages/chat/test/consumer.spec.tsx | 71 +++++
24 files changed, 1033 insertions(+), 414 deletions(-)
create mode 100644 client/src/components/Chat/Messages/Thread/Message.tsx
delete mode 100644 client/src/components/Chat/Messages/Thread/Row.tsx
create mode 100644 e2e/specs/mock/scenarios/thread-rows.spec.ts
rename {client/src/components/Chat/Messages/Thread => packages/chat/src/components/messages/thread}/List.tsx (64%)
rename {client/src/components/Chat/Messages => packages/chat/src/components/messages/thread}/MultiMessage.tsx (75%)
create mode 100644 packages/chat/src/components/messages/thread/Row.tsx
create mode 100644 packages/chat/src/components/messages/thread/Thread.tsx
rename {client/src/components/Chat/Messages => packages/chat/src/components/messages/thread}/__tests__/MultiMessage.spec.tsx (75%)
create mode 100644 packages/chat/src/components/messages/thread/__tests__/Thread.spec.tsx
create mode 100644 packages/chat/src/core/__tests__/activity.spec.ts
create mode 100644 packages/chat/src/core/activity.ts
rename client/src/hooks/Messages/__tests__/useThreadRows.spec.tsx => packages/chat/src/react/messages/__tests__/rows.spec.tsx (88%)
rename client/src/hooks/Messages/useThreadRows.ts => packages/chat/src/react/messages/rows.ts (93%)
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 ;
+ },
+ ...overrides,
+ });
+}
+
+const contract = {
+ index: 0,
+ isSubmitting: false,
+ latestMessageDepth: 0,
+ messagesKey: 'convo-1',
+} as ChatContract;
+
+function renderThread(
+ props: Partial,
+ host: MessagesHost = createHost(),
+ store = createStore(),
+) {
+ const view = (next: Partial) => (
+
+
+
+
+
+
+
+
+
+ );
+ const result = render(view({}));
+ return {
+ ...result,
+ rerenderThread: (next: Partial) => 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']);
+ });
+});
diff --git a/packages/chat/src/core/__tests__/activity.spec.ts b/packages/chat/src/core/__tests__/activity.spec.ts
new file mode 100644
index 0000000000..156ed57026
--- /dev/null
+++ b/packages/chat/src/core/__tests__/activity.spec.ts
@@ -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']);
+ });
+});
diff --git a/packages/chat/src/core/activity.ts b/packages/chat/src/core/activity.ts
new file mode 100644
index 0000000000..a2ecb7d3d6
--- /dev/null
+++ b/packages/chat/src/core/activity.ts
@@ -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,
+ 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;
+}
diff --git a/packages/chat/src/core/index.ts b/packages/chat/src/core/index.ts
index 19b2d8a8a2..cea5adf15c 100644
--- a/packages/chat/src/core/index.ts
+++ b/packages/chat/src/core/index.ts
@@ -28,3 +28,4 @@ export * from './pane';
export * from './documents';
export * from './thread';
export * from './lanes';
+export * from './activity';
diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.ts
index 8f9c40c446..27097d0054 100644
--- a/packages/chat/src/react.ts
+++ b/packages/chat/src/react.ts
@@ -143,12 +143,14 @@ export type {
MessageCopyInput,
ForkPreferences,
ForkConversation,
+ ActivitySlotProps,
MessagesScrolling,
ReportNearBottom,
MessageIconData,
MessageIconProps,
MessageAudioProps,
MessageAudioButtonProps,
+ MessageRowSlotProps,
} from './react/messages/host';
export {
SoleToolContext,
diff --git a/client/src/hooks/Messages/__tests__/useThreadRows.spec.tsx b/packages/chat/src/react/messages/__tests__/rows.spec.tsx
similarity index 88%
rename from client/src/hooks/Messages/__tests__/useThreadRows.spec.tsx
rename to packages/chat/src/react/messages/__tests__/rows.spec.tsx
index 83521f7a4f..4b2df01bd5 100644
--- a/client/src/hooks/Messages/__tests__/useThreadRows.spec.tsx
+++ b/packages/chat/src/react/messages/__tests__/rows.spec.tsx
@@ -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) };
});
diff --git a/packages/chat/src/react/messages/host.tsx b/packages/chat/src/react/messages/host.tsx
index c59424e5f4..3bccafb19b 100644
--- a/packages/chat/src/react/messages/host.tsx
+++ b/packages/chat/src/react/messages/host.tsx
@@ -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>;
+};
+
+/** 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 | 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(null);
diff --git a/client/src/hooks/Messages/useThreadRows.ts b/packages/chat/src/react/messages/rows.ts
similarity index 93%
rename from client/src/hooks/Messages/useThreadRows.ts
rename to packages/chat/src/react/messages/rows.ts
index d1187b7b3d..2634d6cfd3 100644
--- a/client/src/hooks/Messages/useThreadRows.ts
+++ b/packages/chat/src/react/messages/rows.ts
@@ -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[] = [];
diff --git a/packages/chat/test/consumer.spec.tsx b/packages/chat/test/consumer.spec.tsx
index 92b7f43f0f..32b7271bf5 100644
--- a/packages/chat/test/consumer.spec.tsx
+++ b/packages/chat/test/consumer.spec.tsx
@@ -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 (
+
+ }
+ isCreatedByUser={message.isCreatedByUser}
+ >
+ {message.text}
+
+ );
+ },
+ };
+ const contract = {
+ index: 0,
+ isSubmitting: false,
+ latestMessageDepth: 0,
+ messagesKey: 'convo',
+ } as ChatContract;
+ render(
+
+
+
+
+
+
+
+
+ ,
+ );
+
+ 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');
+ });
});