diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts index 4b2e7b82d2..009799504f 100644 --- a/packages/chat/src/components.ts +++ b/packages/chat/src/components.ts @@ -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, diff --git a/packages/chat/src/components/messages/HoverButtons.tsx b/packages/chat/src/components/messages/HoverButtons.tsx index a1eea131c5..41fa755110 100644 --- a/packages/chat/src/components/messages/HoverButtons.tsx +++ b/packages/chat/src/components/messages/HoverButtons.tsx @@ -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 { diff --git a/packages/chat/src/components/messages/MessagesView.tsx b/packages/chat/src/components/messages/MessagesView.tsx index 5a0433077c..4828b796af 100644 --- a/packages/chat/src/components/messages/MessagesView.tsx +++ b/packages/chat/src/components/messages/MessagesView.tsx @@ -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({ <>
@@ -282,7 +289,11 @@ export default function MessagesView({ index, fullWidth: maximizeChatSpace, })} -
+
diff --git a/packages/chat/src/components/messages/__tests__/HoverButtons.spec.tsx b/packages/chat/src/components/messages/__tests__/HoverButtons.spec.tsx index 0d9fb5179a..953e196a73 100644 --- a/packages/chat/src/components/messages/__tests__/HoverButtons.spec.tsx +++ b/packages/chat/src/components/messages/__tests__/HoverButtons.spec.tsx @@ -37,8 +37,12 @@ const answer = { text: 'The answer is 4.', } as TMessage; -function renderButtons(overrides: Partial = {}, isSubmitting = false) { - const chat = { index: 0, isSubmitting } as ChatContract; +function renderButtons( + overrides: Partial = {}, + isSubmitting = false, + readOnly = false, +) { + const chat = { index: 0, isSubmitting, readOnly } as ChatContract; return render( @@ -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(); + }); }); diff --git a/packages/chat/src/components/pane/Followed.tsx b/packages/chat/src/components/pane/Followed.tsx new file mode 100644 index 0000000000..d9f3d0ab04 --- /dev/null +++ b/packages/chat/src/components/pane/Followed.tsx @@ -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 ( + + + + ); +} diff --git a/packages/chat/src/components/pane/__tests__/followed.spec.tsx b/packages/chat/src/components/pane/__tests__/followed.spec.tsx new file mode 100644 index 0000000000..0f87fae281 --- /dev/null +++ b/packages/chat/src/components/pane/__tests__/followed.spec.tsx @@ -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((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 | 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 }) => ( +
{`${message.messageId}=${message.text ?? ''}`}
+ ), +}); +const partsHost = createMessagePartsHost({ + renderContentParts: ({ messageId, content }) => ( +
{`${messageId}=${partsText(content)}`}
+ ), +}); +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; + nav?: boolean; +}): ReactElement { + const followed = useFollowChat({ id: 'thread-1', transport, loadMessages }); + return ( + , + ...(nav ? { renderNav: () =>
} : {}), + }} + /> + ); +} + +const mount = (ui: ReactElement) => + render( + + + (), + }, + claimForeground: () => undefined, + handOffComposerText: () => undefined, + }} + > + + {ui} + + + + , + ); + +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( 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( [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(); + 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( [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( [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(); + await waitFor(() => expect(rows()).toHaveLength(1)); + expect(screen.queryByTestId('rail')).toBeNull(); + unmount(); + + mount(); + await waitFor(() => expect(rows()).toHaveLength(1)); + expect(screen.getByTestId('rail')).toBeInTheDocument(); + }); +}); diff --git a/packages/chat/src/components/pane/load.ts b/packages/chat/src/components/pane/load.ts index 882651aac1..0596676aeb 100644 --- a/packages/chat/src/components/pane/load.ts +++ b/packages/chat/src/components/pane/load.ts @@ -7,3 +7,9 @@ export function loadScreenMessages(): Promise { 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 { + return import('./Followed'); +} diff --git a/packages/chat/src/components/pane/messages.tsx b/packages/chat/src/components/pane/messages.tsx index 8970575b71..542da78258 100644 --- a/packages/chat/src/components/pane/messages.tsx +++ b/packages/chat/src/components/pane/messages.tsx @@ -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 ( @@ -34,6 +39,7 @@ export default function ScreenMessages({ messages={messages} showScrollButton={showScrollButton} maximizeChatSpace={maximizeChatSpace} + primary={primary} /> ); diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.ts index db82830ea6..9fde07ebc7 100644 --- a/packages/chat/src/react.ts +++ b/packages/chat/src/react.ts @@ -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'; diff --git a/packages/chat/src/react/chat/contract.ts b/packages/chat/src/react/chat/contract.ts index 5c6f1cb824..cc8c2b92eb 100644 --- a/packages/chat/src/react/chat/contract.ts +++ b/packages/chat/src/react/chat/contract.ts @@ -112,6 +112,12 @@ export type ChatSubmissionContract = { handleRegenerate: (e: MouseEvent) => void; /** Button handler that continues the latest response from where it stopped. */ handleContinue: (e: MouseEvent) => 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`. */ diff --git a/packages/chat/src/react/chat/followed.ts b/packages/chat/src/react/chat/followed.ts new file mode 100644 index 0000000000..f40d23f309 --- /dev/null +++ b/packages/chat/src/react/chat/followed.ts @@ -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 => Promise.resolve(); +const noFiles: ChatContract['files'] = new Map(); +const noOptions: ChatContract['optionSettings'] = {}; +const noAttachments: Record = {}; +const useNoLiveAttachments = (): Record => noAttachments; + +/** Where the tail sits in its thread, which a streamed delta does not change. */ +const pickTailPlace = (tail: TMessage | null): Pick | 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( + () => ({ + 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, + ], + ); +} diff --git a/packages/chat/src/react/messages/__tests__/generations.spec.ts b/packages/chat/src/react/messages/__tests__/generations.spec.ts index c40d3ddaa9..c847fd07b6 100644 --- a/packages/chat/src/react/messages/__tests__/generations.spec.ts +++ b/packages/chat/src/react/messages/__tests__/generations.spec.ts @@ -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, + }); + }); }); diff --git a/packages/chat/src/react/messages/generations.ts b/packages/chat/src/react/messages/generations.ts index 23c55337fd..16a25b9c5a 100644 --- a/packages/chat/src/react/messages/generations.ts +++ b/packages/chat/src/react/messages/generations.ts @@ -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 || diff --git a/packages/chat/src/react/messages/view.tsx b/packages/chat/src/react/messages/view.tsx index cb92e52983..bb8f32e485 100644 --- a/packages/chat/src/react/messages/view.tsx +++ b/packages/chat/src/react/messages/view.tsx @@ -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( () => ({ - 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 (