📋 refactor: Move the Copy Footer and Action Gate into @librechat/chat (#17585)

* refactor: Move useGenerationsByLatest and MinimalHoverButtons into @librechat/chat

* test: Give the Consumer Spec Messages Host the Copy Member
This commit is contained in:
Marco Beretta 2026-11-01 00:38:11 +01:00 • committed by GitHub
parent 76f9246497
commit 2cd70ebaf7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 156 additions and 54 deletions

View file

@ -4,12 +4,20 @@ import { useRecoilState } from 'recoil';
import { setDefaultMessagesHost } from '@librechat/chat/react';
import type {
ForkEvents,
MessageCopy,
MessagesHost,
MessageCopyInput,
ForkPreferences,
ForkConversation,
MessagesScrolling,
} from '@librechat/chat/react';
import type { TMessage } from 'librechat-data-provider';
import {
hasCopyableText,
useNavigateToConvo,
getMessageClipboardSource,
useCopyMessageToClipboard,
} from '~/hooks';
import useConversationSeen from '~/hooks/Conversations/useConversationSeen';
import useMessageScrolling from '~/hooks/Messages/useMessageScrolling';
import MessageIcon from '~/components/Chat/Messages/MessageIcon';
@ -18,7 +26,6 @@ import { useScreenshot } from '~/hooks/ScreenshotContext';
import { useForkConvoMutation } from '~/data-provider';
import useClockFormat from '~/hooks/useClockFormat';
import { autoScrollAtom } from '~/store/autoScroll';
import { useNavigateToConvo } from '~/hooks';
import store from '~/store';
function useAppForkPreferences(): ForkPreferences {
@ -65,16 +72,30 @@ function useScrolling(messagesTree: TMessage[] | null | undefined): MessagesScro
return { ...scrolling, conversationId: conversation?.conversationId };
}
function useAppMessageCopy({ message, searchResults, variant }: MessageCopyInput): MessageCopy {
const clipboardSource = useMemo(() => getMessageClipboardSource(message), [message]);
const copyToClipboard = useCopyMessageToClipboard({
...clipboardSource,
searchResults,
variant: clipboardSource.variant ?? variant,
});
const canCopy = useMemo(
() => hasCopyableText({ ...clipboardSource, searchResults }),
[clipboardSource, searchResults],
);
return { copyToClipboard, canCopy };
}
/** What the message list reads from the app: the viewer's clock format and fork defaults, the
* fork request, 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, 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. */
export const appMessagesHost: MessagesHost = {
useHour12: useClockFormat,
renderFiles: (message) => <Files message={message} />,
useForkPreferences: useAppForkPreferences,
useForkConversation: useAppForkConversation,
useMessageCopy: useAppMessageCopy,
useScrolling,
useScreenshotTarget: () => useScreenshot().screenshotTargetRef,
useAutoScroll: () => useAtomValue(autoScrollAtom),

View file

@ -3,8 +3,8 @@ import { Copy, Check } from 'lucide';
import { useAtomValue } from 'jotai';
import { useRecoilState } from 'recoil';
import { hasEditablePart } from '@librechat/chat';
import { revealedQueuedTurnFamily } from '@librechat/chat/react';
import { hoverButtonClasses, Fork, Feedback } from '@librechat/chat/components';
import { useGenerationsByLatest, revealedQueuedTurnFamily } from '@librechat/chat/react';
import { getSpeechText, findMessageById, isUserInitiatedCompaction } from 'librechat-data-provider';
import {
Button,
@ -16,8 +16,8 @@ import {
} from '@librechat/client';
import type { TConversation, TMessage, TFeedback } from 'librechat-data-provider';
import { useMessagesIsSubmitting, useOptionalMessagesOperations } from '~/Providers';
import { useGenerationsByLatest, useLocalize } from '~/hooks';
import MessageAudio from './MessageAudio';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
import store from '~/store';

View file

@ -5,11 +5,11 @@ import {
MessageRow,
AuthorHeader,
getHeaderModelName,
MinimalHoverButtons,
getMessageRowWidthClass,
} from '@librechat/chat/components';
import type { TMessage } from 'librechat-data-provider';
import type { TMessageProps, TMessageIcon } from '~/common';
import MinimalHoverButtons from '~/components/Chat/Messages/MinimalHoverButtons';
import { getHeaderPrefixForScreenReader, getMessageAriaLabel } from '~/utils';
import SearchContent, { rendersMarkdownLite } from './Content/SearchContent';
import Icon from '~/components/Chat/Messages/MessageIcon';

View file

@ -48,9 +48,9 @@ jest.mock('~/Providers/MessagePartsHostContext', () => {
};
});
jest.mock('~/components/Chat/Messages/MinimalHoverButtons', () => ({
__esModule: true,
default: ({ message }: { message: TMessage }) => {
jest.mock('@librechat/chat/components', () => ({
...jest.requireActual('@librechat/chat/components'),
MinimalHoverButtons: ({ message }: { message: TMessage }) => {
mockCopyMessage(message);
return <button type="button" aria-label="copy" />;
},

View file

@ -25,6 +25,7 @@ import {
SubagentActivityContent,
SubagentStatus,
getActivityContent,
MinimalHoverButtons,
} from '@librechat/chat/components';
import type { ChildConversationTurn, ToolContentQuery, TurnAuthor } from '@librechat/chat/react';
import type { TMessage, TMessageContentParts } from 'librechat-data-provider';
@ -41,7 +42,6 @@ import { MessagePartsHostProvider, useMessagePartsHost } from '~/Providers/Messa
import ResumeAuthorHeader from '~/components/Chat/Messages/Content/Parts/ResumeAuthorHeader';
import { useSearchResultsByTurn } from '~/hooks/Messages/useSearchResultsByTurn';
import { ErrorSourceProvider } from '~/components/Messages/Content/Error/source';
import MinimalHoverButtons from '~/components/Chat/Messages/MinimalHoverButtons';
import ContentParts from '~/components/Chat/Messages/Content/ContentParts';
import { AuthorContext } from '~/Providers/AuthorContext';
import { ChatContext } from '~/Providers/ChatContext';

View file

@ -6,12 +6,12 @@ import {
AuthorHeader,
SiblingSwitch,
getHeaderHoverLabel,
MinimalHoverButtons,
} from '@librechat/chat/components';
import type { TMessageProps } from '~/common';
import SearchContent, {
rendersMarkdownLite,
} from '~/components/Chat/Messages/Content/SearchContent';
import MinimalHoverButtons from '~/components/Chat/Messages/MinimalHoverButtons';
import MessageContent from '~/components/Chat/Messages/Content/MessageContent';
import { getHeaderPrefixForScreenReader, getMessageAriaLabel } from '~/utils';
import WakeupRow from '~/components/Chat/Messages/ui/WakeupRow';

View file

@ -8,6 +8,7 @@ import type { TMessage, TAgentsMap } from 'librechat-data-provider';
import { ShareMessagesProvider } from './ShareMessagesProvider';
import { AgentsMapContext } from '~/Providers/AgentsMapContext';
import { ShareContext } from '~/Providers/ShareContext';
import '~/Providers/MessagesHostContext';
import MessagesView from './MessagesView';
import '~/Providers/MessagePartsHostContext';
import '~/Providers/MessagesHostContext';
@ -303,6 +304,6 @@ it('copies only the visible public wake-up result through its real footer', () =
const clipboard = jest.mocked(copy);
clipboard.mockReturnValue(true);
renderShared(prompt(), true);
fireEvent.click(screen.getByRole('button', { name: 'com_ui_copy_to_clipboard' }));
fireEvent.click(screen.getByRole('button', { name: 'Copy to clipboard' }));
expect(clipboard).toHaveBeenCalledWith('Shared durable result.', expect.anything());
});

View file

@ -38,7 +38,6 @@ export { default as useIsActiveItem } from './useIsActiveItem';
export { default as useLocalStorage } from './useLocalStorage';
export { default as useDocumentTitle } from './useDocumentTitle';
export { default as useSpeechToText } from './Input/useSpeechToText';
export { default as useGenerationsByLatest } from './useGenerationsByLatest';
export { default as useLocalizedConfig } from './useLocalizedConfig';
export { default as useResourcePermissions } from './useResourcePermissions';
export { useRoleSelector } from './useRoleSelector';

View file

@ -408,14 +408,6 @@
"count": 1
}
},
"client/src/components/Chat/Messages/MinimalHoverButtons.tsx": {
"shadcn/no-restyle": {
"count": 2
},
"shadcn/require-static-classes": {
"count": 1
}
},
"client/src/components/Chat/ProjectLandingChip.tsx": {
"shadcn/no-restyle": {
"count": 14
@ -1383,6 +1375,14 @@
"count": 1
}
},
"packages/chat/src/components/messages/MinimalHoverButtons.tsx": {
"shadcn/no-restyle": {
"count": 2
},
"shadcn/require-static-classes": {
"count": 1
}
},
"packages/chat/src/components/messages/ScrollToBottom.tsx": {
"shadcn/no-restyle": {
"count": 1

View file

@ -1,7 +1,7 @@
import type { MessagesHost } from '../react/messages/host';
/** A messages host for specs: locale clock, no slots, no forking, inert scrolling, with the
* members a spec needs overridden. */
/** A messages host for specs: locale clock, no slots, no forking, no copying, inert scrolling,
* with the members a spec needs overridden. */
export function createMessagesHost(overrides: Partial<MessagesHost> = {}): MessagesHost {
return {
useHour12: () => undefined,
@ -15,6 +15,7 @@ export function createMessagesHost(overrides: Partial<MessagesHost> = {}): Messa
setRememberOption: () => undefined,
}),
useForkConversation: () => null,
useMessageCopy: () => ({ copyToClipboard: () => undefined, canCopy: false }),
useScrolling: () => ({
contentRef: { current: null },
scrollableRef: { current: null },

View file

@ -82,6 +82,7 @@ export { isValidTimestamp, getMessageTimestamp } from './components/messages/tim
export type { MessageTimestamp as MessageTimestampParts } from './components/messages/time';
export { default as Fork } from './components/messages/Fork';
export { default as Feedback } from './components/messages/Feedback';
export { default as MinimalHoverButtons } from './components/messages/MinimalHoverButtons';
/** Parts: the leaf components and row classes tool cards share. */
export { default as Stdout } from './components/parts/Stdout';

View file

@ -1,16 +1,11 @@
import { useState, useMemo } from 'react';
import { useState } from 'react';
import { Copy, Check } from 'lucide';
import { revealOnRowHoverClasses } from '@librechat/chat/components';
import { Button, MorphIcon, TooltipAnchor } from '@librechat/client';
import { cn, Button, MorphIcon, useLocalize, TooltipAnchor } from '@librechat/client';
import type { TMessage, SearchResultData } from 'librechat-data-provider';
import type { MarkdownVariant } from '~/utils/richtext';
import {
useLocalize,
useCopyMessageToClipboard,
getMessageClipboardSource,
hasCopyableText,
} from '~/hooks';
import { cn } from '~/utils';
import type { ReactNode } from 'react';
import type { MarkdownVariant } from '../../react/messages/host';
import { useMessagesHost } from '../../react/messages/host';
import { revealOnRowHoverClasses } from './styles';
type THoverButtons = {
message: TMessage;
@ -19,19 +14,15 @@ type THoverButtons = {
variant?: MarkdownVariant;
};
export default function MinimalHoverButtons({ message, searchResults, variant }: THoverButtons) {
export default function MinimalHoverButtons({
message,
searchResults,
variant,
}: THoverButtons): ReactNode {
const localize = useLocalize();
const { useMessageCopy } = useMessagesHost();
const [isCopied, setIsCopied] = useState(false);
const clipboardSource = useMemo(() => getMessageClipboardSource(message), [message]);
const copyToClipboard = useCopyMessageToClipboard({
...clipboardSource,
searchResults,
variant: clipboardSource.variant ?? variant,
});
const canCopy = useMemo(
() => hasCopyableText({ ...clipboardSource, searchResults }),
[clipboardSource, searchResults],
);
const { copyToClipboard, canCopy } = useMessageCopy({ message, searchResults, variant });
return (
<div className="text-text-tertiary visible mt-1 flex justify-center gap-1 self-end lg:justify-start">

View file

@ -0,0 +1,49 @@
/**
* @jest-environment jsdom
*/
import { fireEvent, render, screen } from '@testing-library/react';
import type { TMessage } from 'librechat-data-provider';
import type { MessageCopy, MessageCopyInput } from '../../../react/messages/host';
import { createMessagesHost } from '../../../__fixtures__/messagesHost';
import { MessagesHostProvider } from '../../../react/messages/host';
import MinimalHoverButtons from '../MinimalHoverButtons';
jest.mock('@librechat/client', () => ({
...jest.requireActual('@librechat/client'),
useLocalize: () => (key: string) => key,
}));
const message = { messageId: 'm1', text: 'Shared result.', isCreatedByUser: false } as TMessage;
function renderWithCopy(useMessageCopy: (input: MessageCopyInput) => MessageCopy) {
const host = createMessagesHost({ useMessageCopy });
return render(
<MessagesHostProvider host={host}>
<MinimalHoverButtons message={message} variant="lite" />
</MessagesHostProvider>,
);
}
describe('MinimalHoverButtons', () => {
it('asks the host to copy the row and shows the copied state it reports', () => {
const useMessageCopy = jest.fn<MessageCopy, [MessageCopyInput]>(() => ({
copyToClipboard: (setIsCopied) => setIsCopied(true),
canCopy: true,
}));
renderWithCopy(useMessageCopy);
expect(useMessageCopy).toHaveBeenCalledWith({
message,
searchResults: undefined,
variant: 'lite',
});
fireEvent.click(screen.getByRole('button', { name: 'com_ui_copy_to_clipboard' }));
expect(screen.getByRole('button', { name: 'com_ui_copied_to_clipboard' })).toBeInTheDocument();
});
it('disables the copy control when the host cannot copy', () => {
renderWithCopy(() => ({ copyToClipboard: jest.fn(), canCopy: false }));
expect(screen.getByRole('button', { name: 'com_ui_copy_to_clipboard' })).toBeDisabled();
});
});

View file

@ -125,6 +125,8 @@ export { composerLiftFamily } from './react/lift';
export { showSkillsPopoverFamily } from './react/skills';
export { useComposerOverlay, composerOverlayCountFamily } from './react/overlay';
export { default as useTimeTick } from './react/tick';
export { default as useGenerationsByLatest } from './react/messages/generations';
export type { Generations, TUseGenerations } from './react/messages/generations';
export {
useMessagesHost,
MessagesHostProvider,
@ -133,7 +135,10 @@ export {
} from './react/messages/host';
export type {
ForkEvents,
MessageCopy,
MessagesHost,
MarkdownVariant,
MessageCopyInput,
ForkPreferences,
ForkConversation,
MessagesScrolling,

View file

@ -1,5 +1,5 @@
import { Constants, EModelEndpoint } from 'librechat-data-provider';
import useGenerationsByLatest from '../useGenerationsByLatest';
import useGenerationsByLatest from '../generations';
const base = {
endpoint: EModelEndpoint.agents,

View file

@ -1,6 +1,6 @@
import { Constants, EModelEndpoint, isAssistantsEndpoint } from 'librechat-data-provider';
type TUseGenerations = {
export type TUseGenerations = {
error?: boolean;
endpoint?: string;
messageId?: string;
@ -25,6 +25,16 @@ type TUseGenerations = {
isUserInitiatedCompaction?: boolean;
};
/** Which rerun, edit, continue and fork controls a message row offers. */
export type Generations = {
forkingSupported: boolean;
continueSupported: boolean;
regenerateEnabled: boolean;
isActiveStreamingMessage: boolean;
isEditableEndpoint: boolean;
hideEditButton: boolean;
};
export default function useGenerationsByLatest({
error = false,
endpoint,
@ -38,7 +48,7 @@ export default function useGenerationsByLatest({
getHasEditablePart,
parentIsUserMessage,
isUserInitiatedCompaction = false,
}: TUseGenerations) {
}: TUseGenerations): Generations {
const isEditableEndpoint = Boolean(
[
EModelEndpoint.openAI,

View file

@ -4,9 +4,10 @@ import type {
TMessage,
Assistant,
TConversation,
SearchResultData,
TForkConvoRequest,
} from 'librechat-data-provider';
import type { MouseEvent, ReactNode, RefObject } from 'react';
import type { Dispatch, ReactNode, MouseEvent, RefObject, SetStateAction } from 'react';
/** The scroll machinery of the message list, as the app's scrolling hook drives it. */
export type MessagesScrolling = {
@ -51,6 +52,24 @@ export type ForkEvents = {
/** Starts a fork of a conversation. */
export type ForkConversation = (request: TForkConvoRequest, events: ForkEvents) => void;
/** The renderer a message is displayed with: `full` for model text, `lite` for user markdown. */
export type MarkdownVariant = 'full' | 'lite';
/** What a row asks the host to copy. */
export type MessageCopyInput = {
message: TMessage;
/** Search results the message cites, resolved into the copied text. */
searchResults?: { [key: string]: SearchResultData };
/** The renderer the row displayed the message with, when it is not the authorship default. */
variant?: MarkdownVariant;
};
/** A row's copy action: `copyToClipboard` flips `setIsCopied` on while the copied state shows. */
export type MessageCopy = {
copyToClipboard: (setIsCopied: Dispatch<SetStateAction<boolean>>) => void;
canCopy: boolean;
};
/** What a message author's icon is drawn from: the endpoint and model, or the agent or
* assistant that wrote it. */
export type MessageIconData = { endpoint?: string | null; isCreatedByUser?: boolean } & Pick<
@ -83,7 +102,8 @@ export interface MessagesHost {
useForkPreferences: () => ForkPreferences;
/** Forks a conversation and opens the copy; `null` where forking is unavailable. */
useForkConversation: () => ForkConversation | null;
/** Copies a message the way the app renders it; `canCopy` is `false` where copying is unavailable. */
useMessageCopy: (input: MessageCopyInput) => MessageCopy;
/**
* Drives the list's scrolling: follows the stream, lands on a conversation's end and keeps
* the reader's position.
@ -111,6 +131,8 @@ export interface MessagesHost {
const noop = (): void => undefined;
const fallbackMessageCopy: MessageCopy = { copyToClipboard: noop, canCopy: false };
const fallbackForkPreferences: ForkPreferences = {
option: '',
setOption: noop,
@ -137,13 +159,14 @@ function useInertScrolling(): MessagesScrolling {
const ignoreNearBottom: ReportNearBottom = () => undefined;
/** The host rows read outside any provider before an app registers one: locale clock, no slots, no forking. */
/** The host rows read outside any provider before an app registers one: locale clock, no slots,
* no forking, no copying, inert scrolling. */
const fallbackHost: MessagesHost = {
useHour12: () => undefined,
renderFiles: () => null,
useForkPreferences: () => fallbackForkPreferences,
useForkConversation: () => null,
useMessageCopy: () => fallbackMessageCopy,
useScrolling: useInertScrolling,
useScreenshotTarget: () => useRef<HTMLDivElement>(null),
useAutoScroll: () => false,

View file

@ -214,6 +214,7 @@ const messagesHost: MessagesHost = {
setRememberOption: () => undefined,
}),
useForkConversation: () => null,
useMessageCopy: () => ({ copyToClipboard: () => undefined, canCopy: false }),
useScrolling: () => ({
contentRef: { current: null },
scrollableRef: { current: null },