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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
↔️ fix: Follow the Interface Direction in Radix, the Composer and First Paint (#17264)
Marco Beretta6c0d3a7cbb97
diff --git a/client/index.html b/client/index.htmlindex 049c2e3fc4..ca68ab0dee 100644--- a/client/index.html+++ b/client/index.html@@ -47,6 +47,24 @@document.documentElement.style.setProperty('--ui-scale', String(uiScale));}+ /* Direction before first paint, from the same sources `detectInitialLanguage` reads,+ * so a right-to-left interface does not render one frame left-to-right. The list is+ * the right-to-left locales the app ships; i18n.ts reapplies `dir` once it loads. */+ const cookie = document.cookie.match(/(?:^|;\s*)lang=([^;]*)/);+ let lang = cookie ? cookie[1] : '';+ if (!lang) {+ try {+ lang = localStorage.getItem('lang') || '';+ lang = JSON.parse(lang);+ } catch (e) {+ /* Stored unquoted, or Web Storage denied: the raw value or the browser language. */+ }+ }+ lang = String(lang || navigator.language || '').toLowerCase();+ if (['ar', 'he', 'fa', 'ug'].indexOf(lang.split(/[-_]/)[0]) !== -1) {+ document.documentElement.dir = 'rtl';+ }+let theme = null;try {theme = localStorage.getItem('color-theme');diff --git a/client/package.json b/client/package.jsonindex a26e0cb9ae..a07bb8cded 100644--- a/client/package.json+++ b/client/package.json@@ -47,6 +47,7 @@"@radix-ui/react-checkbox": "^1.3.11","@radix-ui/react-collapsible": "^1.1.20","@radix-ui/react-dialog": "^1.1.23",+ "@radix-ui/react-direction": "^1.1.4","@radix-ui/react-dropdown-menu": "^2.1.24","@radix-ui/react-hover-card": "^1.1.23","@radix-ui/react-icons": "^1.3.0",diff --git a/client/src/App.jsx b/client/src/App.jsxindex f8fc49a552..7b57c13a59 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -2,10 +2,10 @@ import { useEffect } from 'react';import { RecoilRoot } from 'recoil';import { DndProvider } from 'react-dnd';import { RouterProvider } from 'react-router-dom';-import * as RadixToast from '@radix-ui/react-toast';import { HTML5Backend } from 'react-dnd-html5-backend';import { Toast, ToastViewport, ToastProvider, useInputModality } from '@librechat/client';import { QueryClient, QueryClientProvider, QueryCache, MutationCache } from '@tanstack/react-query';+import Direction, { ToastSwipeProvider } from '~/Providers/Direction';import { ScreenshotProvider, useApiErrorBoundary } from './hooks';import WakeLockManager from '~/components/System/WakeLockManager';import QueryDevtoolsGate from '~/components/QueryDevtoolsGate';@@ -55,12 +55,13 @@ const App = () => {<RecoilRoot><LanguageSync /><UiScaleSync />- <LiveAnnouncer>- <DeploymentTheme>- <RadixToast.Provider>- <ToastProvider>- <DndProvider backend={HTML5Backend}>- {/* Location updates commit in the caller's own task instead+ <Direction>+ <LiveAnnouncer>+ <DeploymentTheme>+ <ToastSwipeProvider>+ <ToastProvider>+ <DndProvider backend={HTML5Backend}>+ {/* Location updates commit in the caller's own task insteadof React's transition lane. A transition keeps theOUTGOING route painted until the incoming one finishesrendering, so switching conversations left the previous@@ -79,16 +80,17 @@ const App = () => {transition-safe reads are gated behind`_TRANSITION_SUPPORT_UNSTABLE` hooks this app does not use.Worth revisiting once that state has moved to Jotai. */}- <RouterProvider router={router} useTransitions={false} />- <WakeLockManager />- <QueryDevtoolsGate />- <Toast />- <ToastViewport />- </DndProvider>- </ToastProvider>- </RadixToast.Provider>- </DeploymentTheme>- </LiveAnnouncer>+ <RouterProvider router={router} useTransitions={false} />+ <WakeLockManager />+ <QueryDevtoolsGate />+ <Toast />+ <ToastViewport />+ </DndProvider>+ </ToastProvider>+ </ToastSwipeProvider>+ </DeploymentTheme>+ </LiveAnnouncer>+ </Direction></RecoilRoot></QueryClientProvider>);diff --git a/client/src/Providers/Direction.tsx b/client/src/Providers/Direction.tsxnew file mode 100644index 0000000000..314a46a795--- /dev/null+++ b/client/src/Providers/Direction.tsx@@ -0,0 +1,24 @@+import { useTranslation } from 'react-i18next';+import * as RadixToast from '@radix-ui/react-toast';+import { DirectionProvider, useDirection } from '@radix-ui/react-direction';+import type { ReactNode } from 'react';++/**+ * Radix primitives read their direction from this context, never from `<html dir>`, and fall back+ * to `ltr`. Without it Tabs, Select and menus render `dir="ltr"` subtrees and map arrow keys as LTR+ * inside a right-to-left interface.+ */+export default function Direction({ children }: { children: ReactNode }) {+ const { i18n } = useTranslation();+ return <DirectionProvider dir={i18n.dir()}>{children}</DirectionProvider>;+}++/** Swiping a toast away runs toward the inline end, which is the left edge in a right-to-left UI. */+export function ToastSwipeProvider({ children }: { children: ReactNode }) {+ const dir = useDirection();+ return (+ <RadixToast.Provider swipeDirection={dir === 'rtl' ? 'left' : 'right'}>+ {children}+ </RadixToast.Provider>+ );+}diff --git a/client/src/Providers/MessagePartsHostContext.tsx b/client/src/Providers/MessagePartsHostContext.tsxindex 6b00fa3e44..7e73f7b271 100644--- a/client/src/Providers/MessagePartsHostContext.tsx+++ b/client/src/Providers/MessagePartsHostContext.tsx@@ -130,8 +130,7 @@ export const appMessagePartsHost: MessagePartsHost = {useShowThinking: () => useAtomValue(showThinkingAtom),useAutoExpandTools: () => useRecoilValue<boolean>(store.autoExpandTools),useLaTeXParsing: () => useRecoilValue<boolean>(store.LaTeXParsing),- useChatDirection: () =>- useRecoilValue<string>(store.chatDirection).toLowerCase() === 'rtl' ? 'rtl' : 'ltr',+ useChatDirection: () => useRecoilValue(store.chatDirection),useUserTextPreferences: useAppUserTextPreferences,/* The atom rather than the auth context: AuthContextProvider mirrors the user into it, and the* public share route mounts outside that provider. */diff --git a/client/src/Providers/__tests__/bootDirection.spec.ts b/client/src/Providers/__tests__/bootDirection.spec.tsnew file mode 100644index 0000000000..967b6b250d--- /dev/null+++ b/client/src/Providers/__tests__/bootDirection.spec.ts@@ -0,0 +1,48 @@+import { resolve } from 'path';+import { readFileSync } from 'fs';++/** The inline shell script in `client/index.html` that sets `dir` before first paint. */+const bootScript = (() => {+ const html = readFileSync(resolve(__dirname, '../../../index.html'), 'utf8');+ const scripts = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map((match) => match[1]);+ const script = scripts.find((source) => source.includes('Direction before first paint'));+ if (!script) {+ throw new Error('client/index.html has no direction boot script');+ }+ return script;+})();++const runBoot = () => new Function(bootScript)();++const clearCookie = () => {+ document.cookie = 'lang=; expires=Thu, 01 Jan 1970 00:00:00 GMT';+};++describe('index.html direction boot', () => {+ beforeEach(() => {+ document.documentElement.removeAttribute('dir');+ localStorage.clear();+ clearCookie();+ });++ afterAll(clearCookie);++ it('marks the document right-to-left from the lang cookie', () => {+ document.cookie = 'lang=ar-EG';+ runBoot();+ expect(document.documentElement.dir).toBe('rtl');+ });++ it.each([JSON.stringify('he'), 'fa'])('reads a stored language %s', (stored) => {+ localStorage.setItem('lang', stored);+ runBoot();+ expect(document.documentElement.dir).toBe('rtl');+ });++ it('leaves a left-to-right language alone', () => {+ document.cookie = 'lang=en-US';+ localStorage.setItem('lang', JSON.stringify('ar'));+ runBoot();+ expect(document.documentElement.dir).toBe('');+ });+});diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsxindex 1a7dfacabf..b49ed2bfe4 100644--- a/client/src/components/Chat/Input/ChatForm.tsx+++ b/client/src/components/Chat/Input/ChatForm.tsx@@ -3,6 +3,7 @@ import { useAtom } from 'jotai';import { useRecoilValue } from 'recoil';import { useWatch } from 'react-hook-form';import { useNavigate } from 'react-router-dom';+import { useDirection } from '@radix-ui/react-direction';import { useSteering, showStopButtonByIndex, useComposerRestoreHost } from '@librechat/chat/react';import {composerSurfaceClasses,@@ -237,10 +238,6 @@ const ChatForm = memo(function ChatForm({*/const quotesEnabled = useMemo(() => !isAssistantsEndpoint(endpoint), [endpoint]);- const isRTL = useMemo(- () => (chatDirection != null ? chatDirection?.toLowerCase() === 'rtl' : false),- [chatDirection],- );const invalidAssistant = useMemo(() =>isAssistantsEndpoint(endpoint) &&@@ -495,6 +492,11 @@ const ChatForm = memo(function ChatForm({});const textValue = useWatch({ control: methods.control, name: 'text' });+ const interfaceDirection = useDirection();+ /** An empty `dir="auto"` field resolves to LTR, which would park an RTL interface's placeholder on+ * the wrong edge, so the empty field follows the interface until text gives it a direction. */+ const autoDirection = textValue ? 'auto' : interfaceDirection;+ const textDirection = chatDirection === 'auto' ? autoDirection : chatDirection;/** The composer commits once per keystroke for the row count and the send* button; a second commit for a row count that did not move (or that no@@ -725,6 +727,9 @@ const ChatForm = memo(function ChatForm({return (<form+ /* A forced direction mirrors the whole composer, chrome included; `auto`+ leaves the layout to the page and lets the text field follow its text. */+ dir={chatDirection === 'auto' ? undefined : chatDirection}onSubmit={methods.handleSubmit((data) => {if (!isPreparingFromUrl && submitComposerText(data) !== false) {clearSettingsError();@@ -767,7 +772,6 @@ const ChatForm = memo(function ChatForm({className={cn('mx-4 -mb-3 flex min-w-0 flex-wrap items-center gap-1.5 rounded-t-2xl','border-border-light bg-surface-secondary border px-2 pt-2 pb-5',- isRTL && 'flex-row-reverse',)}>{project ? <ProjectLandingChip project={project} /> : null}@@ -782,7 +786,7 @@ const ChatForm = memo(function ChatForm({) : null}</div>)}- <div className={cn('flex w-full items-center', isRTL && 'flex-row-reverse')}>+ <div className="flex w-full items-center"><Mentionindex={index}popoverAtom={plusPopoverAtom}@@ -847,7 +851,6 @@ const ChatForm = memo(function ChatForm({files={files}setFiles={setFiles}setFilesLoading={setFilesLoading}- isRTL={isRTL}index={index}isPastedTextFile={isPastedTextFile}isPasteActionPending={isPasteActionPending}@@ -860,7 +863,7 @@ const ChatForm = memo(function ChatForm({onSave={pastedTextEdit.saveEdit}/>{endpoint && (- <div className={cn('flex', isRTL ? 'flex-row-reverse' : 'flex-row')}>+ <div className="flex"><divclassName={cn('relative flex-1',@@ -881,6 +884,7 @@ const ChatForm = memo(function ChatForm({><TextareaAutosize{...registerProps}+ dir={textDirection}ref={(e) => {ref(e);(@@ -937,7 +941,7 @@ const ChatForm = memo(function ChatForm({{/* Sits over the fade scrim in the corner of the inputrather than in its own column beside it, so a long draftdoes not push an orphaned control off to the side. */}- <div className="absolute right-2 bottom-1 z-10">+ <div className="absolute inset-e-2 bottom-1 z-10"><CollapseChatisCollapsed={isCollapsed}isScrollable={isMoreThanThreeRows && !answerMode.composerLocked}@@ -973,7 +977,6 @@ const ChatForm = memo(function ChatForm({><Barindex={index}- isRTL={isRTL}disabled={disableInputs}agentId={conversation?.agent_id}/* The RAW endpoint, not the effective type above: the attach@@ -998,7 +1001,7 @@ const ChatForm = memo(function ChatForm({speechDisabled={speechDisabled}dictation={dictation}approvalSlot={- <div className={cn('flex items-center gap-1.5', isRTL && 'flex-row-reverse')}>+ <div className="flex items-center gap-1.5"><CodeApprovalMenuconversation={conversation}addedConversation={addedConvo}diff --git a/client/src/components/Chat/Input/Composer/Bar.tsx b/client/src/components/Chat/Input/Composer/Bar.tsxindex d57ab0e61d..7df732d6fb 100644--- a/client/src/components/Chat/Input/Composer/Bar.tsx+++ b/client/src/components/Chat/Input/Composer/Bar.tsx@@ -180,7 +180,6 @@ export function ChipModes({ modes }: ChipModesProps) {interface BarProps {index: number;- isRTL: boolean;disabled: boolean;agentId?: string | null;endpoint?: string | null;@@ -217,7 +216,6 @@ interface BarProps {*/function Bar({index,- isRTL,disabled,agentId,endpoint,@@ -316,10 +314,7 @@ function Bar({const above = chipsInline ? EMPTY_ENTRIES : packedEntries;const inline = chipsInline ? packedEntries : EMPTY_ENTRIES;- const rowClass = cn(- 'flex flex-wrap items-center gap-1.5',- isRTL ? 'flex-row-reverse' : 'flex-row',- );+ const rowClass = 'flex flex-wrap items-center gap-1.5';const barClass = 'flex flex-col gap-1.5 px-2 pb-2';const renderChip = (entry: PaletteEntry) => {@@ -450,10 +445,7 @@ function Bar({each takes over the job next to it (stop, and stop-and-send) ratherthan being replaced by a control that slides in somewhere else. Onlywhat has no job during a recording actually moves. */}- <div- ref={controlsRef}- className={cn('flex shrink-0 items-center gap-1.5', isRTL ? 'mr-auto' : 'ml-auto')}- >+ <div ref={controlsRef} className="ms-auto flex shrink-0 items-center gap-1.5">{/* One cell holding both: the settled controls drop out of it as theelapsed time rises into their place, and the row keeps one widththroughout so nothing beside it shifts. */}diff --git a/client/src/components/Chat/Input/Composer/Tray.tsx b/client/src/components/Chat/Input/Composer/Tray.tsxindex a0c71c1423..caa16c7511 100644--- a/client/src/components/Chat/Input/Composer/Tray.tsx+++ b/client/src/components/Chat/Input/Composer/Tray.tsx@@ -44,7 +44,6 @@ interface TrayProps {files: Map<string, ExtendedFile>;setFiles: FileSetter;setFilesLoading: React.Dispatch<React.SetStateAction<boolean>>;- isRTL: boolean;index: number;isPastedTextFile: (file: ExtendedFile) => boolean;isPasteActionPending: (file: ExtendedFile) => boolean;@@ -70,7 +69,6 @@ function Tray({files,setFiles,setFilesLoading,- isRTL,index,isPastedTextFile,isPasteActionPending,@@ -131,7 +129,6 @@ function Tray({<FileRowfiles={files}setFiles={setFiles}- isRTL={isRTL}abortUpload={abortUpload}setFilesLoading={setFilesLoading}index={index}diff --git a/client/src/components/Chat/Input/Composer/__tests__/Tray.spec.tsx b/client/src/components/Chat/Input/Composer/__tests__/Tray.spec.tsxindex d1a17149d9..80664dc79e 100644--- a/client/src/components/Chat/Input/Composer/__tests__/Tray.spec.tsx+++ b/client/src/components/Chat/Input/Composer/__tests__/Tray.spec.tsx@@ -46,7 +46,6 @@ function renderTray(files={files}setFiles={jest.fn()}setFilesLoading={jest.fn()}- isRTL={false}index={0}isPastedTextFile={mockIsPastedTextFile}isPasteActionPending={mockIsPasteActionPending}diff --git a/client/src/components/Chat/Input/Files/FileRow.tsx b/client/src/components/Chat/Input/Files/FileRow.tsxindex d21342662c..bee3166100 100644--- a/client/src/components/Chat/Input/Files/FileRow.tsx+++ b/client/src/components/Chat/Input/Files/FileRow.tsx@@ -28,7 +28,6 @@ export default function FileRow({tool_resource,index,fileFilter,- isRTL = false,Wrapper,isPastedTextFile,isPasteActionPending,@@ -44,7 +43,6 @@ export default function FileRow({agent_id?: string;tool_resource?: EToolResources;index?: number;- isRTL?: boolean;Wrapper?: React.FC<{ children: React.ReactNode }>;/** Marks chips the composer generated from a long paste. Provenance comes from the caller's* marker registry rather than the filename, which a deliberate upload can share. */@@ -114,13 +112,7 @@ export default function FileRow({return (/* `items-center` so a card and a thumbnail of different heights shareone baseline instead of hanging from the top of the tallest row. */- <div- className={- isRTL- ? 'flex w-full max-w-full flex-row-reverse flex-wrap items-center gap-1.5'- : 'flex w-full max-w-full flex-wrap items-center gap-1.5'- }- >+ <div className="flex w-full max-w-full flex-wrap items-center gap-1.5">{files.reduce((acc, current) => {diff --git a/client/src/components/Chat/Messages/Content/EditContentParts.tsx b/client/src/components/Chat/Messages/Content/EditContentParts.tsxindex ef25f38c1f..b93be4e245 100644--- a/client/src/components/Chat/Messages/Content/EditContentParts.tsx+++ b/client/src/components/Chat/Messages/Content/EditContentParts.tsx@@ -47,7 +47,7 @@ export default function EditContentParts({}: EditContentPartsProps) {const localize = useLocalize();const { useChatDirection, useMessagesEditing } = useMessagePartsHost();- const isRTL = useChatDirection() === 'rtl';+ const chatDirection = useChatDirection();const { conversation, ask, getMessages, setMessages } = useMessagesEditing();const getAddedConvo = useGetAddedConvo();const firstEditorRef = useRef<HTMLTextAreaElement | null>(null);@@ -395,7 +395,7 @@ export default function EditContentParts({return (<labelkey={`editor-${messageId}-${absoluteIndex}`}- dir={isRTL ? 'rtl' : 'ltr'}+ dir={chatDirection === 'auto' ? undefined : chatDirection}className="text-text-secondary flex min-w-0 flex-col gap-1.5 text-xs font-medium">{label}@@ -418,12 +418,11 @@ export default function EditContentParts({}disabled={isBusy}minRows={3}- dir={isRTL ? 'rtl' : 'ltr'}+ dir={chatDirection}className={cn('message-editor-text max-h-[65vh] min-h-24 w-full resize-y rounded-lg','border-border-medium bg-surface-tertiary-alt border px-3 py-2',- 'text-text-primary font-normal',- isRTL ? 'text-right' : 'text-left',+ 'text-text-primary text-start font-normal','disabled:opacity-50 md:max-h-[75vh]',)}/>diff --git a/client/src/components/Chat/Messages/Content/EditMessage.tsx b/client/src/components/Chat/Messages/Content/EditMessage.tsxindex ab2e584242..350288099d 100644--- a/client/src/components/Chat/Messages/Content/EditMessage.tsx+++ b/client/src/components/Chat/Messages/Content/EditMessage.tsx@@ -44,7 +44,7 @@ const EditMessage = ({const updateMessageMutation = useUpdateMessageMutation(conversationId ?? '');const localize = useLocalize();- const isRTL = useChatDirection() === 'rtl';+ const chatDirection = useChatDirection();const getAddedConvo = useGetAddedConvo();@@ -273,8 +273,7 @@ const EditMessage = ({className={cn('message-editor-text max-h-[65vh] min-h-24 w-full resize-y whitespace-pre-wrap','border-border-medium bg-surface-tertiary-alt rounded-lg border break-words',- 'text-text-primary px-3 py-2',- isRTL ? 'text-right' : 'text-left',+ 'text-text-primary px-3 py-2 text-start','disabled:opacity-50 md:max-h-[75vh]',)}aria-label={localize('com_ui_message_input')}@@ -284,7 +283,7 @@ const EditMessage = ({: 'Control+S Meta+S Escape'}disabled={isSubmitting || updateMessageMutation.isLoading}- dir={isRTL ? 'rtl' : 'ltr'}+ dir={chatDirection}/>{/* The actions wrap rather than hold one unbreakable row: on a 320px assistantturn the identity column and page padding leave less width than the threediff --git a/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsx b/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsxindex 6aaba72901..b04b1c4f7d 100644--- a/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/EditContentParts.spec.tsx@@ -7,7 +7,7 @@ import EditContentParts from '../EditContentParts';const mockMutateAsync = jest.fn();const mockSetMessages = jest.fn();const mockAsk = jest.fn();-let mockChatDirection = 'LTR';+let mockChatDirection = 'auto';jest.mock('recoil', () => ({useRecoilValue: () => mockChatDirection,@@ -77,7 +77,7 @@ describe('EditContentParts', () => {mockMutateAsync.mockReset();mockAsk.mockReset();mockMutateAsync.mockResolvedValue({});- mockChatDirection = 'LTR';+ mockChatDirection = 'auto';message.content = undefined;mockThread = [parentMessage, message];});@@ -653,7 +653,7 @@ describe('EditContentParts', () => {});it('turns the editor around for a right-to-left chat direction', () => {- mockChatDirection = 'RTL';+ mockChatDirection = 'rtl';render(<EditContentPartscontent={content}@@ -668,10 +668,10 @@ describe('EditContentParts', () => {const editor = screen.getByRole('textbox');expect(editor).toHaveAttribute('dir', 'rtl');- expect(editor).toHaveClass('text-right');+ expect(editor).toHaveClass('text-start');});- it('leaves the editor left-to-right by default', () => {+ it('lets the editor resolve its direction from the text by default', () => {render(<EditContentPartscontent={content}@@ -685,8 +685,8 @@ describe('EditContentParts', () => {);const editor = screen.getByRole('textbox');- expect(editor).toHaveAttribute('dir', 'ltr');- expect(editor).toHaveClass('text-left');+ expect(editor).toHaveAttribute('dir', 'auto');+ expect(editor).toHaveClass('text-start');});it('sizes the editor from the configured message font rather than pinning it', () => {diff --git a/client/src/components/Nav/Settings/controls.tsx b/client/src/components/Nav/Settings/controls.tsxindex a1429e1258..7fe18d48cc 100644--- a/client/src/components/Nav/Settings/controls.tsx+++ b/client/src/components/Nav/Settings/controls.tsx@@ -43,9 +43,6 @@ export function LangSetting() {(value: string) => {const userLang =value === 'auto' ? navigator.language || navigator.languages?.[0] || 'en-US' : value;- requestAnimationFrame(() => {- document.documentElement.lang = userLang;- });setLangcode(userLang);Cookies.set('lang', userLang, { expires: 365 });},diff --git a/client/src/components/Nav/SettingsTabs/Chat/ChatDirection.tsx b/client/src/components/Nav/SettingsTabs/Chat/ChatDirection.tsxindex 0bffbe9f78..5a41770ca5 100644--- a/client/src/components/Nav/SettingsTabs/Chat/ChatDirection.tsx+++ b/client/src/components/Nav/SettingsTabs/Chat/ChatDirection.tsx@@ -1,35 +1,33 @@-import React from 'react';import { useRecoilState } from 'recoil';-import { Button } from '@librechat/client';+import { Dropdown } from '@librechat/client';+import type { ChatDirection as TChatDirection } from '~/store/settings';import { useLocalize } from '~/hooks';import store from '~/store';const ChatDirection = () => {- const [direction, setDirection] = useRecoilState(store.chatDirection);const localize = useLocalize();+ const [direction, setDirection] = useRecoilState(store.chatDirection);++ const options = [+ { value: 'auto', label: localize('com_ui_auto') },+ { value: 'ltr', label: localize('chat_direction_left_to_right') },+ { value: 'rtl', label: localize('chat_direction_right_to_left') },+ ];- const toggleChatDirection = () => {- setDirection((prev) => (prev === 'LTR' ? 'RTL' : 'LTR'));- };+ const labelId = 'chat-direction-label';return (- <div className="flex flex-wrap items-center justify-between gap-2">- <div className="flex items-center space-x-2">- <span id="chat-direction-label">{localize('com_nav_chat_direction')}</span>- </div>- <Button- variant="outline"- aria-label={localize('com_nav_chat_direction_selected', {- direction:- direction === 'LTR'- ? localize('chat_direction_left_to_right')- : localize('chat_direction_right_to_left'),- })}- onClick={toggleChatDirection}- data-testid="chatDirection"- >- {direction.toLowerCase()}- </Button>+ <div className="flex w-full flex-wrap items-center justify-between gap-2">+ <div id={labelId}>{localize('com_nav_chat_direction')}</div>+ <Dropdown+ value={direction}+ options={options}+ onChange={(value: string) => setDirection(value as TChatDirection)}+ testId="chatDirection"+ sizeClasses="z-50 w-[9.375rem]"+ className="z-50"+ aria-labelledby={labelId}+ /></div>);};diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 6ac0955e7b..f45537db93 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -832,7 +832,6 @@"com_nav_center_chat_input": "Center Chat Input on Welcome Screen","com_nav_change_picture": "Change picture","com_nav_chat_direction": "Chat direction",- "com_nav_chat_direction_selected": "Chat direction: {{direction}}","com_nav_chat_title_in_tab": "Display chat title in tab","com_nav_clear_all_chats": "Delete all chats","com_nav_clear_cache_confirm_message": "Are you sure you want to clear the cache?",diff --git a/client/src/store/__tests__/chatDirection.spec.ts b/client/src/store/__tests__/chatDirection.spec.tsnew file mode 100644index 0000000000..dac5d362a2--- /dev/null+++ b/client/src/store/__tests__/chatDirection.spec.ts@@ -0,0 +1,33 @@+const DIRECTION_KEY = 'chatDirection';++const readStoredDirection = async (): Promise<string> => {+ const { snapshot_UNSTABLE } = await import('recoil');+ const settings = await import('../settings');+ return snapshot_UNSTABLE().getLoadable(settings.default.chatDirection).valueOrThrow();+};++describe('chatDirection', () => {+ beforeEach(() => {+ jest.resetModules();+ localStorage.clear();+ });++ it('defaults to auto so typed text resolves its own direction', async () => {+ expect(await readStoredDirection()).toBe('auto');+ });++ it.each([+ ['LTR', 'ltr'],+ ['RTL', 'rtl'],+ ['rtl', 'rtl'],+ ])('keeps a stored %s choice as %s', async (stored, expected) => {+ localStorage.setItem(DIRECTION_KEY, JSON.stringify(stored));+ expect(await readStoredDirection()).toBe(expected);+ expect(localStorage.getItem(DIRECTION_KEY)).toBe(JSON.stringify(expected));+ });++ it('falls back to auto for an unrecognized stored value', async () => {+ localStorage.setItem(DIRECTION_KEY, JSON.stringify('sideways'));+ expect(await readStoredDirection()).toBe('auto');+ });+});diff --git a/client/src/store/settings.ts b/client/src/store/settings.tsindex 6c66181d09..dd043323f7 100644--- a/client/src/store/settings.ts+++ b/client/src/store/settings.ts@@ -23,6 +23,15 @@ const normalizeSavedSpeechEngine = (return legacyExternalEngines.has(engine) ? STTEndpoints.external : STTEndpoints.browser;};+/** `auto` lets each field resolve its direction from what is typed; the others force it. */+export type ChatDirection = 'auto' | 'ltr' | 'rtl';++/** Older clients stored `LTR`/`RTL`; anything unrecognized falls back to `auto`. */+const normalizeChatDirection = (direction: ChatDirection): ChatDirection => {+ const value = typeof direction === 'string' ? direction.toLowerCase() : '';+ return value === 'ltr' || value === 'rtl' ? value : 'auto';+};+// Static atoms without localStorageconst staticAtoms = {abortScroll: atom<boolean>({ key: 'abortScroll', default: false }),@@ -59,7 +68,11 @@ const localStorageAtoms = {// Chat settingsenterToSend: atomWithLocalStorage('enterToSend', false),maximizeChatSpace: atomWithLocalStorage('maximizeChatSpace', false),- chatDirection: atomWithLocalStorage('chatDirection', 'LTR'),+ chatDirection: atomWithLocalStorage<ChatDirection>(+ 'chatDirection',+ 'auto',+ normalizeChatDirection,+ ),autoExpandTools: atomWithLocalStorage(LocalStorageKeys.AUTO_EXPAND_TOOLS, false),saveDrafts: atomWithLocalStorage('saveDrafts', true),/**diff --git a/package-lock.json b/package-lock.jsonindex 3845f13783..c2ffa9352a 100644--- a/package-lock.json+++ b/package-lock.json@@ -876,6 +876,7 @@"@radix-ui/react-checkbox": "^1.3.11","@radix-ui/react-collapsible": "^1.1.20","@radix-ui/react-dialog": "^1.1.23",+ "@radix-ui/react-direction": "^1.1.4","@radix-ui/react-dropdown-menu": "^2.1.24","@radix-ui/react-hover-card": "^1.1.23","@radix-ui/react-icons": "^1.3.0",@@ -42049,6 +42050,7 @@"@radix-ui/react-checkbox": "^1.3.11","@radix-ui/react-collapsible": "^1.1.20","@radix-ui/react-dialog": "^1.1.23",+ "@radix-ui/react-direction": "^1.1.4","@radix-ui/react-dropdown-menu": "^2.1.24","@radix-ui/react-hover-card": "^1.1.23","@radix-ui/react-icons": "^1.3.0",diff --git a/packages/chat/src/react/host.tsx b/packages/chat/src/react/host.tsxindex 5bb2e699d9..32eb206448 100644--- a/packages/chat/src/react/host.tsx+++ b/packages/chat/src/react/host.tsx@@ -76,8 +76,8 @@ export interface MessagePartsHost {useAutoExpandTools: () => boolean;/** Whether the viewer wants LaTeX in markdown rendered as math. */useLaTeXParsing: () => boolean;- /** The direction the viewer reads chat text in. */- useChatDirection: () => 'ltr' | 'rtl';+ /** The direction chat text is typed in; `auto` resolves it from the text itself. */+ useChatDirection: () => 'auto' | 'ltr' | 'rtl';/** How the viewer prefers user-authored text to display. */useUserTextPreferences: () => MessagePartsUserTextPreferences;/** The signed-in user. */diff --git a/packages/client/package.json b/packages/client/package.jsonindex 13b65bcaf9..62cfe9b821 100644--- a/packages/client/package.json+++ b/packages/client/package.json@@ -52,6 +52,7 @@"@radix-ui/react-checkbox": "^1.3.11","@radix-ui/react-collapsible": "^1.1.20","@radix-ui/react-dialog": "^1.1.23",+ "@radix-ui/react-direction": "^1.1.4","@radix-ui/react-dropdown-menu": "^2.1.24","@radix-ui/react-hover-card": "^1.1.23","@radix-ui/react-icons": "^1.3.0",diff --git a/packages/client/src/components/TextareaAutosize.tsx b/packages/client/src/components/TextareaAutosize.tsxindex 719ffc45ab..a1246e8ff3 100644--- a/packages/client/src/components/TextareaAutosize.tsx+++ b/packages/client/src/components/TextareaAutosize.tsx@@ -5,7 +5,6 @@ import {useLayoutEffect,useState,} from 'react';-import { useAtomValue } from 'jotai';import ReactTextareaAutosize from 'react-textarea-autosize';import type { TextareaAutosizeProps } from 'react-textarea-autosize';import type { FocusOutline } from './Focus';@@ -18,7 +17,6 @@ import {fieldFillTransparent,} from './Field';import { focusOutlineVariants } from './Focus';-import { chatDirectionAtom } from '~/store';import { cn } from '~/utils';import './Field.css';@@ -55,13 +53,12 @@ export type TextareaAutosizePropsWithAria =export const TextareaAutosize: ForwardRefExoticComponent<TextareaAutosizePropsWithAria & RefAttributes<HTMLTextAreaElement>> = forwardRef<HTMLTextAreaElement, TextareaAutosizePropsWithAria>(- ({ focusOutline, variant = 'default', className, ...props }, ref) => {+ ({ focusOutline, variant = 'default', className, dir = 'auto', ...props }, ref) => {const [, setIsRerendered] = useState(false);- const chatDirection = useAtomValue(chatDirectionAtom).toLowerCase();useLayoutEffect(() => setIsRerendered(true), []);return (<ReactTextareaAutosize- dir={chatDirection}+ dir={dir}{...props}className={cn(diff --git a/packages/client/src/store.ts b/packages/client/src/store.tsindex 660b825dca..6123a9e10a 100644--- a/packages/client/src/store.ts+++ b/packages/client/src/store.ts@@ -1,9 +1,6 @@import { atom, PrimitiveAtom } from 'jotai';import { NotificationSeverity } from '~/common';-export const chatDirectionAtom: PrimitiveAtom<string> & {- init: string;-} = atom<string>('ltr');export const fontSizeAtom: PrimitiveAtom<string> & {init: string;} = atom<string>('text-base');