Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🪟 refactor: Move Message Row and Timestamp into @librechat/chat (#17554)

Marco Beretta287a718688d2
diff --git a/client/src/App.jsx b/client/src/App.jsx
index 7b57c13a59..a6a0c9f0db 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -16,6 +16,7 @@ import { initializeFontSize } from '~/store/fontSize';
import { reopenTermsOnRefusal } from '~/utils/terms';
import { LiveAnnouncer } from '~/a11y';
import { router } from './routes';
+import '~/Providers/MessagesHostContext';
const App = () => {
const { setError } = useApiErrorBoundary();
diff --git a/client/src/Providers/MessagesHostContext.tsx b/client/src/Providers/MessagesHostContext.tsx
new file mode 100644
index 0000000000..a98ae8b4a8
--- /dev/null
+++ b/client/src/Providers/MessagesHostContext.tsx
@@ -0,0 +1,14 @@
+import { setDefaultMessagesHost } from '@librechat/chat/react';
+import type { MessagesHost } from '@librechat/chat/react';
+import Files from '~/components/Chat/Messages/Content/Files';
+import useClockFormat from '~/hooks/useClockFormat';
+
+/** What the message list reads from the app: the viewer's clock format 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} />,
+};
+
+setDefaultMessagesHost(appMessagesHost);
diff --git a/client/src/components/Balance/Summary.tsx b/client/src/components/Balance/Summary.tsx
index fc7cca81c6..a986dea84a 100644
--- a/client/src/components/Balance/Summary.tsx
+++ b/client/src/components/Balance/Summary.tsx
@@ -1,10 +1,10 @@
import { memo, useId } from 'react';
import { useTranslation } from 'react-i18next';
+import { useTimeTick } from '@librechat/chat/react';
import { Progress, Skeleton } from '@librechat/client';
import type { BalanceSummary, BalanceTone, CurrencyConfig } from '~/utils';
import type { BalanceState } from '~/hooks/useBalanceSummary';
import { formatBalanceAmount, formatTimeUntil } from '~/utils/balance';
-import useTimeTick from '~/hooks/useTimeTick';
import useLocalize from '~/hooks/useLocalize';
import cn from '~/utils/cn';
diff --git a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx
index cd248f3553..05b9cce852 100644
--- a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx
+++ b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx
@@ -1,6 +1,7 @@
import { memo, useId, useCallback, useEffect, useMemo, useRef, useState, useContext } from 'react';
import { useAtomValue } from 'jotai';
import { useTranslation } from 'react-i18next';
+import { useTimeTick } from '@librechat/chat/react';
import { ContentTypes } from 'librechat-data-provider';
import { Check, CircleX, Lightbulb, ChevronDown, TriangleAlert } from 'lucide-react';
import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';
@@ -41,7 +42,6 @@ import { MessageSurfaceContext } from '../ui/surface';
import useClockFormat from '~/hooks/useClockFormat';
import { cn, getMessageTimestamp } from '~/utils';
import { StackedToolIcons } from './ToolOutput';
-import useTimeTick from '~/hooks/useTimeTick';
import { getSourceDomains } from './sources';
import { mapAttachments } from '~/utils/map';
import { AttachmentGroup } from './Parts';
diff --git a/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx b/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx
index ed9894d257..d054ef0891 100644
--- a/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/PendingSteers.tsx
@@ -4,6 +4,7 @@ import { Clock, TextQuote, X } from 'lucide-react';
import { useQueryClient } from '@tanstack/react-query';
import { Button, TooltipAnchor } from '@librechat/client';
import { QueryKeys, type TMessage } from 'librechat-data-provider';
+import { getMessageRowWidthClass } from '@librechat/chat/components';
import {
useSteerCancel,
useSteerMoveToQueue,
@@ -12,7 +13,6 @@ import {
useSteerRecovery,
} from '@librechat/chat/react';
import type { SteerReceiptState } from '@librechat/chat/components';
-import { getMessageRowWidthClass } from '~/components/Chat/Messages/ui/width';
import EscalateNowButton from '~/components/Chat/Input/EscalateNowButton';
import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext';
import { useGetMessagesByConvoId } from '~/data-provider';
diff --git a/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx b/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx
index e88dc384be..57b6d86925 100644
--- a/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx
@@ -1,9 +1,8 @@
import { memo, useMemo, useState, useEffect, useCallback } from 'react';
-import { SteerReceipt, CollapsibleText } from '@librechat/chat/components';
+import { SteerReceipt, CollapsibleText, MessageTimestamp } from '@librechat/chat/components';
import type { SteerReceiptState } from '@librechat/chat/components';
import type { TFile, TMessage } from 'librechat-data-provider';
import FilePreviewDialog from '~/components/Chat/Messages/Content/FilePreviewDialog';
-import MessageTimestamp from '~/components/Chat/Messages/ui/MessageTimestamp';
import MessageQuotes from '~/components/Chat/Messages/Content/MessageQuotes';
import { cn, hydrateFileDeliveryMetadata, usesImagePreview } from '~/utils';
import MarkdownLite from '~/components/Chat/Messages/Content/MarkdownLite';
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx
index 83dbfcebe7..319901739a 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx
@@ -27,9 +27,9 @@ jest.mock('~/Providers', () => ({
useFileMapContext: () => mockFileMap,
}));
-jest.mock('~/components/Chat/Messages/ui/MessageTimestamp', () => ({
- __esModule: true,
- default: () => <time data-testid="steer-timestamp" />,
+jest.mock('@librechat/chat/components', () => ({
+ ...jest.requireActual('@librechat/chat/components'),
+ MessageTimestamp: () => <time data-testid="steer-timestamp" />,
}));
jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({
diff --git a/client/src/components/Chat/Messages/Content/SiblingHeader.tsx b/client/src/components/Chat/Messages/Content/SiblingHeader.tsx
index 86a5eddb57..8c42193a98 100644
--- a/client/src/components/Chat/Messages/Content/SiblingHeader.tsx
+++ b/client/src/components/Chat/Messages/Content/SiblingHeader.tsx
@@ -1,8 +1,8 @@
import { useMemo } from 'react';
import { GitBranchPlus } from 'lucide-react';
+import { MessageTimestamp } from '@librechat/chat/components';
import { EModelEndpoint, parseEphemeralAgentId, stripAgentIdSuffix } from 'librechat-data-provider';
import type { TMessage, Agent } from 'librechat-data-provider';
-import MessageTimestamp from '~/components/Chat/Messages/ui/MessageTimestamp';
import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext';
import { useBranchMessageMutation } from '~/data-provider/Messages';
import MessageIcon from '~/components/Share/MessageIcon';
diff --git a/client/src/components/Chat/Messages/MessageParts.tsx b/client/src/components/Chat/Messages/MessageParts.tsx
index 66f2ad403a..7dcc96dc98 100644
--- a/client/src/components/Chat/Messages/MessageParts.tsx
+++ b/client/src/components/Chat/Messages/MessageParts.tsx
@@ -9,6 +9,7 @@ import {
shouldShowElapsed,
SiblingSwitch,
SubRow,
+ MessageRow,
} from '@librechat/chat/components';
import type { TMessageContentParts } from 'librechat-data-provider';
import type { TMessageProps, TMessageIcon } from '~/common';
@@ -21,7 +22,6 @@ import {
import { useLocalize, useAttachments, useMessageHelpers, useContentMetadata } from '~/hooks';
import ResumeAuthorHeader from '~/components/Chat/Messages/Content/Parts/ResumeAuthorHeader';
import { ErrorSourceProvider } from '~/components/Messages/Content/Error/source';
-import MessageRow from '~/components/Chat/Messages/ui/MessageRow';
import MessageIcon from '~/components/Chat/Messages/MessageIcon';
import { showThinkingAtom } from '~/store/showThinking';
import ContentParts from './Content/ContentParts';
diff --git a/client/src/components/Chat/Messages/PendingTurn.tsx b/client/src/components/Chat/Messages/PendingTurn.tsx
index 4d4018281c..c96fcf8a96 100644
--- a/client/src/components/Chat/Messages/PendingTurn.tsx
+++ b/client/src/components/Chat/Messages/PendingTurn.tsx
@@ -1,7 +1,12 @@
import { useCallback, useEffect, useMemo, useRef } from 'react';
import { useAtomValue } from 'jotai';
import { useRecoilValue } from 'recoil';
-import { SubRow, messageFooterClasses, useQueuedTurnPortal } from '@librechat/chat/components';
+import {
+ SubRow,
+ messageFooterClasses,
+ useQueuedTurnPortal,
+ MessageRow,
+} from '@librechat/chat/components';
import {
hasRevealSuccessor,
buildRevealedMessage,
@@ -11,7 +16,6 @@ import type { TMessage } from 'librechat-data-provider';
import type { RefObject } from 'react';
import type { TMessageIcon } from '~/common';
import { getHeaderPrefixForScreenReader, getMessageAriaLabel } from '~/utils';
-import MessageRow from '~/components/Chat/Messages/ui/MessageRow';
import MessageIcon from '~/components/Chat/Messages/MessageIcon';
import { useAuthContext } from '~/hooks/AuthContext';
import MarkdownLite from './Content/MarkdownLite';
diff --git a/client/src/components/Chat/Messages/SearchMessage.tsx b/client/src/components/Chat/Messages/SearchMessage.tsx
index 45ac4b5fe5..457f78c4fb 100644
--- a/client/src/components/Chat/Messages/SearchMessage.tsx
+++ b/client/src/components/Chat/Messages/SearchMessage.tsx
@@ -1,14 +1,17 @@
import { memo, useMemo } from 'react';
import { useRecoilValue } from 'recoil';
-import { getHeaderModelName, SubRow } from '@librechat/chat/components';
+import {
+ getHeaderModelName,
+ SubRow,
+ getMessageRowWidthClass,
+ MessageRow,
+} from '@librechat/chat/components';
import type { TMessage } from 'librechat-data-provider';
import type { TMessageProps, TMessageIcon } from '~/common';
import AuthorHeader from '~/components/Chat/Messages/Content/Parts/AuthorHeader';
import MinimalHoverButtons from '~/components/Chat/Messages/MinimalHoverButtons';
-import { getMessageRowWidthClass } from '~/components/Chat/Messages/ui/width';
import { getHeaderPrefixForScreenReader, getMessageAriaLabel } from '~/utils';
import SearchContent, { rendersMarkdownLite } from './Content/SearchContent';
-import MessageRow from '~/components/Chat/Messages/ui/MessageRow';
import Icon from '~/components/Chat/Messages/MessageIcon';
import { useAuthContext, useLocalize } from '~/hooks';
import SearchButtons from './SearchButtons';
diff --git a/client/src/components/Chat/Messages/ui/MessageRender.tsx b/client/src/components/Chat/Messages/ui/MessageRender.tsx
index f6025abbbb..4f6d82719c 100644
--- a/client/src/components/Chat/Messages/ui/MessageRender.tsx
+++ b/client/src/components/Chat/Messages/ui/MessageRender.tsx
@@ -8,6 +8,7 @@ import {
getHeaderHoverLabel,
SiblingSwitch,
SubRow,
+ MessageRow,
} from '@librechat/chat/components';
import type { TMessage } from 'librechat-data-provider';
import type { TMessageProps, TMessageIcon, TMessageChatContext } from '~/common';
@@ -23,7 +24,6 @@ import MessageContent from '~/components/Chat/Messages/Content/MessageContent';
import { useLocalize, useMessageActions, useContentMetadata } from '~/hooks';
import { PrivateText } from '~/components/Chat/Messages/PrivateText';
import HoverButtons from '~/components/Chat/Messages/HoverButtons';
-import MessageRow from '~/components/Chat/Messages/ui/MessageRow';
import MessageIcon from '~/components/Chat/Messages/MessageIcon';
import Wakeup from '~/components/Chat/Messages/Content/Wakeup';
import { MessageContext } from '~/Providers';
diff --git a/client/src/components/Chat/Messages/ui/WakeupRow.tsx b/client/src/components/Chat/Messages/ui/WakeupRow.tsx
index a5f20039e6..9b4c21480c 100644
--- a/client/src/components/Chat/Messages/ui/WakeupRow.tsx
+++ b/client/src/components/Chat/Messages/ui/WakeupRow.tsx
@@ -1,4 +1,5 @@
import { useMemo } from 'react';
+import { MessageRow } from '@librechat/chat/components';
import type { ComponentProps } from 'react';
import type { WakeupTask } from '../Content/Parts/wakeup';
import {
@@ -12,7 +13,6 @@ import { useOptionalMessagesOperations } from '~/Providers/MessagesViewContext';
import { findSubagentDispatch } from '~/components/Chat/Subagents/dispatch';
import { useShareContext } from '~/Providers/ShareContext';
import { useAgentsMapContext } from '~/Providers';
-import MessageRow from './MessageRow';
import { useLocalize } from '~/hooks';
/** Only wake-up rows observe the child index; ordinary rows keep their subscriptions. */
diff --git a/client/src/components/Chat/Messages/ui/__tests__/MessageRender.wakeup.spec.tsx b/client/src/components/Chat/Messages/ui/__tests__/MessageRender.wakeup.spec.tsx
index 7d8c4cb631..80d307e991 100644
--- a/client/src/components/Chat/Messages/ui/__tests__/MessageRender.wakeup.spec.tsx
+++ b/client/src/components/Chat/Messages/ui/__tests__/MessageRender.wakeup.spec.tsx
@@ -69,10 +69,6 @@ jest.mock('@librechat/chat/components', () => ({
<span data-testid="sibling-footer" className={className} />
),
}));
-jest.mock('~/components/Chat/Messages/ui/MessageTimestamp', () => ({
- __esModule: true,
- default: () => null,
-}));
const chatContext = { latestMessageId: 'wake' } as unknown as TMessageChatContext;
diff --git a/client/src/components/Chat/Subagents/EventSubagentActivityGroup.tsx b/client/src/components/Chat/Subagents/EventSubagentActivityGroup.tsx
index 0c1d801998..dc14175785 100644
--- a/client/src/components/Chat/Subagents/EventSubagentActivityGroup.tsx
+++ b/client/src/components/Chat/Subagents/EventSubagentActivityGroup.tsx
@@ -2,9 +2,9 @@ import { useCallback, useId, useMemo, useState } from 'react';
import { useSetAtom } from 'jotai';
import { Button, cn } from '@librechat/client';
import { Bot, ChevronDown } from 'lucide-react';
+import { getMessageRowWidthClass } from '@librechat/chat/components';
import type { ParentSubagentSummary } from 'librechat-data-provider';
import { isLiveSubagentStatus, subagentStatusDotClass, subagentStatusLabelKey } from './status';
-import { getMessageRowWidthClass } from '~/components/Chat/Messages/ui/width';
import { useChatSurface, useOpenSubagentPanel } from './surface';
import { useParentSubagents } from './ParentSubagentsProvider';
import { eventSubagentSelection } from './eventSelection';
diff --git a/client/src/components/Chat/Subagents/SubagentActivity.test.tsx b/client/src/components/Chat/Subagents/SubagentActivity.test.tsx
index 5cd769821a..15776510b3 100644
--- a/client/src/components/Chat/Subagents/SubagentActivity.test.tsx
+++ b/client/src/components/Chat/Subagents/SubagentActivity.test.tsx
@@ -232,6 +232,8 @@ jest.mock('@librechat/chat/components', () => ({
}));
jest.mock('@librechat/client', () => ({
+ cn: jest.requireActual('@librechat/client').cn,
+ useLanguage: () => 'en',
Alert: ({ children }: { children: React.ReactNode }) => <div role="alert">{children}</div>,
Button: ({ children, ...props }: React.ComponentProps<'button'>) => (
<button {...props}>{children}</button>
diff --git a/client/src/components/Chat/Subagents/SubagentActivity.tsx b/client/src/components/Chat/Subagents/SubagentActivity.tsx
index 4b893b3849..7d5011dd20 100644
--- a/client/src/components/Chat/Subagents/SubagentActivity.tsx
+++ b/client/src/components/Chat/Subagents/SubagentActivity.tsx
@@ -3,6 +3,7 @@ import { useQuery } from '@tanstack/react-query';
import { Alert, Button } from '@librechat/client';
import { Maximize2, Minimize2 } from 'lucide-react';
import { CSSTransition } from 'react-transition-group';
+import { MessageTimestamp } from '@librechat/chat/components';
import { ContentTypes, QueryKeys, dataService } from 'librechat-data-provider';
import type { SearchResultData, TMessageContentParts } from 'librechat-data-provider';
import type { SteerReceiptState } from '@librechat/chat/components';
@@ -17,7 +18,6 @@ import {
subagentStatusLabelKey,
} from './status';
import { ToolContentQueryContext } from '~/components/Chat/Messages/Content/disclosure';
-import MessageTimestamp from '~/components/Chat/Messages/ui/MessageTimestamp';
import { TaskContentScopeContext } from '~/data-provider/Subagents/content';
import MarkdownLite from '~/components/Chat/Messages/Content/MarkdownLite';
import ContentParts from '~/components/Chat/Messages/Content/ContentParts';
diff --git a/client/src/components/Chat/Subagents/SubagentConversation.tsx b/client/src/components/Chat/Subagents/SubagentConversation.tsx
index 53b1076097..5e464f4e8c 100644
--- a/client/src/components/Chat/Subagents/SubagentConversation.tsx
+++ b/client/src/components/Chat/Subagents/SubagentConversation.tsx
@@ -14,6 +14,7 @@ import {
systemEventHeaderClasses,
messageFooterClasses,
ElapsedTimer,
+ MessageRow,
} from '@librechat/chat/components';
import type { TMessage, TMessageContentParts } from 'librechat-data-provider';
import type { ReactNode } from 'react';
@@ -36,7 +37,6 @@ import { ErrorSourceProvider } from '~/components/Messages/Content/Error/source'
import MinimalHoverButtons from '~/components/Chat/Messages/MinimalHoverButtons';
import ContentParts from '~/components/Chat/Messages/Content/ContentParts';
import { isAbnormalTerminalStatus, isLiveSubagentStatus } from './status';
-import MessageRow from '~/components/Chat/Messages/ui/MessageRow';
import { AuthorContext } from '~/Providers/AuthorContext';
import { ChatContext } from '~/Providers/ChatContext';
import { isEmptyContentPart } from '~/utils/messages';
diff --git a/client/src/components/Messages/ContentRender.tsx b/client/src/components/Messages/ContentRender.tsx
index a0f48e4941..6f74cdc2a4 100644
--- a/client/src/components/Messages/ContentRender.tsx
+++ b/client/src/components/Messages/ContentRender.tsx
@@ -10,6 +10,7 @@ import {
getHeaderHoverLabel,
SiblingSwitch,
SubRow,
+ MessageRow,
} from '@librechat/chat/components';
import type { TMessage, TMessageContentParts } from 'librechat-data-provider';
import type { TMessageProps, TMessageIcon, TMessageChatContext } from '~/common';
@@ -27,7 +28,6 @@ import { ErrorSourceProvider } from '~/components/Messages/Content/Error/source'
import ContentParts from '~/components/Chat/Messages/Content/ContentParts';
import { PrivateText } from '~/components/Chat/Messages/PrivateText';
import HoverButtons from '~/components/Chat/Messages/HoverButtons';
-import MessageRow from '~/components/Chat/Messages/ui/MessageRow';
import MessageIcon from '~/components/Chat/Messages/MessageIcon';
import { showThinkingAtom } from '~/store/showThinking';
import { AuthorContext } from '~/Providers';
diff --git a/client/src/components/Messages/__tests__/ContentRender.tail.spec.tsx b/client/src/components/Messages/__tests__/ContentRender.tail.spec.tsx
index 7ddd387fbd..87de2c7a48 100644
--- a/client/src/components/Messages/__tests__/ContentRender.tail.spec.tsx
+++ b/client/src/components/Messages/__tests__/ContentRender.tail.spec.tsx
@@ -7,27 +7,6 @@ import MessageContent from '../MessageContent';
const mockRowRenders = new Map<string, number>();
-jest.mock('~/components/Chat/Messages/ui/MessageRow', () => ({
- __esModule: true,
- default: ({
- id,
- children,
- footer,
- }: {
- id?: string;
- children: React.ReactNode;
- footer: React.ReactNode;
- }) => {
- mockRowRenders.set(id ?? '', (mockRowRenders.get(id ?? '') ?? 0) + 1);
- return (
- <div data-testid={`row-${id}`}>
- {children}
- {footer}
- </div>
- );
- },
-}));
-
jest.mock('~/components/Chat/Messages/Content/ContentParts', () => ({
__esModule: true,
default: () => null,
@@ -45,6 +24,23 @@ jest.mock('~/components/Chat/Messages/MessageIcon', () => ({
jest.mock('@librechat/chat/components', () => ({
...jest.requireActual('@librechat/chat/components'),
+ MessageRow: ({
+ id,
+ children,
+ footer,
+ }: {
+ id?: string;
+ children: React.ReactNode;
+ footer: React.ReactNode;
+ }) => {
+ mockRowRenders.set(id ?? '', (mockRowRenders.get(id ?? '') ?? 0) + 1);
+ return (
+ <div data-testid={`row-${id}`}>
+ {children}
+ {footer}
+ </div>
+ );
+ },
Elapsed: () => null,
shouldShowElapsed: () => false,
}));
diff --git a/client/src/components/Messages/__tests__/ContentRender.test.tsx b/client/src/components/Messages/__tests__/ContentRender.test.tsx
index 2af2d9351b..820eb9a85b 100644
--- a/client/src/components/Messages/__tests__/ContentRender.test.tsx
+++ b/client/src/components/Messages/__tests__/ContentRender.test.tsx
@@ -34,11 +34,6 @@ jest.mock('~/components/Chat/Messages/HoverButtons', () => ({
default: () => null,
}));
-jest.mock('~/components/Chat/Messages/ui/MessageTimestamp', () => ({
- __esModule: true,
- default: () => null,
-}));
-
/**
* Stands in for the agents map: `useMessageActions` reads it through context, so the
* agents list landing re-renders the memoized row without any new props.
diff --git a/client/src/components/Messages/__tests__/ProtectedAttachments.spec.tsx b/client/src/components/Messages/__tests__/ProtectedAttachments.spec.tsx
index b6c6d43f17..117738cc66 100644
--- a/client/src/components/Messages/__tests__/ProtectedAttachments.spec.tsx
+++ b/client/src/components/Messages/__tests__/ProtectedAttachments.spec.tsx
@@ -7,6 +7,7 @@ import type { TMessageChatContext } from '~/common';
import { OwnerTextProvider } from '~/components/Chat/Messages/PrivateText';
import MessageRender from '~/components/Chat/Messages/ui/MessageRender';
import ContentRender from '../ContentRender';
+import '~/Providers/MessagesHostContext';
jest.mock('librechat-data-provider', () => ({
...jest.requireActual('librechat-data-provider'),
diff --git a/client/src/components/Share/Message.tsx b/client/src/components/Share/Message.tsx
index 7fcd53997d..727ac10459 100644
--- a/client/src/components/Share/Message.tsx
+++ b/client/src/components/Share/Message.tsx
@@ -1,5 +1,5 @@
import { useMemo } from 'react';
-import { getHeaderHoverLabel, SiblingSwitch, SubRow } from '@librechat/chat/components';
+import { getHeaderHoverLabel, SiblingSwitch, SubRow, MessageRow } from '@librechat/chat/components';
import type { TMessageProps } from '~/common';
import SearchContent, {
rendersMarkdownLite,
@@ -9,7 +9,6 @@ import AuthorHeader from '~/components/Chat/Messages/Content/Parts/AuthorHeader'
import MinimalHoverButtons from '~/components/Chat/Messages/MinimalHoverButtons';
import MessageContent from '~/components/Chat/Messages/Content/MessageContent';
import { getHeaderPrefixForScreenReader, getMessageAriaLabel } from '~/utils';
-import MessageRow from '~/components/Chat/Messages/ui/MessageRow';
import WakeupRow from '~/components/Chat/Messages/ui/WakeupRow';
import Wakeup from '~/components/Chat/Messages/Content/Wakeup';
import { MessageContext, useShareContext } from '~/Providers';
diff --git a/client/src/routes/Search.tsx b/client/src/routes/Search.tsx
index 9fd191e8c2..ddfae05cb8 100644
--- a/client/src/routes/Search.tsx
+++ b/client/src/routes/Search.tsx
@@ -3,11 +3,11 @@ import { useAtomValue } from 'jotai';
import throttle from 'lodash/throttle';
import { useRecoilValue } from 'recoil';
import { Search as SearchIcon, SearchX } from 'lucide-react';
+import { getMessageRowWidthClass } from '@librechat/chat/components';
import { List, CellMeasurer, CellMeasurerCache } from 'react-virtualized';
import { EmptyState, Spinner, useRemScale, useToastContext } from '@librechat/client';
import type { Index, ListRowProps } from 'react-virtualized';
import type { TMessage } from 'librechat-data-provider';
-import { getMessageRowWidthClass } from '~/components/Chat/Messages/ui/width';
import { useElementSize, useLocalize, useAuthContext } from '~/hooks';
import SearchMessage from '~/components/Chat/Messages/SearchMessage';
import { useMessagesInfiniteQuery } from '~/data-provider';
diff --git a/client/src/utils/__tests__/messages.test.ts b/client/src/utils/__tests__/messages.test.ts
index 5537ad0ad6..a41925b782 100644
--- a/client/src/utils/__tests__/messages.test.ts
+++ b/client/src/utils/__tests__/messages.test.ts
@@ -7,9 +7,7 @@ import {
clearMessagesCache,
clearArchivedConversationMessagesCache,
clearDeletedConversationMessagesCache,
- isValidTimestamp,
getMessageAriaLabel,
- getMessageTimestamp,
getHeaderPrefixForScreenReader,
areMessageFieldsEqual,
areMessageRowPropsEqual,
@@ -223,122 +221,6 @@ describe('getHeaderPrefixForScreenReader', () => {
});
});
-describe('isValidTimestamp', () => {
- it('returns false for missing values', () => {
- expect(isValidTimestamp(undefined)).toBe(false);
- expect(isValidTimestamp(null)).toBe(false);
- expect(isValidTimestamp('')).toBe(false);
- });
-
- it('returns false for unparseable strings', () => {
- expect(isValidTimestamp('not-a-date')).toBe(false);
- });
-
- it('returns true for ISO date strings', () => {
- expect(isValidTimestamp('2026-06-12T15:42:00.000Z')).toBe(true);
- });
-});
-
-describe('getMessageTimestamp', () => {
- const NOW = new Date('2026-06-12T15:42:00.000Z').getTime();
-
- beforeEach(() => {
- jest.useFakeTimers().setSystemTime(NOW);
- });
-
- afterEach(() => {
- jest.useRealTimers();
- });
-
- it('returns null for missing or invalid values', () => {
- expect(getMessageTimestamp(undefined, 'en-US')).toBeNull();
- expect(getMessageTimestamp(null, 'en-US')).toBeNull();
- expect(getMessageTimestamp('not-a-date', 'en-US')).toBeNull();
- });
-
- it('formats relative and absolute time for a recent message', () => {
- const twoHoursAgo = new Date(NOW - 2 * 60 * 60 * 1000).toISOString();
- const result = getMessageTimestamp(twoHoursAgo, 'en-US');
- expect(result).not.toBeNull();
- expect(result?.relative).toBe('2 hours ago');
- expect(result?.iso).toBe(twoHoursAgo);
- expect(result?.absolute).toContain('2026');
- });
-
- it('flags messages under 24h as recent (prefer relative)', () => {
- const justUnderADay = new Date(NOW - 23 * 60 * 60 * 1000).toISOString();
- expect(getMessageTimestamp(justUnderADay, 'en-US')?.isRecent).toBe(true);
- });
-
- it('flags older messages as not recent (prefer absolute date)', () => {
- const overADay = new Date(NOW - 25 * 60 * 60 * 1000).toISOString();
- const monthAgo = new Date(NOW - 38 * 24 * 60 * 60 * 1000).toISOString();
- expect(getMessageTimestamp(overADay, 'en-US')?.isRecent).toBe(false);
- expect(getMessageTimestamp(monthAgo, 'en-US')?.isRecent).toBe(false);
- });
-
- it('uses "now" for the current instant', () => {
- const result = getMessageTimestamp(new Date(NOW).toISOString(), 'en-US');
- expect(result?.relative).toBe('now');
- expect(result?.isRecent).toBe(true);
- });
-
- it('falls back to the default locale for a malformed locale tag', () => {
- const iso = new Date(NOW - 60 * 1000).toISOString();
- expect(() => getMessageTimestamp(iso, 'not a locale!!')).not.toThrow();
- expect(getMessageTimestamp(iso, 'not a locale!!')).not.toBeNull();
- });
-
- /** Every message row formats its timestamp on each render; constructing the
- * Intl formatters per call made them the costliest function of a send. */
- it('reuses its formatters across calls for the same locale and clock', () => {
- const { DateTimeFormat, RelativeTimeFormat } = Intl;
- const replaceIntl = (key: 'DateTimeFormat' | 'RelativeTimeFormat', value: unknown) =>
- Object.defineProperty(Intl, key, { value, configurable: true, writable: true });
- const constructed = { absolute: 0, relative: 0 };
- replaceIntl(
- 'DateTimeFormat',
- class extends DateTimeFormat {
- constructor(...args: ConstructorParameters<typeof DateTimeFormat>) {
- super(...args);
- constructed.absolute += 1;
- }
- },
- );
- replaceIntl(
- 'RelativeTimeFormat',
- class extends RelativeTimeFormat {
- constructor(...args: ConstructorParameters<typeof RelativeTimeFormat>) {
- super(...args);
- constructed.relative += 1;
- }
- },
- );
- try {
- const iso = new Date(NOW - 5 * 60 * 1000).toISOString();
- const first = getMessageTimestamp(iso, 'fr-CA', true);
- const second = getMessageTimestamp(iso, 'fr-CA', true);
- getMessageTimestamp(iso, 'fr-CA', true);
-
- expect(second).toEqual(first);
- expect(constructed).toEqual({ absolute: 1, relative: 1 });
-
- getMessageTimestamp(iso, 'fr-CA', false);
- expect(constructed).toEqual({ absolute: 2, relative: 1 });
- } finally {
- replaceIntl('DateTimeFormat', DateTimeFormat);
- replaceIntl('RelativeTimeFormat', RelativeTimeFormat);
- }
- });
-
- it('keeps a formatter per clock format', () => {
- const iso = new Date(2026, 5, 12, 15, 5).toISOString();
-
- expect(getMessageTimestamp(iso, 'en-US', true)?.absolute).toMatch(/3:05\sPM/);
- expect(getMessageTimestamp(iso, 'en-US', false)?.absolute).toMatch(/15:05/);
- });
-});
-
const noop = () => {};
/** Shared content reference so the baseline compares equal on `content` (which
* the comparator diffs BY REFERENCE); the mutation below hands a fresh array. */
diff --git a/client/src/utils/messages.ts b/client/src/utils/messages.ts
index 96d498fc59..939ee971fe 100644
--- a/client/src/utils/messages.ts
+++ b/client/src/utils/messages.ts
@@ -474,129 +474,8 @@ export const getHeaderPrefixForScreenReader = (
: `${localize('com_ui_response')}${suffix}: `;
};
-export type MessageTimestamp = {
- /** Localized relative time, e.g. "2 hours ago". */
- relative: string;
- /** Localized absolute date and time, e.g. "Jun 12, 2026, 3:42 PM". */
- absolute: string;
- /** ISO 8601 string for the `<time>` element's `dateTime` attribute. */
- iso: string;
- /**
- * True when the message is recent enough that the relative form ("10 minutes ago")
- * reads better than the absolute date. Past this window the absolute date is clearer.
- */
- isRecent: boolean;
-};
-
-/** Below this age the relative form is preferred over the absolute date. */
-const RECENT_THRESHOLD_MS = 24 * 60 * 60 * 1000;
-
-/** Returns true when `value` parses to a valid date. */
-export const isValidTimestamp = (value?: string | null): value is string => {
- if (!value) {
- return false;
- }
- return !Number.isNaN(new Date(value).getTime());
-};
-
-const RELATIVE_TIME_DIVISIONS: { amount: number; unit: Intl.RelativeTimeFormatUnit }[] = [
- { amount: 60, unit: 'second' },
- { amount: 60, unit: 'minute' },
- { amount: 24, unit: 'hour' },
- { amount: 7, unit: 'day' },
- { amount: 4.34524, unit: 'week' },
- { amount: 12, unit: 'month' },
- { amount: Number.POSITIVE_INFINITY, unit: 'year' },
-];
-
-/**
- * Intl formatters are expensive to construct and every message row formats its
- * timestamp on each render, so they are built once per locale (and clock format).
- */
-const resolvedLocales = new Map<string, string | undefined>();
-const relativeFormatters = new Map<string, Intl.RelativeTimeFormat>();
-const absoluteFormatters = new Map<string, Intl.DateTimeFormat>();
-
-/** Returns the locale only when it is a syntactically valid BCP-47 tag, else undefined. */
-const resolveLocale = (locale?: string): string | undefined => {
- if (!locale) {
- return undefined;
- }
- if (resolvedLocales.has(locale)) {
- return resolvedLocales.get(locale);
- }
- let resolved: string | undefined;
- try {
- Intl.DateTimeFormat.supportedLocalesOf(locale);
- resolved = locale;
- } catch {
- resolved = undefined;
- }
- resolvedLocales.set(locale, resolved);
- return resolved;
-};
-
-const getRelativeFormatter = (locale?: string): Intl.RelativeTimeFormat => {
- const key = locale ?? '';
- let formatter = relativeFormatters.get(key);
- if (!formatter) {
- formatter = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
- relativeFormatters.set(key, formatter);
- }
- return formatter;
-};
-
-const getAbsoluteFormatter = (locale?: string, hour12?: boolean): Intl.DateTimeFormat => {
- const key = `${locale ?? ''}|${String(hour12)}`;
- let formatter = absoluteFormatters.get(key);
- if (!formatter) {
- formatter = new Intl.DateTimeFormat(locale, {
- dateStyle: 'medium',
- timeStyle: 'short',
- hour12,
- });
- absoluteFormatters.set(key, formatter);
- }
- return formatter;
-};
-
-const formatRelativeTime = (from: Date, to: Date, locale?: string): string => {
- const formatter = getRelativeFormatter(locale);
- let duration = (from.getTime() - to.getTime()) / 1000;
- for (const division of RELATIVE_TIME_DIVISIONS) {
- if (Math.abs(duration) < division.amount) {
- return formatter.format(Math.round(duration), division.unit);
- }
- duration /= division.amount;
- }
- return formatter.format(Math.round(duration), 'year');
-};
-
-/**
- * Formats a message timestamp into locale-aware relative and absolute strings.
- * Returns null when the value is missing or unparseable, so callers can skip
- * rendering the timestamp entirely.
- */
-export const getMessageTimestamp = (
- value?: string | null,
- locale?: string,
- hour12?: boolean,
-): MessageTimestamp | null => {
- if (!isValidTimestamp(value)) {
- return null;
- }
-
- const date = new Date(value);
- const now = new Date(Date.now());
- const safeLocale = resolveLocale(locale);
-
- return {
- iso: date.toISOString(),
- relative: formatRelativeTime(date, now, safeLocale),
- absolute: getAbsoluteFormatter(safeLocale, hour12).format(date),
- isRecent: Math.abs(now.getTime() - date.getTime()) < RECENT_THRESHOLD_MS,
- };
-};
+export { isValidTimestamp, getMessageTimestamp } from '@librechat/chat/components';
+export type { MessageTimestamp } from '@librechat/chat/components';
export function areMessageFilesEqual(prevFiles?: TMessage['files'], nextFiles?: TMessage['files']) {
if (prevFiles === nextFiles) {
diff --git a/e2e/specs/mock/scenarios/message-row.spec.ts b/e2e/specs/mock/scenarios/message-row.spec.ts
new file mode 100644
index 0000000000..a21c9017d8
--- /dev/null
+++ b/e2e/specs/mock/scenarios/message-row.spec.ts
@@ -0,0 +1,103 @@
+import { randomUUID } from 'crypto';
+import { expect, test } from '@playwright/test';
+import type { Page } from '@playwright/test';
+import {
+ withMongo,
+ seedMessages,
+ seedConversations,
+ deleteConversations,
+ deleteMessagesByConversation,
+} from '../db';
+import { getAccessToken, requestJson } from '../helpers';
+import { getE2EUser } from '../../../setup/user';
+
+/** Rows built from the package's MessageRow and MessageTimestamp, with the attachments the app
+ * host renders into them, on the chat route and on a public shared link. */
+
+const NO_PARENT = '00000000-0000-0000-0000-000000000000';
+const TEXT = 'Rows keep their header, timestamp and attachments.';
+
+async function seedThread(email: string, createdAt: Date) {
+ const conversationId = randomUUID();
+ const userId = randomUUID();
+ const replyId = randomUUID();
+ await seedConversations(email, [
+ { conversationId, title: 'Message row fixture', updatedAt: new Date() },
+ ]);
+ await seedMessages(email, conversationId, [
+ {
+ messageId: userId,
+ parentMessageId: NO_PARENT,
+ text: TEXT,
+ isCreatedByUser: true,
+ sender: 'User',
+ files: [{ file_id: randomUUID(), filename: 'row-notes.txt', type: 'text/plain', bytes: 64 }],
+ },
+ {
+ messageId: replyId,
+ parentMessageId: userId,
+ text: `Reply to ${TEXT}`,
+ isCreatedByUser: false,
+ sender: 'Assistant',
+ },
+ ]);
+ await withMongo((db) =>
+ db.collection('messages').updateMany({ conversationId }, { $set: { createdAt } }),
+ );
+ return { conversationId, userId, replyId };
+}
+
+const row = (page: Page, id: string) => page.locator(`[id="${id}"]`);
+
+test.describe('message row', () => {
+ test('a recent message is stamped with its relative time and exact date @scenario:message-row-shows-relative-timestamp', async ({
+ page,
+ }) => {
+ const { email } = getE2EUser();
+ const twoHoursAgo = new Date(Date.now() - 2 * 60 * 60 * 1000);
+ const { conversationId, replyId } = await seedThread(email, twoHoursAgo);
+ try {
+ await page.goto(`/c/${conversationId}`);
+ const reply = row(page, replyId);
+ await expect(reply).toContainText(`Reply to ${TEXT}`);
+ const time = reply.locator('time').first();
+ await expect(time).toHaveAttribute('datetime', twoHoursAgo.toISOString());
+ await expect(time).toHaveText('2 hours ago');
+ await expect(time).toHaveAttribute('title', /\d/);
+ } finally {
+ await deleteMessagesByConversation([conversationId]);
+ await deleteConversations([conversationId]);
+ }
+ });
+
+ test('a shared link shows the attachments of a user message @scenario:shared-row-shows-user-attachments', async ({
+ page,
+ }) => {
+ const { email } = getE2EUser();
+ const { conversationId, userId } = await seedThread(email, new Date());
+ try {
+ await page.goto(`/c/${conversationId}`);
+ await expect(
+ row(page, userId).getByTestId('message-attachments').getByRole('button'),
+ ).toHaveCount(1);
+
+ const token = await getAccessToken(page);
+ const share = await requestJson<{ shareId?: string }>(page, {
+ path: `/api/share/${conversationId}`,
+ token,
+ method: 'POST',
+ body: {},
+ });
+ if (!share.shareId) {
+ throw new Error('Expected the share response to include a shareId');
+ }
+ await page.goto(`/share/${share.shareId}`);
+ const shared = page.locator('.message-render').filter({ hasText: TEXT }).first();
+ await expect(shared).toBeVisible({ timeout: 15000 });
+ await expect(shared.getByTestId('message-attachments')).toBeVisible();
+ } finally {
+ await deleteMessagesByConversation([conversationId]);
+ await deleteConversations([conversationId]);
+ }
+ });
+});
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index 229194fe08..1531db7d48 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -498,11 +498,6 @@
"count": 1
}
},
- "client/src/components/Chat/Messages/ui/MessageRow.tsx": {
- "shadcn/no-arbitrary-values": {
- "count": 1
- }
- },
"client/src/components/Chat/ProjectLandingChip.tsx": {
"shadcn/no-restyle": {
"count": 14
@@ -1424,6 +1419,11 @@
"count": 5
}
},
+ "packages/chat/src/components/messages/MessageRow.tsx": {
+ "shadcn/no-arbitrary-values": {
+ "count": 1
+ }
+ },
"packages/chat/src/components/messages/SiblingSwitch.tsx": {
"shadcn/no-restyle": {
"count": 2
diff --git a/eslint.config.mjs b/eslint.config.mjs
index c1590c9d88..60e9768e07 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -358,6 +358,8 @@ export default [
'result-thinking',
'shimmer',
'tool-status-text',
+ 'message-render',
+ 'message-timestamp',
],
},
],
diff --git a/packages/chat/src/__fixtures__/i18n.ts b/packages/chat/src/__fixtures__/i18n.ts
new file mode 100644
index 0000000000..ce0fb8772c
--- /dev/null
+++ b/packages/chat/src/__fixtures__/i18n.ts
@@ -0,0 +1,16 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import i18next from 'i18next';
+import { initReactI18next } from 'react-i18next';
+
+const TRANSLATION = path.resolve(__dirname, '../../../../client/src/locales/en/translation.json');
+
+/** Loads the app's English bundle into the shared i18next instance, so a spec reads the copy and
+ * plural forms users see. Call it from a `beforeAll`. */
+export async function initEnglish(): Promise<void> {
+ await i18next.use(initReactI18next).init({
+ lng: 'en',
+ resources: { en: { translation: JSON.parse(fs.readFileSync(TRANSLATION, 'utf8')) } },
+ interpolation: { escapeValue: false },
+ });
+}
diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts
index 14aa0b59e8..63a58ea0b6 100644
--- a/packages/chat/src/components.ts
+++ b/packages/chat/src/components.ts
@@ -53,3 +53,8 @@ export {
} from './components/messages/styles';
export { getRunStepDurationLabels, getElapsedDurationLabels } from './components/messages/duration';
export type { RunStepDurationLabels } from './components/messages/duration';
+export { default as MessageRow } from './components/messages/MessageRow';
+export { default as MessageTimestamp } from './components/messages/MessageTimestamp';
+export { getMessageRowWidthClass } from './components/messages/width';
+export { isValidTimestamp, getMessageTimestamp } from './components/messages/time';
+export type { MessageTimestamp as MessageTimestampParts } from './components/messages/time';
diff --git a/client/src/components/Chat/Messages/ui/MessageRow.tsx b/packages/chat/src/components/messages/MessageRow.tsx
similarity index 95%
rename from client/src/components/Chat/Messages/ui/MessageRow.tsx
rename to packages/chat/src/components/messages/MessageRow.tsx
index 17d3e2741b..ede6dd72b8 100644
--- a/client/src/components/Chat/Messages/ui/MessageRow.tsx
+++ b/packages/chat/src/components/messages/MessageRow.tsx
@@ -1,12 +1,12 @@
import { Zap } from 'lucide-react';
+import { cn } from '@librechat/client';
import { ContentTypes } from 'librechat-data-provider';
-import { HeaderLabel } from '@librechat/chat/components';
import type { TMessage } from 'librechat-data-provider';
-import type { ReactNode } from 'react';
+import type { ReactNode, ReactElement } from 'react';
+import { useMessagesHost } from '../../react/messages/host';
import MessageTimestamp from './MessageTimestamp';
import { getMessageRowWidthClass } from './width';
-import Files from '../Content/Files';
-import { cn } from '~/utils';
+import HeaderLabel from './HeaderLabel';
type MessageRowProps = {
id?: string;
@@ -98,7 +98,8 @@ export default function MessageRow({
systemLabel,
showAuthor = false,
outlined = false,
-}: MessageRowProps) {
+}: MessageRowProps): ReactElement {
+ const { renderFiles } = useMessagesHost();
// Same column as ChatForm: max-width plus `sm:px-2`, so the body lines
// up with the composer surface rather than the form's outer box.
const widthClass = getMessageRowWidthClass({ fullWidth, hasParallelContent });
@@ -178,12 +179,12 @@ export default function MessageRow({
})}
<div className={cn('flex w-full flex-col gap-1', isUserSide && 'items-end')}>
- {hasFiles && (
+ {hasFiles && message != null && (
<div
data-testid="message-attachments"
className="flex max-w-full flex-col items-end gap-3 pb-2"
>
- <Files message={message} />
+ {renderFiles(message)}
</div>
)}
{hasBody && (
diff --git a/client/src/components/Chat/Messages/ui/MessageTimestamp.tsx b/packages/chat/src/components/messages/MessageTimestamp.tsx
similarity index 81%
rename from client/src/components/Chat/Messages/ui/MessageTimestamp.tsx
rename to packages/chat/src/components/messages/MessageTimestamp.tsx
index 69e128a11b..ef33b3302c 100644
--- a/client/src/components/Chat/Messages/ui/MessageTimestamp.tsx
+++ b/packages/chat/src/components/messages/MessageTimestamp.tsx
@@ -1,7 +1,8 @@
-import { useTranslation } from 'react-i18next';
-import useClockFormat from '~/hooks/useClockFormat';
-import { cn, getMessageTimestamp } from '~/utils';
-import useTimeTick from '~/hooks/useTimeTick';
+import { cn, useLanguage } from '@librechat/client';
+import type { ReactElement } from 'react';
+import { useMessagesHost } from '../../react/messages/host';
+import { getMessageTimestamp } from './time';
+import useTimeTick from '../../react/tick';
type Timestamp = NonNullable<ReturnType<typeof getMessageTimestamp>>;
@@ -41,7 +42,7 @@ function RecentTimestamp({
}: {
value?: string | null;
language: string;
- hour12: boolean;
+ hour12: boolean | undefined;
className?: string;
revealOnHover?: boolean;
}) {
@@ -72,10 +73,10 @@ export default function MessageTimestamp({
value?: string | null;
className?: string;
revealOnHover?: boolean;
-}) {
- const { i18n } = useTranslation();
- const hour12 = useClockFormat();
- const timestamp = getMessageTimestamp(value, i18n.language, hour12);
+}): ReactElement | null {
+ const language = useLanguage();
+ const hour12 = useMessagesHost().useHour12();
+ const timestamp = getMessageTimestamp(value, language, hour12);
if (!timestamp) {
return null;
@@ -85,7 +86,7 @@ export default function MessageTimestamp({
return (
<RecentTimestamp
value={value}
- language={i18n.language}
+ language={language}
hour12={hour12}
className={className}
revealOnHover={revealOnHover}
diff --git a/packages/chat/src/components/messages/__tests__/Elapsed.spec.tsx b/packages/chat/src/components/messages/__tests__/Elapsed.spec.tsx
index ac0f82367e..45acf948d7 100644
--- a/packages/chat/src/components/messages/__tests__/Elapsed.spec.tsx
+++ b/packages/chat/src/components/messages/__tests__/Elapsed.spec.tsx
@@ -1,28 +1,13 @@
/**
* @jest-environment jsdom
*/
-import fs from 'node:fs';
-import path from 'node:path';
-import i18next from 'i18next';
import { Provider, createStore } from 'jotai';
-import { initReactI18next } from 'react-i18next';
import { render, screen, act } from '@testing-library/react';
import { submissionStartFamily } from '../../../react/generation';
+import { initEnglish } from '../../../__fixtures__/i18n';
import Elapsed, { shouldShowElapsed } from '../Elapsed';
-/** The app's English bundle, so the readings and their plural forms are the ones users see. */
-const TRANSLATION = path.resolve(
- __dirname,
- '../../../../../../client/src/locales/en/translation.json',
-);
-
-beforeAll(async () => {
- await i18next.use(initReactI18next).init({
- lng: 'en',
- resources: { en: { translation: JSON.parse(fs.readFileSync(TRANSLATION, 'utf8')) } },
- interpolation: { escapeValue: false },
- });
-});
+beforeAll(initEnglish);
function storeWithStart(start?: number) {
const jotaiStore = createStore();
diff --git a/client/src/components/Chat/Messages/ui/__tests__/MessageRow.spec.tsx b/packages/chat/src/components/messages/__tests__/MessageRow.spec.tsx
similarity index 90%
rename from client/src/components/Chat/Messages/ui/__tests__/MessageRow.spec.tsx
rename to packages/chat/src/components/messages/__tests__/MessageRow.spec.tsx
index 88b57a6de7..044fcb60a2 100644
--- a/client/src/components/Chat/Messages/ui/__tests__/MessageRow.spec.tsx
+++ b/packages/chat/src/components/messages/__tests__/MessageRow.spec.tsx
@@ -1,5 +1,11 @@
+/**
+ * @jest-environment jsdom
+ */
import { render, screen } from '@testing-library/react';
import type { TMessage } from 'librechat-data-provider';
+import type { MessagesHost } from '../../../react/messages/host';
+import { MessagesHostProvider } from '../../../react/messages/host';
+import { initEnglish } from '../../../__fixtures__/i18n';
import MessageRow from '../MessageRow';
jest.mock('../MessageTimestamp', () => ({
@@ -9,10 +15,12 @@ jest.mock('../MessageTimestamp', () => ({
),
}));
-jest.mock('../../Content/Files', () => ({
- __esModule: true,
- default: () => <button data-testid="attached-file" />,
-}));
+beforeAll(initEnglish);
+
+const host: MessagesHost = {
+ useHour12: () => undefined,
+ renderFiles: () => <button data-testid="attached-file" />,
+};
const MESSAGE_BODY = 'Message body';
const attachedMessage = (overrides: Partial<TMessage> = {}) =>
@@ -44,25 +52,27 @@ const renderRow = ({
outlined?: boolean;
}) =>
render(
- <MessageRow
- id="message-1"
- message={message}
- label={isCreatedByUser ? 'You' : 'Assistant'}
- hoverLabel={isCreatedByUser ? undefined : 'gpt-5.6'}
- icon={<span data-testid="message-icon" />}
- footer={<div data-testid="message-actions" />}
- ariaLabel={isCreatedByUser ? 'User message' : 'Assistant message'}
- headerPrefix="Message from "
- isCreatedByUser={isCreatedByUser}
- hasParallelContent={hasParallelContent}
- fullWidth={fullWidth}
- isEditing={isEditing}
- systemLabel={systemLabel}
- showAuthor={showAuthor}
- outlined={outlined}
- >
- <p>{MESSAGE_BODY}</p>
- </MessageRow>,
+ <MessagesHostProvider host={host}>
+ <MessageRow
+ id="message-1"
+ message={message}
+ label={isCreatedByUser ? 'You' : 'Assistant'}
+ hoverLabel={isCreatedByUser ? undefined : 'gpt-5.6'}
+ icon={<span data-testid="message-icon" />}
+ footer={<div data-testid="message-actions" />}
+ ariaLabel={isCreatedByUser ? 'User message' : 'Assistant message'}
+ headerPrefix="Message from "
+ isCreatedByUser={isCreatedByUser}
+ hasParallelContent={hasParallelContent}
+ fullWidth={fullWidth}
+ isEditing={isEditing}
+ systemLabel={systemLabel}
+ showAuthor={showAuthor}
+ outlined={outlined}
+ >
+ <p>{MESSAGE_BODY}</p>
+ </MessageRow>
+ </MessagesHostProvider>,
);
describe('MessageRow', () => {
diff --git a/packages/chat/src/components/messages/__tests__/time.spec.ts b/packages/chat/src/components/messages/__tests__/time.spec.ts
new file mode 100644
index 0000000000..9831dfc409
--- /dev/null
+++ b/packages/chat/src/components/messages/__tests__/time.spec.ts
@@ -0,0 +1,117 @@
+import { isValidTimestamp, getMessageTimestamp } from '../time';
+
+describe('isValidTimestamp', () => {
+ it('returns false for missing values', () => {
+ expect(isValidTimestamp(undefined)).toBe(false);
+ expect(isValidTimestamp(null)).toBe(false);
+ expect(isValidTimestamp('')).toBe(false);
+ });
+
+ it('returns false for unparseable strings', () => {
+ expect(isValidTimestamp('not-a-date')).toBe(false);
+ });
+
+ it('returns true for ISO date strings', () => {
+ expect(isValidTimestamp('2026-06-12T15:42:00.000Z')).toBe(true);
+ });
+});
+
+describe('getMessageTimestamp', () => {
+ const NOW = new Date('2026-06-12T15:42:00.000Z').getTime();
+
+ beforeEach(() => {
+ jest.useFakeTimers().setSystemTime(NOW);
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('returns null for missing or invalid values', () => {
+ expect(getMessageTimestamp(undefined, 'en-US')).toBeNull();
+ expect(getMessageTimestamp(null, 'en-US')).toBeNull();
+ expect(getMessageTimestamp('not-a-date', 'en-US')).toBeNull();
+ });
+
+ it('formats relative and absolute time for a recent message', () => {
+ const twoHoursAgo = new Date(NOW - 2 * 60 * 60 * 1000).toISOString();
+ const result = getMessageTimestamp(twoHoursAgo, 'en-US');
+ expect(result).not.toBeNull();
+ expect(result?.relative).toBe('2 hours ago');
+ expect(result?.iso).toBe(twoHoursAgo);
+ expect(result?.absolute).toContain('2026');
+ });
+
+ it('flags messages under 24h as recent (prefer relative)', () => {
+ const justUnderADay = new Date(NOW - 23 * 60 * 60 * 1000).toISOString();
+ expect(getMessageTimestamp(justUnderADay, 'en-US')?.isRecent).toBe(true);
+ });
+
+ it('flags older messages as not recent (prefer absolute date)', () => {
+ const overADay = new Date(NOW - 25 * 60 * 60 * 1000).toISOString();
+ const monthAgo = new Date(NOW - 38 * 24 * 60 * 60 * 1000).toISOString();
+ expect(getMessageTimestamp(overADay, 'en-US')?.isRecent).toBe(false);
+ expect(getMessageTimestamp(monthAgo, 'en-US')?.isRecent).toBe(false);
+ });
+
+ it('uses "now" for the current instant', () => {
+ const result = getMessageTimestamp(new Date(NOW).toISOString(), 'en-US');
+ expect(result?.relative).toBe('now');
+ expect(result?.isRecent).toBe(true);
+ });
+
+ it('falls back to the default locale for a malformed locale tag', () => {
+ const iso = new Date(NOW - 60 * 1000).toISOString();
+ expect(() => getMessageTimestamp(iso, 'not a locale!!')).not.toThrow();
+ expect(getMessageTimestamp(iso, 'not a locale!!')).not.toBeNull();
+ });
+
+ /** Every message row formats its timestamp on each render; constructing the
+ * Intl formatters per call made them the costliest function of a send. */
+ it('reuses its formatters across calls for the same locale and clock', () => {
+ const { DateTimeFormat, RelativeTimeFormat } = Intl;
+ const replaceIntl = (key: 'DateTimeFormat' | 'RelativeTimeFormat', value: unknown) =>
+ Object.defineProperty(Intl, key, { value, configurable: true, writable: true });
+ const constructed = { absolute: 0, relative: 0 };
+ replaceIntl(
+ 'DateTimeFormat',
+ class extends DateTimeFormat {
+ constructor(...args: ConstructorParameters<typeof DateTimeFormat>) {
+ super(...args);
+ constructed.absolute += 1;
+ }
+ },
+ );
+ replaceIntl(
+ 'RelativeTimeFormat',
+ class extends RelativeTimeFormat {
+ constructor(...args: ConstructorParameters<typeof RelativeTimeFormat>) {
+ super(...args);
+ constructed.relative += 1;
+ }
+ },
+ );
+ try {
+ const iso = new Date(NOW - 5 * 60 * 1000).toISOString();
+ const first = getMessageTimestamp(iso, 'fr-CA', true);
+ const second = getMessageTimestamp(iso, 'fr-CA', true);
+ getMessageTimestamp(iso, 'fr-CA', true);
+
+ expect(second).toEqual(first);
+ expect(constructed).toEqual({ absolute: 1, relative: 1 });
+
+ getMessageTimestamp(iso, 'fr-CA', false);
+ expect(constructed).toEqual({ absolute: 2, relative: 1 });
+ } finally {
+ replaceIntl('DateTimeFormat', DateTimeFormat);
+ replaceIntl('RelativeTimeFormat', RelativeTimeFormat);
+ }
+ });
+
+ it('keeps a formatter per clock format', () => {
+ const iso = new Date(2026, 5, 12, 15, 5).toISOString();
+
+ expect(getMessageTimestamp(iso, 'en-US', true)?.absolute).toMatch(/3:05\sPM/);
+ expect(getMessageTimestamp(iso, 'en-US', false)?.absolute).toMatch(/15:05/);
+ });
+});
diff --git a/client/src/components/Chat/Messages/ui/__tests__/width.spec.ts b/packages/chat/src/components/messages/__tests__/width.spec.ts
similarity index 100%
rename from client/src/components/Chat/Messages/ui/__tests__/width.spec.ts
rename to packages/chat/src/components/messages/__tests__/width.spec.ts
diff --git a/packages/chat/src/components/messages/time.ts b/packages/chat/src/components/messages/time.ts
new file mode 100644
index 0000000000..f717aefe86
--- /dev/null
+++ b/packages/chat/src/components/messages/time.ts
@@ -0,0 +1,125 @@
+/** Locale-aware message timestamps, formatted once per locale and clock format. */
+
+export type MessageTimestamp = {
+ /** Localized relative time, e.g. "2 hours ago". */
+ relative: string;
+ /** Localized absolute date and time, e.g. "Jun 12, 2026, 3:42 PM". */
+ absolute: string;
+ /** ISO 8601 string for the `<time>` element's `dateTime` attribute. */
+ iso: string;
+ /**
+ * True when the message is recent enough that the relative form ("10 minutes ago")
+ * reads better than the absolute date. Past this window the absolute date is clearer.
+ */
+ isRecent: boolean;
+};
+
+/** Below this age the relative form is preferred over the absolute date. */
+const RECENT_THRESHOLD_MS = 24 * 60 * 60 * 1000;
+
+/** Returns true when `value` parses to a valid date. */
+export const isValidTimestamp = (value?: string | null): value is string => {
+ if (!value) {
+ return false;
+ }
+ return !Number.isNaN(new Date(value).getTime());
+};
+
+const RELATIVE_TIME_DIVISIONS: { amount: number; unit: Intl.RelativeTimeFormatUnit }[] = [
+ { amount: 60, unit: 'second' },
+ { amount: 60, unit: 'minute' },
+ { amount: 24, unit: 'hour' },
+ { amount: 7, unit: 'day' },
+ { amount: 4.34524, unit: 'week' },
+ { amount: 12, unit: 'month' },
+ { amount: Number.POSITIVE_INFINITY, unit: 'year' },
+];
+
+/**
+ * Intl formatters are expensive to construct and every message row formats its
+ * timestamp on each render, so they are built once per locale (and clock format).
+ */
+const resolvedLocales = new Map<string, string | undefined>();
+const relativeFormatters = new Map<string, Intl.RelativeTimeFormat>();
+const absoluteFormatters = new Map<string, Intl.DateTimeFormat>();
+
+/** Returns the locale only when it is a syntactically valid BCP-47 tag, else undefined. */
+const resolveLocale = (locale?: string): string | undefined => {
+ if (!locale) {
+ return undefined;
+ }
+ if (resolvedLocales.has(locale)) {
+ return resolvedLocales.get(locale);
+ }
+ let resolved: string | undefined;
+ try {
+ Intl.DateTimeFormat.supportedLocalesOf(locale);
+ resolved = locale;
+ } catch {
+ resolved = undefined;
+ }
+ resolvedLocales.set(locale, resolved);
+ return resolved;
+};
+
+const getRelativeFormatter = (locale?: string): Intl.RelativeTimeFormat => {
+ const key = locale ?? '';
+ let formatter = relativeFormatters.get(key);
+ if (!formatter) {
+ formatter = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
+ relativeFormatters.set(key, formatter);
+ }
+ return formatter;
+};
+
+const getAbsoluteFormatter = (locale?: string, hour12?: boolean): Intl.DateTimeFormat => {
+ const key = `${locale ?? ''}|${String(hour12)}`;
+ let formatter = absoluteFormatters.get(key);
+ if (!formatter) {
+ formatter = new Intl.DateTimeFormat(locale, {
+ dateStyle: 'medium',
+ timeStyle: 'short',
+ hour12,
+ });
+ absoluteFormatters.set(key, formatter);
+ }
+ return formatter;
+};
+
+const formatRelativeTime = (from: Date, to: Date, locale?: string): string => {
+ const formatter = getRelativeFormatter(locale);
+ let duration = (from.getTime() - to.getTime()) / 1000;
+ for (const division of RELATIVE_TIME_DIVISIONS) {
+ if (Math.abs(duration) < division.amount) {
+ return formatter.format(Math.round(duration), division.unit);
+ }
+ duration /= division.amount;
+ }
+ return formatter.format(Math.round(duration), 'year');
+};
+
+/**
+ * Formats a message timestamp into locale-aware relative and absolute strings.
+ * Returns null when the value is missing or unparseable, so callers can skip
+ * rendering the timestamp entirely.
+ */
+export const getMessageTimestamp = (
+ value?: string | null,
+ locale?: string,
+ hour12?: boolean,
+): MessageTimestamp | null => {
+ if (!isValidTimestamp(value)) {
+ return null;
+ }
+
+ const date = new Date(value);
+ const now = new Date(Date.now());
+ const safeLocale = resolveLocale(locale);
+
+ return {
+ iso: date.toISOString(),
+ relative: formatRelativeTime(date, now, safeLocale),
+ absolute: getAbsoluteFormatter(safeLocale, hour12).format(date),
+ isRecent: Math.abs(now.getTime() - date.getTime()) < RECENT_THRESHOLD_MS,
+ };
+};
diff --git a/client/src/components/Chat/Messages/ui/width.ts b/packages/chat/src/components/messages/width.ts
similarity index 95%
rename from client/src/components/Chat/Messages/ui/width.ts
rename to packages/chat/src/components/messages/width.ts
index 2b4a43e682..4fe55240c7 100644
--- a/client/src/components/Chat/Messages/ui/width.ts
+++ b/packages/chat/src/components/messages/width.ts
@@ -4,7 +4,7 @@ export function getMessageRowWidthClass({
}: {
fullWidth?: boolean;
hasParallelContent?: boolean;
-} = {}) {
+} = {}): string {
if (fullWidth) return 'w-full max-w-full sm:px-2';
if (hasParallelContent) return 'w-full sm:px-2 md:max-w-[58rem] xl:max-w-[70rem]';
return 'w-full sm:px-2 md:max-w-3xl xl:max-w-4xl';
diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.ts
index 1b25e67969..5c6fe7bbde 100644
--- a/packages/chat/src/react.ts
+++ b/packages/chat/src/react.ts
@@ -118,3 +118,10 @@ export type { ReactQueryChatStateOptions } from './react/state';
export { composerLiftFamily } from './react/lift';
export { showSkillsPopoverFamily } from './react/skills';
export { useComposerOverlay, composerOverlayCountFamily } from './react/overlay';
+export { default as useTimeTick } from './react/tick';
+export {
+ useMessagesHost,
+ MessagesHostProvider,
+ setDefaultMessagesHost,
+} from './react/messages/host';
+export type { MessagesHost } from './react/messages/host';
diff --git a/packages/chat/src/react/messages/host.tsx b/packages/chat/src/react/messages/host.tsx
new file mode 100644
index 0000000000..8c2b1c443e
--- /dev/null
+++ b/packages/chat/src/react/messages/host.tsx
@@ -0,0 +1,52 @@
+import { createContext, useContext } from 'react';
+import type { TMessage } from 'librechat-data-provider';
+import type { ReactNode } from 'react';
+
+/**
+ * Everything the message list reads from the app: viewer preferences, and render slots for the
+ * pieces of a row that have not moved into this package yet. Members are hooks or slots, called
+ * unconditionally, and a host stays the same object for the life of the tree it wraps.
+ *
+ * It is an interface so an app can declare members of rows it has not handed to this package
+ * yet, by augmenting `@librechat/chat/react`.
+ */
+export interface MessagesHost {
+ /** The viewer's clock preference as `hour12`; `undefined` follows the locale's convention. */
+ useHour12: () => boolean | undefined;
+ /** Renders the files attached to a user message, above its text. */
+ renderFiles: (message: TMessage) => ReactNode;
+}
+
+/** The host rows read outside any provider before an app registers one: locale clock, no slots. */
+const fallbackHost: MessagesHost = {
+ useHour12: () => undefined,
+ renderFiles: () => null,
+};
+
+const MessagesHostContext = createContext<MessagesHost | null>(null);
+
+let defaultHost: MessagesHost = fallbackHost;
+
+/**
+ * Registers the host that rows rendered outside any `MessagesHostProvider` read. An app registers
+ * its own once, when the module that builds it loads; a provider always wins over it.
+ */
+export function setDefaultMessagesHost(host: MessagesHost): void {
+ defaultHost = host;
+}
+
+/** Supplies the host the message list reads from. */
+export function MessagesHostProvider({
+ host,
+ children,
+}: {
+ host: MessagesHost;
+ children: ReactNode;
+}): ReactNode {
+ return <MessagesHostContext.Provider value={host}>{children}</MessagesHostContext.Provider>;
+}
+
+/** The host of the nearest provider, else the registered default, else the fallback. */
+export function useMessagesHost(): MessagesHost {
+ return useContext(MessagesHostContext) ?? defaultHost;
+}
diff --git a/client/src/hooks/useTimeTick.ts b/packages/chat/src/react/tick.ts
similarity index 100%
rename from client/src/hooks/useTimeTick.ts
rename to packages/chat/src/react/tick.ts