mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-27 02:13:36 +00:00
📺 feat: Render Followed Chats With Main Chat's Message List (#18193)
* 🪟 feat: Draw a Followed Chat With Main Chat's Message List * 🪟 fix: Leave the Page's End Marker and Screenshot Target to the Main List * 🔒 fix: Make a Followed Thread Read-Only at the View, Not Only in Its Handlers * 🔒 chore: Sort the Followed Thread Spec's Imports
This commit is contained in:
parent
9306de83f1
commit
c0305236da
14 changed files with 610 additions and 11 deletions
|
|
@ -263,7 +263,8 @@ export type { ChatPaneView, ChatPaneColumn } from './components/pane/view';
|
|||
export { default as ChatScreen } from './components/pane/Screen';
|
||||
export { default as ChatStarters } from './components/pane/starters';
|
||||
export { getChatPaneChrome } from './components/pane/chrome';
|
||||
export { loadScreenMessages } from './components/pane/load';
|
||||
export { loadScreenMessages, loadFollowedThread } from './components/pane/load';
|
||||
export type { FollowedThreadProps } from './components/pane/Followed';
|
||||
export type {
|
||||
ChatScreenProps,
|
||||
ChatScreenComposerProps,
|
||||
|
|
|
|||
|
|
@ -151,7 +151,9 @@ const HoverButtons = ({
|
|||
const localize = useLocalize();
|
||||
/** Read from the pane's chat contract here rather than passed down: a send toggles the
|
||||
* rerun controls on every row, and only this toolbar has to re-render for it. */
|
||||
const isSubmitting = useContext(ChatContext)?.isSubmitting === true;
|
||||
const chat = useContext(ChatContext);
|
||||
const isSubmitting = chat?.isSubmitting === true;
|
||||
const readOnly = chat?.readOnly === true;
|
||||
const [isCopied, setIsCopied] = useState(false);
|
||||
const { useGetMessages, useHasPendingTurn } = useMessagesHost();
|
||||
const getMessages = useGetMessages();
|
||||
|
|
@ -203,6 +205,7 @@ const HoverButtons = ({
|
|||
parentIsUserMessage,
|
||||
isUserInitiatedCompaction: isUserInitiatedCompaction(message),
|
||||
latestMessageId: latestMessageId,
|
||||
readOnly,
|
||||
});
|
||||
|
||||
const {
|
||||
|
|
|
|||
|
|
@ -34,6 +34,12 @@ export type MessagesViewProps = {
|
|||
maximizeChatSpace: boolean;
|
||||
/** Renders the thread as a flat row list (the default) or, when `false`, as a recursive tree. */
|
||||
flatThread?: boolean;
|
||||
/**
|
||||
* Whether this is the page's main list, which owns the `messages-end` id and the screenshot
|
||||
* target that the app and its tests look up page-wide. A list mounted beside it passes `false`
|
||||
* and leaves both to the main one.
|
||||
*/
|
||||
primary?: 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. */
|
||||
|
|
@ -98,6 +104,7 @@ export default function MessagesView({
|
|||
showScrollButton,
|
||||
maximizeChatSpace,
|
||||
flatThread,
|
||||
primary = true,
|
||||
renderThread = renderDefaultThread,
|
||||
renderPendingTurn: renderPendingTurnSlot,
|
||||
renderPendingSteers: renderPendingSteersSlot,
|
||||
|
|
@ -248,9 +255,9 @@ export default function MessagesView({
|
|||
<>
|
||||
<div
|
||||
key={treeConversationId}
|
||||
ref={screenshotTargetRef}
|
||||
ref={primary ? screenshotTargetRef : undefined}
|
||||
data-conversation-id={treeConversationId}
|
||||
data-testid="screenshot-target"
|
||||
data-testid={primary ? 'screenshot-target' : undefined}
|
||||
>
|
||||
<RowMountProvider mountWindow={mountWindow}>
|
||||
<OffscreenRowsProvider observe={observeRow}>
|
||||
|
|
@ -282,7 +289,11 @@ export default function MessagesView({
|
|||
index,
|
||||
fullWidth: maximizeChatSpace,
|
||||
})}
|
||||
<div id="messages-end" className="group h-0 w-full shrink-0" ref={messagesEndRef} />
|
||||
<div
|
||||
id={primary ? 'messages-end' : undefined}
|
||||
className="group h-0 w-full shrink-0"
|
||||
ref={messagesEndRef}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
|
|
|||
|
|
@ -37,8 +37,12 @@ const answer = {
|
|||
text: 'The answer is 4.',
|
||||
} as TMessage;
|
||||
|
||||
function renderButtons(overrides: Partial<MessagesHost> = {}, isSubmitting = false) {
|
||||
const chat = { index: 0, isSubmitting } as ChatContract;
|
||||
function renderButtons(
|
||||
overrides: Partial<MessagesHost> = {},
|
||||
isSubmitting = false,
|
||||
readOnly = false,
|
||||
) {
|
||||
const chat = { index: 0, isSubmitting, readOnly } as ChatContract;
|
||||
return render(
|
||||
<ChatContext.Provider value={chat}>
|
||||
<MessagesHostProvider host={createMessagesHost(overrides)}>
|
||||
|
|
@ -107,4 +111,12 @@ describe('HoverButtons', () => {
|
|||
|
||||
expect(screen.queryByTestId('regenerate-generation-button')).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps copy and withholds rerun and edit where the reader takes no turn', () => {
|
||||
renderButtons({ useGetMessages: () => () => [question, answer] }, false, true);
|
||||
|
||||
expect(screen.queryByTestId('regenerate-generation-button')).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: 'Edit' })).toBeNull();
|
||||
expect(screen.getByRole('button', { name: 'Copy to clipboard' })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
61
packages/chat/src/components/pane/Followed.tsx
Normal file
61
packages/chat/src/components/pane/Followed.tsx
Normal file
|
|
@ -0,0 +1,61 @@
|
|||
import { useMemo } from 'react';
|
||||
import { buildTree } from 'librechat-data-provider';
|
||||
import type { TConversation } from 'librechat-data-provider';
|
||||
import type { ReactElement } from 'react';
|
||||
import type { ChatScreenMessagesSlots } from './messages';
|
||||
import type { FollowedChat } from '../../react/follow';
|
||||
import { useFollowedContract } from '../../react/chat/followed';
|
||||
import { ChatContext } from '../../react/chat/context';
|
||||
import ScreenMessages from './messages';
|
||||
|
||||
export type FollowedThreadProps = {
|
||||
/** The conversation followed. */
|
||||
id: string;
|
||||
followed: FollowedChat;
|
||||
/** The pane number the host keys per-pane state by; see `useFollowedContract`. */
|
||||
index: number;
|
||||
conversation: TConversation | null;
|
||||
/** Replacements for the list's slots, over the ones a followed conversation leaves empty. */
|
||||
slots?: ChatScreenMessagesSlots;
|
||||
};
|
||||
|
||||
const none = (): null => null;
|
||||
|
||||
/**
|
||||
* A followed conversation has no turn of the reader's waiting on it and no steers of theirs, and
|
||||
* a surface narrow enough to sit beside a chat has no room for the navigation rail.
|
||||
*/
|
||||
const followedSlots: ChatScreenMessagesSlots = {
|
||||
renderPendingTurn: none,
|
||||
renderPendingSteers: none,
|
||||
renderNav: none,
|
||||
};
|
||||
|
||||
/**
|
||||
* A followed conversation drawn by main chat's own message list: the same thread, rows, parts
|
||||
* and scrolling, reading a chat contract built from the followed `Chat`. The hosts those rows
|
||||
* read come from the tree it is mounted in. It is never the page's main list, so it leaves the
|
||||
* page-wide end marker and screenshot target to that one.
|
||||
*/
|
||||
export default function FollowedThread({
|
||||
id,
|
||||
followed,
|
||||
index,
|
||||
conversation,
|
||||
slots,
|
||||
}: FollowedThreadProps): ReactElement {
|
||||
const contract = useFollowedContract({ id, followed, index, conversation });
|
||||
const { messages } = followed;
|
||||
const messagesTree = useMemo(() => buildTree({ messages }), [messages]);
|
||||
const listSlots = useMemo(() => ({ ...followedSlots, ...slots }), [slots]);
|
||||
return (
|
||||
<ChatContext.Provider value={contract}>
|
||||
<ScreenMessages
|
||||
messagesTree={messagesTree}
|
||||
messages={messages}
|
||||
slots={listSlots}
|
||||
primary={false}
|
||||
/>
|
||||
</ChatContext.Provider>
|
||||
);
|
||||
}
|
||||
329
packages/chat/src/components/pane/__tests__/followed.spec.tsx
Normal file
329
packages/chat/src/components/pane/__tests__/followed.spec.tsx
Normal file
|
|
@ -0,0 +1,329 @@
|
|||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import { Provider, createStore } from 'jotai';
|
||||
import { act, render, screen, waitFor } from '@testing-library/react';
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
|
||||
import { Constants, StepTypes, StepEvents, ContentTypes } from 'librechat-data-provider';
|
||||
import type { TMessage, ChatEvent, TConversation } from 'librechat-data-provider';
|
||||
import type { ReactElement } from 'react';
|
||||
import type { ChatStream, ChatTransport, ChatStreamStatus } from '../../../core';
|
||||
import type { ChatContract } from '../../../react/chat/contract';
|
||||
import { createMessagePartsHost } from '../../../__fixtures__/partsHost';
|
||||
import { useIsMessagesViewReadOnly } from '../../../react/messages/view';
|
||||
import { createMessagesHost } from '../../../__fixtures__/messagesHost';
|
||||
import { ChatSurfaceProvider } from '../../../react/subagents/provider';
|
||||
import { MessagesHostProvider } from '../../../react/messages/host';
|
||||
import { MessagePartsHostProvider } from '../../../react/host';
|
||||
import { useChatContext } from '../../../react/chat/context';
|
||||
import { initEnglish } from '../../../__fixtures__/i18n';
|
||||
import { useFollowChat } from '../../../react/follow';
|
||||
import FollowedThread from '../Followed';
|
||||
|
||||
beforeAll(initEnglish);
|
||||
|
||||
type TestStream = ChatStream & { push(event: ChatEvent): void; closed: boolean };
|
||||
|
||||
const createStream = (): TestStream => {
|
||||
const queued: ChatEvent[] = [];
|
||||
let wake: (() => void) | undefined;
|
||||
const stream: TestStream = {
|
||||
closed: false,
|
||||
push(event) {
|
||||
queued.push(event);
|
||||
wake?.();
|
||||
},
|
||||
close() {
|
||||
stream.closed = true;
|
||||
wake?.();
|
||||
},
|
||||
async *[Symbol.asyncIterator]() {
|
||||
while (true) {
|
||||
while (queued.length > 0) {
|
||||
yield queued.shift() as ChatEvent;
|
||||
}
|
||||
if (stream.closed) {
|
||||
return;
|
||||
}
|
||||
await new Promise<void>((resolve) => {
|
||||
wake = resolve;
|
||||
});
|
||||
}
|
||||
},
|
||||
};
|
||||
return stream;
|
||||
};
|
||||
|
||||
const createTransport = (initial: ChatStreamStatus) => {
|
||||
const streams: TestStream[] = [];
|
||||
let status = initial;
|
||||
const transport: ChatTransport = {
|
||||
sendMessages: jest.fn(() => Promise.reject(new Error('view only'))),
|
||||
abort: jest.fn(() => Promise.reject(new Error('view only'))),
|
||||
getStatus: async () => status,
|
||||
reconnectToStream: async () => {
|
||||
if (!status.active) {
|
||||
return null;
|
||||
}
|
||||
const stream = createStream();
|
||||
streams.push(stream);
|
||||
return stream;
|
||||
},
|
||||
};
|
||||
return {
|
||||
transport,
|
||||
streams,
|
||||
setStatus: (next: ChatStreamStatus) => {
|
||||
status = next;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const brief: TMessage = {
|
||||
messageId: 'task-1:user',
|
||||
conversationId: 'thread-1',
|
||||
parentMessageId: Constants.NO_PARENT as string,
|
||||
isCreatedByUser: true,
|
||||
text: 'Research this',
|
||||
};
|
||||
|
||||
const answer = (id: string, parentMessageId: string, text: string): TMessage => ({
|
||||
messageId: id,
|
||||
conversationId: 'thread-1',
|
||||
parentMessageId,
|
||||
isCreatedByUser: false,
|
||||
text: '',
|
||||
content: [{ type: ContentTypes.TEXT, text }],
|
||||
});
|
||||
|
||||
const snapshot = (text: string): ChatEvent =>
|
||||
({
|
||||
type: 'sync',
|
||||
data: {
|
||||
sync: true,
|
||||
resumeState: {
|
||||
conversationId: 'thread-1',
|
||||
responseMessageId: 'task-1:assistant',
|
||||
userMessage: { ...brief },
|
||||
runSteps: [
|
||||
{
|
||||
id: 's0',
|
||||
runId: 'task-1:assistant',
|
||||
index: 0,
|
||||
type: StepTypes.MESSAGE_CREATION,
|
||||
stepDetails: {
|
||||
type: StepTypes.MESSAGE_CREATION,
|
||||
message_creation: { message_id: 's0' },
|
||||
},
|
||||
usage: null,
|
||||
},
|
||||
],
|
||||
aggregatedContent: [{ type: ContentTypes.TEXT, text }],
|
||||
},
|
||||
},
|
||||
}) as ChatEvent;
|
||||
|
||||
const token = (text: string): ChatEvent =>
|
||||
({
|
||||
type: 'step',
|
||||
data: {
|
||||
event: StepEvents.ON_MESSAGE_DELTA,
|
||||
data: { id: 's0', delta: { content: [{ type: ContentTypes.TEXT, text }] } },
|
||||
},
|
||||
}) as ChatEvent;
|
||||
|
||||
const final = (text: string): ChatEvent =>
|
||||
({
|
||||
type: 'final',
|
||||
data: {
|
||||
final: true,
|
||||
conversation: { conversationId: 'thread-1' },
|
||||
requestMessage: brief,
|
||||
responseMessage: answer('task-1:assistant', 'task-1:user', text),
|
||||
},
|
||||
}) as ChatEvent;
|
||||
|
||||
const partsText = (content: ReadonlyArray<object | undefined> | undefined): string =>
|
||||
(content ?? []).map((part) => (part as { text?: string } | undefined)?.text ?? '').join('');
|
||||
|
||||
/**
|
||||
* Rows render as `id=text`, so a spec reads which messages the real thread drew, and with what.
|
||||
* A text turn draws through the messages host and a content turn through the parts host, as in
|
||||
* the app.
|
||||
*/
|
||||
const messagesHost = createMessagesHost({
|
||||
renderMessageBody: ({ message }) => (
|
||||
<div data-testid="row">{`${message.messageId}=${message.text ?? ''}`}</div>
|
||||
),
|
||||
});
|
||||
const partsHost = createMessagePartsHost({
|
||||
renderContentParts: ({ messageId, content }) => (
|
||||
<div data-testid="row">{`${messageId}=${partsText(content)}`}</div>
|
||||
),
|
||||
});
|
||||
const conversation = { conversationId: 'thread-1', endpoint: 'agents' } as TConversation;
|
||||
|
||||
let contract: ChatContract | undefined;
|
||||
let viewReadOnly: boolean | undefined;
|
||||
|
||||
/** Reads the chat contract and the view mode the rows see, from inside the list. */
|
||||
function ContractProbe(): null {
|
||||
contract = useChatContext();
|
||||
viewReadOnly = useIsMessagesViewReadOnly();
|
||||
return null;
|
||||
}
|
||||
|
||||
function Pane({
|
||||
transport,
|
||||
loadMessages,
|
||||
nav,
|
||||
}: {
|
||||
transport: ChatTransport;
|
||||
loadMessages: () => Promise<TMessage[]>;
|
||||
nav?: boolean;
|
||||
}): ReactElement {
|
||||
const followed = useFollowChat({ id: 'thread-1', transport, loadMessages });
|
||||
return (
|
||||
<FollowedThread
|
||||
id="thread-1"
|
||||
index={2}
|
||||
followed={followed}
|
||||
conversation={conversation}
|
||||
slots={{
|
||||
renderScrollButton: () => <ContractProbe />,
|
||||
...(nav ? { renderNav: () => <div data-testid="rail" /> } : {}),
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const mount = (ui: ReactElement) =>
|
||||
render(
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<Provider store={createStore()}>
|
||||
<ChatSurfaceProvider
|
||||
value={{
|
||||
enterToSend: true,
|
||||
maximizeChatSpace: false,
|
||||
showScrollButton: false,
|
||||
composerBindings: {
|
||||
shortcutsEnabled: true,
|
||||
submitOverride: undefined,
|
||||
yieldedChords: new Set<string>(),
|
||||
},
|
||||
claimForeground: () => undefined,
|
||||
handOffComposerText: () => undefined,
|
||||
}}
|
||||
>
|
||||
<MessagesHostProvider host={messagesHost}>
|
||||
<MessagePartsHostProvider host={partsHost}>{ui}</MessagePartsHostProvider>
|
||||
</MessagesHostProvider>
|
||||
</ChatSurfaceProvider>
|
||||
</Provider>
|
||||
</QueryClientProvider>,
|
||||
);
|
||||
|
||||
const rows = () => screen.queryAllByTestId('row').map((row) => row.textContent);
|
||||
|
||||
const settle = () =>
|
||||
act(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
});
|
||||
|
||||
describe('FollowedThread', () => {
|
||||
beforeEach(() => {
|
||||
contract = undefined;
|
||||
viewReadOnly = undefined;
|
||||
});
|
||||
|
||||
it("draws the stored conversation with main chat's thread", async () => {
|
||||
const { transport } = createTransport({ active: false });
|
||||
const stored = [brief, answer('task-1:assistant', 'task-1:user', 'Done')];
|
||||
mount(<Pane transport={transport} loadMessages={async () => stored} />);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(rows()).toEqual(['task-1:user=Research this', 'task-1:assistant=Done']),
|
||||
);
|
||||
expect(contract).toMatchObject({
|
||||
index: 2,
|
||||
messagesKey: 'thread-1',
|
||||
readOnly: true,
|
||||
isSubmitting: false,
|
||||
latestMessageId: 'task-1:assistant',
|
||||
conversation: { conversationId: 'thread-1' },
|
||||
});
|
||||
expect(contract?.getMessages()).toEqual(stored);
|
||||
});
|
||||
|
||||
it('tells its rows the view is read-only, so host-bound actions in them stay off', async () => {
|
||||
const { transport } = createTransport({ active: false });
|
||||
mount(<Pane transport={transport} loadMessages={async () => [brief]} />);
|
||||
await waitFor(() => expect(rows()).toHaveLength(1));
|
||||
|
||||
expect(viewReadOnly).toBe(true);
|
||||
});
|
||||
|
||||
it('draws a running generation as it streams, then the stored result', async () => {
|
||||
const { transport, streams, setStatus } = createTransport({ active: true });
|
||||
const loadMessages = jest.fn(async () => [brief]);
|
||||
mount(<Pane transport={transport} loadMessages={loadMessages} />);
|
||||
await waitFor(() => expect(streams).toHaveLength(1));
|
||||
|
||||
act(() => streams[0].push(snapshot('Hel')));
|
||||
act(() => streams[0].push(token('lo')));
|
||||
await settle();
|
||||
|
||||
expect(rows()).toEqual(['task-1:user=Research this', 'task-1:assistant=Hello']);
|
||||
expect(contract?.isSubmitting).toBe(true);
|
||||
expect(contract?.latestMessageId).toBe('task-1:assistant');
|
||||
|
||||
loadMessages.mockResolvedValue([
|
||||
brief,
|
||||
answer('task-1:assistant', 'task-1:user', 'Hello, stored'),
|
||||
]);
|
||||
setStatus({ active: false });
|
||||
act(() => streams[0].push(final('Hello')));
|
||||
await waitFor(() =>
|
||||
expect(rows()).toEqual(['task-1:user=Research this', 'task-1:assistant=Hello, stored']),
|
||||
);
|
||||
expect(contract?.isSubmitting).toBe(false);
|
||||
});
|
||||
|
||||
it('takes no turn: sending, regenerating and stopping reach nothing', async () => {
|
||||
const { transport } = createTransport({ active: false });
|
||||
mount(<Pane transport={transport} loadMessages={async () => [brief]} />);
|
||||
await waitFor(() => expect(rows()).toHaveLength(1));
|
||||
|
||||
await act(async () => {
|
||||
contract?.ask({ text: 'hello' });
|
||||
contract?.regenerate({ parentMessageId: 'task-1:user' });
|
||||
await contract?.stopGenerating();
|
||||
});
|
||||
|
||||
expect(transport.sendMessages).not.toHaveBeenCalled();
|
||||
expect(transport.abort).not.toHaveBeenCalled();
|
||||
expect(rows()).toEqual(['task-1:user=Research this']);
|
||||
});
|
||||
|
||||
it("leaves the page's end marker and screenshot target to the main list", async () => {
|
||||
const { transport } = createTransport({ active: false });
|
||||
mount(<Pane transport={transport} loadMessages={async () => [brief]} />);
|
||||
await waitFor(() => expect(rows()).toHaveLength(1));
|
||||
|
||||
expect(document.getElementById('messages-end')).toBeNull();
|
||||
expect(screen.queryByTestId('screenshot-target')).toBeNull();
|
||||
});
|
||||
|
||||
it('leaves the navigation rail out unless a host supplies one', async () => {
|
||||
const { transport } = createTransport({ active: false });
|
||||
const load = async () => [brief];
|
||||
const { unmount } = mount(<Pane transport={transport} loadMessages={load} />);
|
||||
await waitFor(() => expect(rows()).toHaveLength(1));
|
||||
expect(screen.queryByTestId('rail')).toBeNull();
|
||||
unmount();
|
||||
|
||||
mount(<Pane transport={transport} loadMessages={load} nav />);
|
||||
await waitFor(() => expect(rows()).toHaveLength(1));
|
||||
expect(screen.getByTestId('rail')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
@ -7,3 +7,9 @@
|
|||
export function loadScreenMessages(): Promise<typeof import('./messages')> {
|
||||
return import('./messages');
|
||||
}
|
||||
|
||||
/** The followed conversation's list is `messages` under another chat contract, so it loads the
|
||||
* same way and shares that chunk. */
|
||||
export function loadFollowedThread(): Promise<typeof import('./Followed')> {
|
||||
return import('./Followed');
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,7 +24,12 @@ export default function ScreenMessages({
|
|||
messagesTree,
|
||||
messages,
|
||||
slots,
|
||||
}: ChatScreenMessagesProps & { slots?: ChatScreenMessagesSlots }): ReactElement {
|
||||
primary,
|
||||
}: ChatScreenMessagesProps & {
|
||||
slots?: ChatScreenMessagesSlots;
|
||||
/** `false` for a list mounted beside the page's main one; see `MessagesViewProps.primary`. */
|
||||
primary?: boolean;
|
||||
}): ReactElement {
|
||||
const { showScrollButton, maximizeChatSpace } = useChatSurface();
|
||||
return (
|
||||
<MessagesViewProvider>
|
||||
|
|
@ -34,6 +39,7 @@ export default function ScreenMessages({
|
|||
messages={messages}
|
||||
showScrollButton={showScrollButton}
|
||||
maximizeChatSpace={maximizeChatSpace}
|
||||
primary={primary}
|
||||
/>
|
||||
</MessagesViewProvider>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -128,6 +128,8 @@ export {
|
|||
export { useCoreChat } from './react/core';
|
||||
export { useFollowChat } from './react/follow';
|
||||
export type { FollowChatOptions, FollowedChat } from './react/follow';
|
||||
export { useFollowedContract } from './react/chat/followed';
|
||||
export type { FollowedContractOptions } from './react/chat/followed';
|
||||
export { useSnapshot } from './react/snapshot';
|
||||
export { ReactQueryChatState } from './react/state';
|
||||
export type { Subscribe, SnapshotOptions } from './react/snapshot';
|
||||
|
|
|
|||
|
|
@ -112,6 +112,12 @@ export type ChatSubmissionContract = {
|
|||
handleRegenerate: (e: MouseEvent<HTMLButtonElement>) => void;
|
||||
/** Button handler that continues the latest response from where it stopped. */
|
||||
handleContinue: (e: MouseEvent<HTMLButtonElement>) => void;
|
||||
/**
|
||||
* The reader takes no turn in this conversation, as in one they follow rather than drive: its
|
||||
* rows offer no rerun, edit or continue, and a recovery prompt is explained rather than offered.
|
||||
* Absent for a chat the reader drives.
|
||||
*/
|
||||
readOnly?: boolean;
|
||||
};
|
||||
|
||||
/** Stopping an in-flight turn. AI SDK: `stop`. */
|
||||
|
|
|
|||
121
packages/chat/src/react/chat/followed.ts
Normal file
121
packages/chat/src/react/chat/followed.ts
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
import { useMemo, useState, useCallback } from 'react';
|
||||
import { useSetAtom } from 'jotai';
|
||||
import type { TMessage, TAttachment, TConversation } from 'librechat-data-provider';
|
||||
import type { ChatContract } from './contract';
|
||||
import type { FollowedChat } from '../follow';
|
||||
import { useBranchTailId, useBranchTailSelect } from '../latest';
|
||||
import { siblingIdxFamily, siblingKey } from '../thread';
|
||||
import { getMappingOptions } from '../../core';
|
||||
|
||||
export type FollowedContractOptions = {
|
||||
/** The conversation followed, which keys its messages in the cache. */
|
||||
id: string;
|
||||
followed: FollowedChat;
|
||||
/**
|
||||
* The pane number a host keys its per-pane state by. Never one a driven chat renders into, or
|
||||
* the two would share that state.
|
||||
*/
|
||||
index: number;
|
||||
/** What the rows read of the conversation: its id, endpoint and agent. */
|
||||
conversation: TConversation | null;
|
||||
};
|
||||
|
||||
const ignore = (): void => undefined;
|
||||
const stopped = (): Promise<void> => Promise.resolve();
|
||||
const noFiles: ChatContract['files'] = new Map();
|
||||
const noOptions: ChatContract['optionSettings'] = {};
|
||||
const noAttachments: Record<string, TAttachment[] | undefined> = {};
|
||||
const useNoLiveAttachments = (): Record<string, TAttachment[] | undefined> => noAttachments;
|
||||
|
||||
/** Where the tail sits in its thread, which a streamed delta does not change. */
|
||||
const pickTailPlace = (tail: TMessage | null): Pick<TMessage, 'depth' | 'parentMessageId'> | null =>
|
||||
tail && { depth: tail.depth, parentMessageId: tail.parentMessageId };
|
||||
|
||||
/**
|
||||
* The chat contract the message rows read, over a conversation that is followed rather than
|
||||
* driven. Reading is real: the list, its revisions, the tail of the branch on screen, whether a
|
||||
* generation is running. Everything that would take a turn (send, regenerate, continue, stop,
|
||||
* files, a new conversation) does nothing, because the reader does not drive this conversation.
|
||||
*/
|
||||
export function useFollowedContract({
|
||||
id,
|
||||
followed,
|
||||
index,
|
||||
conversation,
|
||||
}: FollowedContractOptions): ChatContract {
|
||||
const { chat, status } = followed;
|
||||
const [abortScroll, setAbortScroll] = useState(false);
|
||||
const tailPlace = useBranchTailSelect(id, id, pickTailPlace);
|
||||
const latestMessageId = useBranchTailId(id, id) ?? undefined;
|
||||
const latestMessageDepth = tailPlace?.depth;
|
||||
const setSiblingIdx = useSetAtom(siblingIdxFamily(siblingKey(tailPlace?.parentMessageId)));
|
||||
const isSubmitting = status === 'submitted' || status === 'streaming';
|
||||
|
||||
const getMessages = useCallback(
|
||||
(targetConversationId?: string | null) =>
|
||||
targetConversationId == null || targetConversationId === id ? chat?.messages : undefined,
|
||||
[chat, id],
|
||||
);
|
||||
const setMessages = useCallback(
|
||||
(messages: TMessage[]) => void chat?.setMessages(messages),
|
||||
[chat],
|
||||
);
|
||||
const subscribeMessages = useCallback(
|
||||
(onChange: () => void) => chat?.subscribe(onChange) ?? ignore,
|
||||
[chat],
|
||||
);
|
||||
const getMessagesRevision = useCallback(() => chat?.version ?? 0, [chat]);
|
||||
|
||||
return useMemo<ChatContract>(
|
||||
() => ({
|
||||
index,
|
||||
conversation,
|
||||
setConversation: ignore,
|
||||
newConversation: ignore,
|
||||
preset: null,
|
||||
setPreset: ignore,
|
||||
optionSettings: noOptions,
|
||||
setOptionSettings: ignore,
|
||||
getMessages,
|
||||
messagesKey: id,
|
||||
setMessages,
|
||||
subscribeMessages,
|
||||
getMessagesRevision,
|
||||
setSiblingIdx,
|
||||
latestMessageId,
|
||||
latestMessageDepth,
|
||||
useLiveAttachments: useNoLiveAttachments,
|
||||
ask: ignore,
|
||||
regenerate: ignore,
|
||||
isSubmitting,
|
||||
setIsSubmitting: ignore,
|
||||
handleRegenerate: ignore,
|
||||
handleContinue: ignore,
|
||||
readOnly: true,
|
||||
stopGenerating: stopped,
|
||||
handleStopGenerating: ignore,
|
||||
abortScroll,
|
||||
setAbortScroll,
|
||||
files: noFiles,
|
||||
setFiles: ignore,
|
||||
filesLoading: false,
|
||||
setFilesLoading: ignore,
|
||||
feedbackEnabled: false,
|
||||
getMappingOptions,
|
||||
}),
|
||||
[
|
||||
id,
|
||||
index,
|
||||
conversation,
|
||||
getMessages,
|
||||
setMessages,
|
||||
subscribeMessages,
|
||||
getMessagesRevision,
|
||||
setSiblingIdx,
|
||||
latestMessageId,
|
||||
latestMessageDepth,
|
||||
isSubmitting,
|
||||
abortScroll,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
|
@ -27,4 +27,32 @@ describe('useGenerationsByLatest', () => {
|
|||
|
||||
expect(result.continueSupported).toBe(true);
|
||||
});
|
||||
|
||||
it('offers no rerun, edit or continue in a conversation the reader takes no turn in', () => {
|
||||
const driven = useGenerationsByLatest({
|
||||
...base,
|
||||
finish_reason: 'length',
|
||||
parentIsUserMessage: true,
|
||||
});
|
||||
const followed = useGenerationsByLatest({
|
||||
...base,
|
||||
finish_reason: 'length',
|
||||
parentIsUserMessage: true,
|
||||
readOnly: true,
|
||||
});
|
||||
|
||||
expect(driven).toMatchObject({
|
||||
regenerateOffered: true,
|
||||
regenerateEnabled: true,
|
||||
continueSupported: true,
|
||||
hideEditButton: false,
|
||||
});
|
||||
expect(followed).toMatchObject({
|
||||
regenerateOffered: false,
|
||||
regenerateEnabled: false,
|
||||
continueSupported: false,
|
||||
hideEditButton: true,
|
||||
forkingSupported: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -18,6 +18,9 @@ export type TUseGenerations = {
|
|||
* would replay, `false` when no such turn is in the thread. `undefined` when the
|
||||
* thread is unavailable (a search or share row), which withholds nothing. */
|
||||
parentIsUserMessage?: boolean;
|
||||
/** The reader takes no turn in this conversation, so no rerun, edit or continue is offered.
|
||||
* A fork still is: it makes a conversation of the reader's own. */
|
||||
readOnly?: boolean;
|
||||
/** The turn carries the server's manual-compaction marker. Compact runs on
|
||||
* whatever leaf the branch ends with, so such a turn can hang off a user
|
||||
* message; replaying that message would answer it again instead of redoing the
|
||||
|
|
@ -53,6 +56,7 @@ export default function useGenerationsByLatest({
|
|||
getHasEditablePart,
|
||||
parentIsUserMessage,
|
||||
isUserInitiatedCompaction = false,
|
||||
readOnly = false,
|
||||
}: TUseGenerations): Generations {
|
||||
const isEditableEndpoint = Boolean(
|
||||
[
|
||||
|
|
@ -88,6 +92,7 @@ export default function useGenerationsByLatest({
|
|||
!isSubmitting &&
|
||||
!searchResult &&
|
||||
!hasNoTurnToReplay &&
|
||||
!readOnly &&
|
||||
isEditableEndpoint;
|
||||
|
||||
const branchingSupported = Boolean(
|
||||
|
|
@ -103,7 +108,12 @@ export default function useGenerationsByLatest({
|
|||
);
|
||||
|
||||
const regenerateOffered =
|
||||
!isCreatedByUser && !searchResult && !isEditing && !hasNoTurnToReplay && branchingSupported;
|
||||
!isCreatedByUser &&
|
||||
!searchResult &&
|
||||
!isEditing &&
|
||||
!hasNoTurnToReplay &&
|
||||
!readOnly &&
|
||||
branchingSupported;
|
||||
const regenerateEnabled = regenerateOffered && !isSubmitting;
|
||||
|
||||
const isActiveStreamingMessage =
|
||||
|
|
@ -115,6 +125,7 @@ export default function useGenerationsByLatest({
|
|||
* finished or persisted an error part instead, would open an editor with no
|
||||
* field and one inert Rerun. */
|
||||
const hideEditButton =
|
||||
readOnly ||
|
||||
isActiveStreamingMessage ||
|
||||
error ||
|
||||
searchResult ||
|
||||
|
|
|
|||
|
|
@ -79,6 +79,7 @@ export function MessagesViewProvider({ children }: { children: ReactNode }): Rea
|
|||
const {
|
||||
ask,
|
||||
index,
|
||||
readOnly,
|
||||
regenerate,
|
||||
isSubmitting,
|
||||
conversation,
|
||||
|
|
@ -135,13 +136,14 @@ export function MessagesViewProvider({ children }: { children: ReactNode }): Rea
|
|||
/** Combine all values into final context value */
|
||||
const contextValue = useMemo<MessagesViewContextValue>(
|
||||
() => ({
|
||||
readOnly: false,
|
||||
/** A contract whose reader takes no turns keeps host-bound actions in its rows off too. */
|
||||
readOnly: readOnly === true,
|
||||
...conversationValues,
|
||||
...submissionStates,
|
||||
...messageOperations,
|
||||
...messageState,
|
||||
}),
|
||||
[conversationValues, submissionStates, messageOperations, messageState],
|
||||
[readOnly, conversationValues, submissionStates, messageOperations, messageState],
|
||||
);
|
||||
|
||||
return (
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue