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: Anchor the Sidebar, Mobile Drawer and Panels to Inline Edges in RTL (#17266)
Marco Beretta8cf62da528cf
diff --git a/client/src/components/Chat/Menus/Endpoints/CustomMenu.tsx b/client/src/components/Chat/Menus/Endpoints/CustomMenu.tsxindex 78fa1e141e..7ebde5029b 100644--- a/client/src/components/Chat/Menus/Endpoints/CustomMenu.tsx+++ b/client/src/components/Chat/Menus/Endpoints/CustomMenu.tsx@@ -1,5 +1,6 @@import * as React from 'react';import * as Ariakit from '@ariakit/react';+import useDirection, { inlineSide } from '~/hooks/Nav/useDirection';import { cn } from '~/utils';export interface CustomMenuProps extends Ariakit.MenuButtonProps<'div'> {@@ -32,10 +33,13 @@ export const CustomMenu = React.forwardRef<HTMLDivElement, CustomMenuProps>(func) {const parent = Ariakit.useMenuContext();const searchable = searchValue != null || !!onSearch || !!combobox;+ /** Submenus open toward the inline end, away from the sidebar, in either direction;+ * Ariakit also derives the open/close arrow keys from this physical side. */+ const direction = useDirection();const menuStore = Ariakit.useMenuStore({showTimeout: 100,- placement: parent ? 'right' : 'left',+ placement: inlineSide(direction, parent ? 'end' : 'start'),defaultOpen: defaultOpen,});const isOpen = menuStore.useState('open');@@ -72,7 +76,7 @@ export const CustomMenu = React.forwardRef<HTMLDivElement, CustomMenuProps>(funcunmountOnHidegutter={parent ? -4 : 4}className={cn(- parent ? 'animate-popover-left ml-3' : 'animate-popover',+ parent ? 'animate-popover-left ms-3' : 'animate-popover','z-40 flex max-h-[min(28.125rem,var(--popover-available-height))] w-full outline-hidden!','border-border-menu rounded-theme-menu-panel w-[var(--menu-width,auto)] min-w-[min(18.75rem,90vw)] flex-col overflow-auto border','bg-surface-menu text-text-primary text-sm shadow-lg',@@ -96,7 +100,7 @@ export const CustomMenu = React.forwardRef<HTMLDivElement, CustomMenuProps>(func)}/>{comboboxLabel && (- <label className="text-text-secondary peer-[:not(:placeholder-shown)]:bg-surface-menu pointer-events-none absolute top-2.5 left-2.5 text-sm transition-all duration-200 peer-[:not(:placeholder-shown)]:-top-1.5 peer-[:not(:placeholder-shown)]:left-1.5 peer-[:not(:placeholder-shown)]:text-xs sm:top-1.5">+ <label className="text-text-secondary peer-[:not(:placeholder-shown)]:bg-surface-menu pointer-events-none absolute inset-s-2.5 top-2.5 text-sm transition-all duration-200 peer-[:not(:placeholder-shown)]:inset-s-1.5 peer-[:not(:placeholder-shown)]:-top-1.5 peer-[:not(:placeholder-shown)]:text-xs sm:top-1.5">{comboboxLabel}</label>)}@@ -160,7 +164,7 @@ export const CustomMenuItem = React.forwardRef<HTMLDivElement, CustomMenuItemPro* bg-presentation, which resolves to the same value as* surface-secondary in dark and within 3/255 of it in light, so an* active item styled that way cannot render against its own popover. */- 'relative flex w-full min-w-0 cursor-default scroll-m-1 scroll-mt-[calc(var(--combobox-height,0px)+var(--label-height,0.25rem))] items-center gap-2 rounded-lg px-2 py-1 outline-hidden! hover:bg-surface-hover aria-disabled:opacity-25 aria-selected:bg-surface-hover data-[active-item]:bg-surface-hover data-[active-item]:text-text-primary sm:text-sm before:absolute before:bottom-1 before:left-0 before:top-1 before:w-0.5 before:rounded-full before:bg-transparent data-[active-item]:before:bg-text-primary',+ 'relative flex w-full min-w-0 cursor-default scroll-m-1 scroll-mt-[calc(var(--combobox-height,0px)+var(--label-height,0.25rem))] items-center gap-2 rounded-lg px-2 py-1 outline-hidden! hover:bg-surface-hover aria-disabled:opacity-25 aria-selected:bg-surface-hover data-[active-item]:bg-surface-hover data-[active-item]:text-text-primary sm:text-sm before:absolute before:bottom-1 before:inset-s-0 before:top-1 before:w-0.5 before:rounded-full before:bg-transparent data-[active-item]:before:bg-text-primary',props.className,),};diff --git a/client/src/components/Chat/Menus/OpenSidebar.tsx b/client/src/components/Chat/Menus/OpenSidebar.tsxindex dfa311d551..2d527d3cb1 100644--- a/client/src/components/Chat/Menus/OpenSidebar.tsx+++ b/client/src/components/Chat/Menus/OpenSidebar.tsx@@ -52,7 +52,7 @@ export default function OpenSidebar({className={className}onClick={handleClick}>- <Sidebar className="icon-md" aria-hidden="true" />+ <Sidebar className="icon-md rtl:-scale-x-100" aria-hidden="true" /></Button>}/>diff --git a/client/src/components/Conversations/ChatFilterMenu.tsx b/client/src/components/Conversations/ChatFilterMenu.tsxindex 0bffc27255..6f53cbb194 100644--- a/client/src/components/Conversations/ChatFilterMenu.tsx+++ b/client/src/components/Conversations/ChatFilterMenu.tsx@@ -53,6 +53,7 @@ import {updatedRangeAtom,} from './facets';import { useGetConversationTags, useGetEndpointsQuery, useGetStartupConfig } from '~/data-provider';+import useDirection, { inlineSide } from '~/hooks/Nav/useDirection';import MinimalIcon from '~/components/Endpoints/MinimalIcon';import { useHasAccess, useLocalize } from '~/hooks';import { cn } from '~/utils';@@ -68,9 +69,9 @@ const groupLabelClassName = 'px-2 pb-1 pt-1.5 text-xs font-medium text-text-seco/** Keeps every row's label on the same x, checked or not. */const CheckSlot = ({ checked }: { checked: boolean }) =>checked ? (- <Check className="text-text-primary ml-auto size-4 shrink-0" aria-hidden="true" />+ <Check className="text-text-primary ms-auto size-4 shrink-0" aria-hidden="true" />) : (- <span className="ml-auto size-4 shrink-0" aria-hidden="true" />+ <span className="ms-auto size-4 shrink-0" aria-hidden="true" />);type ChoiceProps = {@@ -151,9 +152,10 @@ const PropertyRow = ({children,}: PropertyRowProps) => {const zIndex = usePopoverZIndex();+ const submenuSide = inlineSide(useDirection(), 'end');return (- <Ariakit.MenuProvider placement="right-start" focusLoop={true}>+ <Ariakit.MenuProvider placement={`${submenuSide}-start`} focusLoop={true}><Ariakit.MenuButtonrender={<Ariakit.MenuItem />}data-testid={testId}@@ -163,10 +165,13 @@ const PropertyRow = ({{icon}</span><span className="shrink-0">{label}</span>- <span className="text-text-secondary ml-auto flex min-w-0 items-center gap-1.5 pl-4">+ <span className="text-text-secondary ms-auto flex min-w-0 items-center gap-1.5 ps-4">{valueIcon}<span className="truncate">{value}</span>- <ChevronRight className="text-text-tertiary size-4 shrink-0" aria-hidden="true" />+ <ChevronRight+ className="text-text-tertiary size-4 shrink-0 rtl:-scale-x-100"+ aria-hidden="true"+ /></span></Ariakit.MenuButton><Ariakit.Menu@@ -250,7 +255,7 @@ const BookmarkChoices = memo(() => {)}</span><span className="truncate">{bookmark.tag}</span>- <span className="text-text-tertiary ml-auto shrink-0 text-xs tabular-nums">+ <span className="text-text-tertiary ms-auto shrink-0 text-xs tabular-nums">{bookmark.count}</span></Ariakit.MenuItem>@@ -869,7 +874,7 @@ const ChatFilterMenu = () => {<ListFilter aria-hidden="true" className="size-4" />{totalCount > 0 && (<span- className="bg-text-primary absolute top-0.5 right-0.5 size-1.5 rounded-full"+ className="bg-text-primary absolute inset-e-0.5 top-0.5 size-1.5 rounded-full"aria-hidden="true"/>)}diff --git a/client/src/components/Nav/AccountSettings.tsx b/client/src/components/Nav/AccountSettings.tsxindex f08d695714..24d32e5da1 100644--- a/client/src/components/Nav/AccountSettings.tsx+++ b/client/src/components/Nav/AccountSettings.tsx@@ -16,6 +16,7 @@ import {} from 'lucide-react';import { ArchivedChatsModal } from '~/components/Nav/SettingsTabs/General/ArchivedChatsModal';import { filesDialogTriggerAtom, showFilesDialogAtom } from '~/store/filesDialog';+import useDirection, { inlineSide } from '~/hooks/Nav/useDirection';import { useGetStartupConfig } from '~/data-provider';import { useAuthContext } from '~/hooks/AuthContext';import { settingsOpenAtom } from './Settings';@@ -39,9 +40,10 @@ function HelpSubmenu({const hasTos = !!termsOfServiceURL;const hasPrivacy = !!privacyPolicyURL;const showLegalDivider = (hasHelpFaq || true) && (hasTos || hasPrivacy);+ const submenuSide = inlineSide(useDirection(), 'end');return (- <Menu.MenuProvider placement="right-start">+ <Menu.MenuProvider placement={`${submenuSide}-start`}><Menu.MenuItemhideOnClick={false}render={@@ -49,8 +51,8 @@ function HelpSubmenu({}><CircleHelp className="icon-md" aria-hidden="true" />- <span className="flex-1 text-left">{localize('com_nav_help')}</span>- <ChevronRight className="text-text-secondary h-4 w-4" aria-hidden="true" />+ <span className="flex-1 text-start">{localize('com_nav_help')}</span>+ <ChevronRight className="text-text-secondary h-4 w-4 rtl:-scale-x-100" aria-hidden="true" /></Menu.MenuItem><Menu.Menuportal@@ -104,9 +106,11 @@ function AccountSettings({ collapsed = false }: { collapsed?: boolean }) {const setShowShortcutsDialog = useSetRecoilState(store.showShortcutsDialog);const [showArchived, setShowArchived] = useState(false);const accountSettingsButtonRef = useRef<HTMLButtonElement>(null);+ /** The collapsed rail opens the menu beside it, toward the content. */+ const railSide = inlineSide(useDirection(), 'end');return (- <Menu.MenuProvider placement={collapsed ? 'right-end' : undefined}>+ <Menu.MenuProvider placement={collapsed ? `${railSide}-end` : undefined}><Menu.MenuButtonref={accountSettingsButtonRef}aria-label={localize('com_nav_account_settings')}@@ -123,10 +127,7 @@ function AccountSettings({ collapsed = false }: { collapsed?: boolean }) {</div></div>{!collapsed && (- <div- className="text-text-primary mt-2 grow overflow-hidden text-left text-ellipsis whitespace-nowrap"- style={{ marginTop: '0', marginLeft: '0' }}- >+ <div className="text-text-primary grow overflow-hidden text-start text-ellipsis whitespace-nowrap">{user?.name ?? user?.username ?? localize('com_nav_user')}</div>)}@@ -135,11 +136,13 @@ function AccountSettings({ collapsed = false }: { collapsed?: boolean }) {portalclassName="popover-ui z-[125] w-[min(19.0625rem,90vw)] md:w-[min(15.25rem,90vw)]"style={{- transformOrigin: collapsed ? 'left bottom' : 'bottom',- translate: collapsed ? '4px 0' : '0 -4px',+ transformOrigin: collapsed+ ? `${railSide === 'right' ? 'left' : 'right'} bottom`+ : 'bottom',+ translate: collapsed ? `${railSide === 'right' ? 4 : -4}px 0` : '0 -4px',}}>- <div className="text-text-secondary mr-2 ml-3 py-2 text-sm" role="note">+ <div className="text-text-secondary ms-3 me-2 py-2 text-sm" role="note">{user?.email ?? localize('com_nav_user')}</div><DropdownMenuSeparator />diff --git a/client/src/components/SidePanel/Agents/Version/VersionItem.tsx b/client/src/components/SidePanel/Agents/Version/VersionItem.tsxindex b5b125db22..6954827b0a 100644--- a/client/src/components/SidePanel/Agents/Version/VersionItem.tsx+++ b/client/src/components/SidePanel/Agents/Version/VersionItem.tsx@@ -10,6 +10,7 @@ import {TooltipAnchor,} from '@librechat/client';import type { VersionRecord } from './types';+import useDirection, { inlineSide } from '~/hooks/Nav/useDirection';import { useLocalize, useClockFormat } from '~/hooks';import { cn } from '~/utils';@@ -45,6 +46,7 @@ export default function VersionItem({onRestore,}: VersionItemProps) {const localize = useLocalize();+ const direction = useDirection();const hour12 = useClockFormat();const [open, setOpen] = useState(false);@@ -119,7 +121,7 @@ export default function VersionItem({{/* Card */}<divclassName={cn(- 'group relative mb-2 ml-2 flex flex-1 flex-col rounded-xl border p-3 transition-colors',+ 'group relative ms-2 mb-2 flex flex-1 flex-col rounded-xl border p-3 transition-colors',isActive? 'border-status-success-border bg-status-success-subtle': 'border-border-light hover:border-border-medium hover:bg-surface-secondary bg-transparent',@@ -162,7 +164,7 @@ export default function VersionItem({<OGDialogTrigger asChild><TooltipAnchordescription={localize('com_ui_agent_version_restore')}- side="left"+ side={inlineSide(direction, 'start')}render={<Buttonvariant="quiet"@@ -180,7 +182,7 @@ export default function VersionItem({className="max-w-[28.125rem]"main={<div className="flex w-full flex-col gap-3 text-sm">- <Label className="text-left font-medium">+ <Label className="text-start font-medium">{localize('com_ui_agent_version_restore_description')}</Label><div className="border-border-light bg-surface-secondary rounded-lg border px-3 py-2">diff --git a/client/src/components/SidePanel/ArtifactsPanel.tsx b/client/src/components/SidePanel/ArtifactsPanel.tsxindex 82f473ca5a..34a62dc63d 100644--- a/client/src/components/SidePanel/ArtifactsPanel.tsx+++ b/client/src/components/SidePanel/ArtifactsPanel.tsx@@ -1,12 +1,15 @@import { useEffect, memo } from 'react';import { usePanelRef } from 'react-resizable-panels';import { ResizableHandleAlt, ResizablePanel } from '@librechat/client';+import useDirection from '~/hooks/Nav/useDirection';interface ArtifactsPanelProps {panel: React.ReactNode | null;minSizeMain: string;shouldRender: boolean;onRenderChange: (shouldRender: boolean) => void;+ /** Rendered before the messages panel (RTL), so the handle follows the panel. */+ reversed?: boolean;}const ArtifactsPanel = memo(function ArtifactsPanel({@@ -14,8 +17,10 @@ const ArtifactsPanel = memo(function ArtifactsPanel({minSizeMain,shouldRender,onRenderChange,+ reversed = false,}: ArtifactsPanelProps) {const artifactsPanelRef = usePanelRef();+ const direction = useDirection();useEffect(() => {if (panel != null) {@@ -34,9 +39,11 @@ const ArtifactsPanel = memo(function ArtifactsPanel({return null;}+ const handle = panel != null && <ResizableHandleAlt withHandle className="text-text-primary" />;+return (<>- {panel != null && <ResizableHandleAlt withHandle className="text-text-primary" />}+ {!reversed && handle}<ResizablePaneldefaultSize="50"maxSize="70"@@ -45,9 +52,11 @@ const ArtifactsPanel = memo(function ArtifactsPanel({minSize={minSizeMain}panelRef={artifactsPanelRef}id="artifacts-panel"+ dir={direction}><div className="h-full min-w-[min(25rem,100%)] overflow-hidden">{panel}</div></ResizablePanel>+ {reversed && handle}</>);});diff --git a/client/src/components/SidePanel/Parameters/OptionHover.tsx b/client/src/components/SidePanel/Parameters/OptionHover.tsxindex d995ce6c88..62a482752c 100644--- a/client/src/components/SidePanel/Parameters/OptionHover.tsx+++ b/client/src/components/SidePanel/Parameters/OptionHover.tsx@@ -1,8 +1,17 @@import React from 'react';import { HoverCardPortal, HoverCardContent } from '@librechat/client';import { TranslationKeys, useLocalize } from '~/hooks';+import useDirection from '~/hooks/Nav/useDirection';import { ESide } from '~/common';+/** Callers name the side for an LTR layout; RTL mirrors the horizontal ones. */+const mirrorSide = (side: ESide): ESide => {+ if (side === ESide.Left) {+ return ESide.Right;+ }+ return side === ESide.Right ? ESide.Left : side;+};+type TOptionHoverProps = {description: string;langCode?: boolean;@@ -21,13 +30,18 @@ function OptionHover({className,}: TOptionHoverProps) {const localize = useLocalize();+ const direction = useDirection();if (disabled) {return null;}const text = langCode ? localize(description as TranslationKeys) : description;return (<HoverCardPortal>- <HoverCardContent side={side} className={`z-[999] w-80 ${className}`} sideOffset={sideOffset}>+ <HoverCardContent+ side={direction === 'rtl' ? mirrorSide(side) : side}+ className={`z-[999] w-80 ${className}`}+ sideOffset={sideOffset}+ ><div className="space-y-2"><p className="text-text-secondary text-sm whitespace-pre-wrap">{text}</p></div>diff --git a/client/src/components/SidePanel/SidePanelGroup.tsx b/client/src/components/SidePanel/SidePanelGroup.tsxindex 55cb3448ba..41a019a02c 100644--- a/client/src/components/SidePanel/SidePanelGroup.tsx+++ b/client/src/components/SidePanel/SidePanelGroup.tsx@@ -3,11 +3,13 @@ import { useDefaultLayout } from 'react-resizable-panels';import { ResizablePanel, ResizablePanelGroup } from '@librechat/client';import { ARTIFACTS_SHEET_MAX_WIDTH } from '~/utils/breakpoints';import useScaledMaxWidth from '~/hooks/useScaledMaxWidth';+import useDirection from '~/hooks/Nav/useDirection';import ArtifactsPanel from './ArtifactsPanel';const PANEL_IDS_SINGLE = ['messages-view'];/** Keep the persisted id stable so existing artifact panel widths carry over. */const PANEL_IDS_SPLIT = ['messages-view', 'artifacts-panel'];+const PANEL_IDS_SPLIT_RTL = ['artifacts-panel', 'messages-view'];interface SidePanelProps {panel?: React.ReactNode;@@ -17,15 +19,48 @@ interface SidePanelProps {const SidePanelGroup = memo(({ panel, children }: SidePanelProps) => {const [shouldRenderPanel, setShouldRenderPanel] = useState(panel != null);const isSmallScreen = useScaledMaxWidth(ARTIFACTS_SHEET_MAX_WIDTH);+ /**+ * react-resizable-panels reads drag deltas and arrow keys physically (a+ * rightward drag always grows the first panel), so under RTL the group stays+ * LTR and the panels are rendered in reverse: the artifacts panel lands on+ * the inline-end side and every drag still moves the separator with the+ * pointer. Each panel restores the document direction for its content. The+ * library keys the saved layout by panel order, so RTL keeps its own widths.+ */+ const direction = useDirection();+ const reversed = direction === 'rtl';+ const splitIds = reversed ? PANEL_IDS_SPLIT_RTL : PANEL_IDS_SPLIT;const { defaultLayout, onLayoutChanged } = useDefaultLayout({id: 'side-panel-layout',- panelIds: panel != null ? PANEL_IDS_SPLIT : PANEL_IDS_SINGLE,+ panelIds: panel != null ? splitIds : PANEL_IDS_SINGLE,storage: localStorage,});const minSizeMain = panel != null ? '15' : '30';+ const panels = [+ <ResizablePanel+ key="messages"+ defaultSize="50"+ minSize={minSizeMain}+ id="messages-view"+ dir={direction}+ >+ {children}+ </ResizablePanel>,+ !isSmallScreen && (+ <ArtifactsPanel+ key="artifacts"+ panel={panel}+ minSizeMain={minSizeMain}+ shouldRender={shouldRenderPanel}+ onRenderChange={setShouldRenderPanel}+ reversed={reversed}+ />+ ),+ ];+return (<>{/* The surface behind the panels is this group's host, not the group@@ -36,19 +71,9 @@ const SidePanelGroup = memo(({ panel, children }: SidePanelProps) => {orientation="horizontal"defaultLayout={defaultLayout}onLayoutChanged={onLayoutChanged}+ dir="ltr">- <ResizablePanel defaultSize="50" minSize={minSizeMain} id="messages-view">- {children}- </ResizablePanel>-- {!isSmallScreen && (- <ArtifactsPanel- panel={panel}- minSizeMain={minSizeMain}- shouldRender={shouldRenderPanel}- onRenderChange={setShouldRenderPanel}- />- )}+ {reversed ? panels.reverse() : panels}</ResizablePanelGroup></div>{panel != null && isSmallScreen && <div className="fixed inset-0 z-[100]">{panel}</div>}diff --git a/client/src/components/UnifiedSidebar/ExpandedPanel.tsx b/client/src/components/UnifiedSidebar/ExpandedPanel.tsxindex e7cc891598..bf621c5ddd 100644--- a/client/src/components/UnifiedSidebar/ExpandedPanel.tsx+++ b/client/src/components/UnifiedSidebar/ExpandedPanel.tsx@@ -7,6 +7,7 @@ import { useShortcutAriaKey, useShortcutHint } from '~/hooks/useKeyboardShortcutimport { useActivePanel, resolveActivePanel, DEFAULT_PANEL } from '~/Providers';import AgentMarketplaceButton from '~/components/Nav/AgentMarketplaceButton';import { CLOSE_SIDEBAR_ID } from '~/components/Chat/Menus/OpenSidebar';+import useDirection, { inlineSide } from '~/hooks/Nav/useDirection';import useNewChat from '~/hooks/Conversations/useNewChat';import { lazyWithRecovery } from '~/lib/assets/lazy';import { useLocalize } from '~/hooks';@@ -21,6 +22,7 @@ const NewChatButton = memo(function NewChatButton({switchToHistory: boolean;}) {const localize = useLocalize();+ const tooltipSide = inlineSide(useDirection(), 'end');const tooltipDescription = useShortcutHint('newChat', localize('com_ui_new_chat'));const ariaKey = useShortcutAriaKey('newChat');@@ -34,7 +36,7 @@ const NewChatButton = memo(function NewChatButton({return (<TooltipAnchor- side="right"+ side={tooltipSide}description={tooltipDescription}render={<a@@ -72,6 +74,7 @@ const NavIconButton = memo(function NavIconButton({onLeaveInsights?: () => void;}) {const localize = useLocalize();+ const tooltipSide = inlineSide(useDirection(), 'end');const handleClick = useCallback((e: React.MouseEvent<HTMLButtonElement>) => {@@ -99,7 +102,7 @@ const NavIconButton = memo(function NavIconButton({return (<TooltipAnchordescription={localize(link.title)}- side="right"+ side={tooltipSide}render={<Buttonsize="icon"@@ -136,6 +139,7 @@ function ExpandedPanel({switchToHistory: boolean;}) {const localize = useLocalize();+ const tooltipSide = inlineSide(useDirection(), 'end');const location = useLocation();const { active, setActive } = useActivePanel();const effectiveActive = resolveActivePanel(active, links);@@ -147,9 +151,9 @@ function ExpandedPanel({const toggleSidebarAriaKey = useShortcutAriaKey('toggleSidebar');return (- <div className="border-border-inset bg-surface-sidebar flex h-full shrink-0 flex-col gap-2 border-r px-2 py-2">+ <div className="border-border-inset bg-surface-sidebar flex h-full shrink-0 flex-col gap-2 border-e px-2 py-2"><TooltipAnchor- side="right"+ side={tooltipSide}description={toggleSidebarHint}render={<Button@@ -163,7 +167,7 @@ function ExpandedPanel({className="h-9 w-9"onClick={toggleClick}>- <Sidebar aria-hidden="true" className="text-text-primary h-5 w-5" />+ <Sidebar aria-hidden="true" className="text-text-primary h-5 w-5 rtl:-scale-x-100" /></Button>}/>diff --git a/client/src/components/UnifiedSidebar/Sidebar.tsx b/client/src/components/UnifiedSidebar/Sidebar.tsxindex ed8253acdc..d30a96fef7 100644--- a/client/src/components/UnifiedSidebar/Sidebar.tsx+++ b/client/src/components/UnifiedSidebar/Sidebar.tsx@@ -1,5 +1,6 @@import { memo } from 'react';import type { NavLink } from '~/common';+import { isRtlElement } from '~/hooks/Nav/useDirection';import SidePanelNav from '~/components/SidePanel/Nav';import ExpandedPanel from './ExpandedPanel';import { cn } from '~/utils';@@ -26,7 +27,7 @@ function Sidebar({onExpand: () => void;onLeaveInsights: () => void;switchToHistory: boolean;- onResizeStart: (e: React.MouseEvent) => void;+ onResizeStart: (e: React.MouseEvent<HTMLElement>) => void;onResizeKeyboard: (direction: 'shrink' | 'grow') => void;}) {return (@@ -42,11 +43,11 @@ function Sidebar({/><navclassName={cn(- /** The resize separator to the right is transparent until hovered, so+ /** The resize separator at the inline end is transparent until hovered, so* the edge is drawn here. The panel and the content beside it now sit* on the same surface, so the fill no longer separates them on its* own and the boundary has to be a line in every theme. */- 'border-border-light bg-surface-sidebar min-h-0 flex-1 overflow-hidden border-r',+ 'border-border-light bg-surface-sidebar min-h-0 flex-1 overflow-hidden border-e',expanded ? 'opacity-100' : 'pointer-events-none opacity-0',)}style={{ transition: expanded ? 'opacity 200ms ease 80ms' : 'opacity 150ms ease' }}@@ -64,17 +65,19 @@ function Sidebar({aria-valuemax={Math.round(maxWidth)}tabIndex={expanded ? 0 : -1}className={cn(- 'hover:bg-border-medium active:bg-border-heavy absolute top-0 right-0 z-10 h-full w-1 cursor-col-resize transition-colors',+ 'hover:bg-border-medium active:bg-border-heavy absolute inset-e-0 top-0 z-10 h-full w-1 cursor-col-resize transition-colors',expanded ? 'opacity-100' : 'pointer-events-none opacity-0',)}style={{ transition: expanded ? 'opacity 200ms ease 80ms' : 'opacity 150ms ease' }}onMouseDown={onResizeStart}onKeyDown={(e) => {- if (e.key === 'ArrowLeft') {- onResizeKeyboard('shrink');- } else if (e.key === 'ArrowRight') {- onResizeKeyboard('grow');+ if (e.key !== 'ArrowLeft' && e.key !== 'ArrowRight') {+ return;}+ /** The handle sits on the inline-end edge, so the arrow pointing away from the+ * sidebar grows it: right in LTR, left in RTL. */+ const towardEnd = (e.key === 'ArrowRight') !== isRtlElement(e.currentTarget);+ onResizeKeyboard(towardEnd ? 'grow' : 'shrink');}}/></>diff --git a/client/src/components/UnifiedSidebar/UnifiedSidebar.tsx b/client/src/components/UnifiedSidebar/UnifiedSidebar.tsxindex 25cdd162a8..bf71938691 100644--- a/client/src/components/UnifiedSidebar/UnifiedSidebar.tsx+++ b/client/src/components/UnifiedSidebar/UnifiedSidebar.tsx@@ -26,6 +26,7 @@ import useSidebarToggle from '~/hooks/Nav/useSidebarToggle';import useSidebarState from '~/hooks/Nav/useSidebarState';import { useChatHelpers, useLocalize } from '~/hooks';import SidePanelNav from '~/components/SidePanel/Nav';+import { createResizeMeasure } from './resize';import Sidebar from './Sidebar';import { cn } from '~/utils';@@ -114,45 +115,49 @@ function UnifiedSidebar({handleExpand();}, [handleExpand, handleLeaveInsights, isInsightsRoute]);- const handleResizeStart = useCallback(() => {- setIsResizing(true);- document.body.style.userSelect = 'none';- const maxWidth = (window.innerWidth * 0.4) / remScale;- /** The scaled minimum can exceed the viewport cap, so it yields to the cap. */- const minWidth = Math.min(EXPANDED_MIN, maxWidth);- let rafId: number | null = null;+ const handleResizeStart = useCallback(+ (event: React.MouseEvent<HTMLElement>) => {+ setIsResizing(true);+ document.body.style.userSelect = 'none';+ const maxWidth = (window.innerWidth * 0.4) / remScale;+ /** The scaled minimum can exceed the viewport cap, so it yields to the cap. */+ const minWidth = Math.min(EXPANDED_MIN, maxWidth);+ const measure = createResizeMeasure(event.currentTarget);+ let rafId: number | null = null;- const move = (e: MouseEvent) => {- if (rafId != null) {- return;- }- rafId = requestAnimationFrame(() => {- rafId = null;- const next = Math.max(minWidth, Math.min(e.clientX / remScale, maxWidth));- setSidebarWidth(next);- });- };+ const move = (e: MouseEvent) => {+ if (rafId != null) {+ return;+ }+ rafId = requestAnimationFrame(() => {+ rafId = null;+ const next = Math.max(minWidth, Math.min(measure(e.clientX) / remScale, maxWidth));+ setSidebarWidth(next);+ });+ };- const up = () => {- if (rafId != null) {- cancelAnimationFrame(rafId);- rafId = null;- }- document.body.style.userSelect = '';- setIsResizing(false);- resizeHandlers.current = null;- setSidebarWidth((w) => {- localStorage.setItem('side:width', String(Math.round(w)));- return w;- });- document.removeEventListener('mousemove', move);- document.removeEventListener('mouseup', up);- };+ const up = () => {+ if (rafId != null) {+ cancelAnimationFrame(rafId);+ rafId = null;+ }+ document.body.style.userSelect = '';+ setIsResizing(false);+ resizeHandlers.current = null;+ setSidebarWidth((w) => {+ localStorage.setItem('side:width', String(Math.round(w)));+ return w;+ });+ document.removeEventListener('mousemove', move);+ document.removeEventListener('mouseup', up);+ };- resizeHandlers.current = { move, up };- document.addEventListener('mousemove', move);- document.addEventListener('mouseup', up);- }, [remScale]);+ resizeHandlers.current = { move, up };+ document.addEventListener('mousemove', move);+ document.addEventListener('mouseup', up);+ },+ [remScale],+ );const handleResizeKeyboard = useCallback((direction: 'shrink' | 'grow') => {@@ -218,13 +223,13 @@ function UnifiedSidebar({* a site banner above that container stays above the drawer too* instead of covering its header strip, as it already does for the* scrim and the pane. */- 'bg-surface-sidebar text-text-primary absolute inset-y-0 left-0 flex touch-pan-y touch-pinch-zoom flex-col',+ 'bg-surface-sidebar text-text-primary absolute inset-y-0 inset-s-0 flex touch-pan-y touch-pinch-zoom flex-col',/** In dark mode the scrim and the drawer are both near-black, and no* scrim opacity separates them by 3:1, so the drawer draws its own* edge. Light palettes get that separation from the scrim, so the* `drawer-edge` role defaults to the drawer's own fill there. */- 'border-drawer-edge border-r',- expanded ? 'translate-x-0' : '-translate-x-full',+ 'border-drawer-edge border-e',+ expanded ? 'translate-x-0' : '-translate-x-full rtl:translate-x-full',)}style={{width: MOBILE_DRAWER_WIDTH,diff --git a/client/src/components/UnifiedSidebar/__tests__/resize.spec.tsx b/client/src/components/UnifiedSidebar/__tests__/resize.spec.tsxnew file mode 100644index 0000000000..8ad2921a1b--- /dev/null+++ b/client/src/components/UnifiedSidebar/__tests__/resize.spec.tsx@@ -0,0 +1,84 @@+import React from 'react';+import { render, fireEvent, screen } from '@testing-library/react';+import { createResizeMeasure } from '../resize';+import Sidebar from '../Sidebar';++jest.mock('~/components/SidePanel/Nav', () => ({+ __esModule: true,+ default: () => null,+}));++jest.mock('../ExpandedPanel', () => ({+ __esModule: true,+ default: () => null,+}));++const renderSidebar = (direction: 'ltr' | 'rtl') => {+ const onResizeKeyboard = jest.fn();+ render(+ <div style={{ direction }}>+ <Sidebar+ links={[]}+ expanded+ width={400}+ minWidth={360}+ maxWidth={600}+ onCollapse={jest.fn()}+ onExpand={jest.fn()}+ onLeaveInsights={jest.fn()}+ switchToHistory={false}+ onResizeStart={jest.fn()}+ onResizeKeyboard={onResizeKeyboard}+ />+ </div>,+ );+ const handle = screen.getByRole('separator');+ handle.style.direction = direction;+ return { handle, onResizeKeyboard };+};++describe('Sidebar resize handle keyboard', () => {+ it('grows on ArrowRight and shrinks on ArrowLeft in LTR', () => {+ const { handle, onResizeKeyboard } = renderSidebar('ltr');+ fireEvent.keyDown(handle, { key: 'ArrowRight' });+ fireEvent.keyDown(handle, { key: 'ArrowLeft' });+ expect(onResizeKeyboard.mock.calls).toEqual([['grow'], ['shrink']]);+ });++ it('grows on ArrowLeft and shrinks on ArrowRight in RTL', () => {+ const { handle, onResizeKeyboard } = renderSidebar('rtl');+ fireEvent.keyDown(handle, { key: 'ArrowLeft' });+ fireEvent.keyDown(handle, { key: 'ArrowRight' });+ expect(onResizeKeyboard.mock.calls).toEqual([['grow'], ['shrink']]);+ });++ it('ignores other keys', () => {+ const { handle, onResizeKeyboard } = renderSidebar('rtl');+ fireEvent.keyDown(handle, { key: 'ArrowUp' });+ expect(onResizeKeyboard).not.toHaveBeenCalled();+ });+});++describe('createResizeMeasure', () => {+ const mount = (direction: 'ltr' | 'rtl', left: number, right: number) => {+ const aside = document.createElement('aside');+ const handle = document.createElement('div');+ handle.style.direction = direction;+ aside.append(handle);+ jest+ .spyOn(aside, 'getBoundingClientRect')+ .mockReturnValue({ left, right, top: 0, bottom: 0, width: right - left } as DOMRect);+ return handle;+ };++ it('measures from the left edge in LTR', () => {+ const measure = createResizeMeasure(mount('ltr', 0, 400));+ expect(measure(450)).toBe(450);+ });++ it('measures from the right edge in RTL, so dragging left grows the sidebar', () => {+ const measure = createResizeMeasure(mount('rtl', 1040, 1440));+ expect(measure(990)).toBe(450);+ expect(measure(1100)).toBe(340);+ });+});diff --git a/client/src/components/UnifiedSidebar/constants.ts b/client/src/components/UnifiedSidebar/constants.tsindex d586f1ba4c..7948dd65d5 100644--- a/client/src/components/UnifiedSidebar/constants.ts+++ b/client/src/components/UnifiedSidebar/constants.ts@@ -18,7 +18,13 @@ export const MOBILE_DRAWER_WIDTH_VAR = '--mobile-drawer-width';export const MOBILE_DRAWER_FULL_WIDTH = '100%';export const MOBILE_DRAWER_STRIP_WIDTH = '80%';export const MOBILE_DRAWER_WIDTH = `var(${MOBILE_DRAWER_WIDTH_VAR}, ${MOBILE_DRAWER_FULL_WIDTH})`;-export const MOBILE_PANE_SHIFT = `translateX(${MOBILE_DRAWER_WIDTH})`;+/**+ * Which way the drawer opens: 1 when it sits on the left (LTR), -1 when it sits on+ * the right (RTL). Root sets it with an `rtl:` utility, so the pane's declarative+ * transform follows the document direction without React reading it.+ */+export const MOBILE_DRAWER_SIGN_VAR = '--mobile-drawer-sign';+export const MOBILE_PANE_SHIFT = `translateX(calc(var(${MOBILE_DRAWER_SIGN_VAR}, 1) * ${MOBILE_DRAWER_WIDTH}))`;export const TRANSITION_MS = 300;/*** Decelerating, but it settles rather than crawls. The previousdiff --git a/client/src/components/UnifiedSidebar/mobile/Header.tsx b/client/src/components/UnifiedSidebar/mobile/Header.tsxindex fb25648eb4..6f80f44903 100644--- a/client/src/components/UnifiedSidebar/mobile/Header.tsx+++ b/client/src/components/UnifiedSidebar/mobile/Header.tsx@@ -72,7 +72,7 @@ function Header({className="shrink-0"onClick={onClose}>- <Sidebar className="icon-md" aria-hidden="true" />+ <Sidebar className="icon-md rtl:-scale-x-100" aria-hidden="true" /></Button><Switcherlinks={links}diff --git a/client/src/components/UnifiedSidebar/mobile/Switcher.tsx b/client/src/components/UnifiedSidebar/mobile/Switcher.tsxindex 11dcd94616..62dd5562f8 100644--- a/client/src/components/UnifiedSidebar/mobile/Switcher.tsx+++ b/client/src/components/UnifiedSidebar/mobile/Switcher.tsx@@ -76,7 +76,7 @@ function Switcher({setIsOpen={setIsOpen}items={items}minWidth="15rem"- iconClassName="mr-2 size-5"+ iconClassName="me-2 size-5"trigger={<Ariakit.MenuButtondata-testid="panel-switcher-button"@@ -95,7 +95,7 @@ function Switcher({><activeLink.icon className="size-5 shrink-0" aria-hidden="true" />{/* Grows so the chevron settles on the trailing edge rather than trailing the label. */}- <span className="flex-1 truncate text-left text-sm font-medium">+ <span className="flex-1 truncate text-start text-sm font-medium">{localize(activeLink.title)}</span><ChevronDown className="text-text-secondary size-4 shrink-0" aria-hidden="true" />diff --git a/client/src/components/UnifiedSidebar/resize.ts b/client/src/components/UnifiedSidebar/resize.tsnew file mode 100644index 0000000000..b9e9eeffcb--- /dev/null+++ b/client/src/components/UnifiedSidebar/resize.ts@@ -0,0 +1,18 @@+import { isRtlElement } from '~/hooks/Nav/useDirection';++/**+ * Returns how wide a drag at `clientX` asks the sidebar to be: the distance from+ * the sidebar's inline-start edge to the pointer. That edge is the sidebar's left+ * in LTR and its right in RTL, where the handle sits on the left and dragging+ * left grows it. Measured once at drag start, from the handle's container.+ */+export function createResizeMeasure(handle: HTMLElement): (clientX: number) => number {+ const rtl = isRtlElement(handle);+ const bounds = handle.parentElement?.getBoundingClientRect();+ if (rtl) {+ const origin = bounds?.right ?? window.innerWidth;+ return (clientX) => origin - clientX;+ }+ const origin = bounds?.left ?? 0;+ return (clientX) => clientX - origin;+}diff --git a/client/src/hooks/Nav/__tests__/useDirection.spec.tsx b/client/src/hooks/Nav/__tests__/useDirection.spec.tsxnew file mode 100644index 0000000000..e914c7c2a3--- /dev/null+++ b/client/src/hooks/Nav/__tests__/useDirection.spec.tsx@@ -0,0 +1,44 @@+import { act, renderHook } from '@testing-library/react';+import useDirection, { inlineSide, isRtlElement } from '../useDirection';++afterEach(() => {+ document.documentElement.removeAttribute('dir');+});++describe('useDirection', () => {+ it('follows the dir attribute on the document element', async () => {+ const { result } = renderHook(() => useDirection());+ expect(result.current).toBe('ltr');++ await act(async () => {+ document.documentElement.dir = 'rtl';+ });+ expect(result.current).toBe('rtl');++ await act(async () => {+ document.documentElement.dir = 'ltr';+ });+ expect(result.current).toBe('ltr');+ });+});++describe('inlineSide', () => {+ it('maps logical edges to physical sides', () => {+ expect(inlineSide('ltr', 'end')).toBe('right');+ expect(inlineSide('ltr', 'start')).toBe('left');+ expect(inlineSide('rtl', 'end')).toBe('left');+ expect(inlineSide('rtl', 'start')).toBe('right');+ });+});++describe('isRtlElement', () => {+ it('reads the element, so an LTR island inside RTL stays LTR', () => {+ const island = document.createElement('div');+ island.style.direction = 'ltr';+ const rtl = document.createElement('div');+ rtl.style.direction = 'rtl';+ expect(isRtlElement(island)).toBe(false);+ expect(isRtlElement(rtl)).toBe(true);+ expect(isRtlElement(null)).toBe(false);+ });+});diff --git a/client/src/hooks/Nav/__tests__/useDrawerSwipe.spec.tsx b/client/src/hooks/Nav/__tests__/useDrawerSwipe.spec.tsxindex 009d079c41..ffdeafa106 100644--- a/client/src/hooks/Nav/__tests__/useDrawerSwipe.spec.tsx+++ b/client/src/hooks/Nav/__tests__/useDrawerSwipe.spec.tsx@@ -1177,3 +1177,150 @@ describe('findHorizontalScrollBlocker', () => {expect(findHorizontalScrollBlocker(child, boundary, 1)).toBeNull();});});++/** In RTL the drawer is anchored to the right edge, so "toward open" is a+ * leftward finger and every transform carries the opposite sign. */+describe('useDrawerSwipe: right-to-left layouts', () => {+ const setupRtl = (open: boolean, viewportWidth = DRAWER_WIDTH) => {+ const harness = setup(open, false, viewportWidth);+ harness.drawer.style.direction = 'rtl';+ return harness;+ };++ const rtlScroller = (scrollLeft: number) => {+ const el = document.createElement('div');+ el.style.overflowX = 'auto';+ el.style.direction = 'rtl';+ Object.defineProperty(el, 'scrollWidth', { value: 600, configurable: true });+ Object.defineProperty(el, 'clientWidth', { value: 300, configurable: true });+ el.scrollLeft = scrollLeft;+ return el;+ };++ it('opens on a leftward swipe and mirrors the drag transforms', () => {+ const harness = setupRtl(false);+ const events = harness.swipe(+ harness.pane,+ [+ { x: 355, y: 100, t: 0 },+ { x: 255, y: 104, t: 50 },+ { x: 155, y: 108, t: 100 },+ ],+ false,+ );++ expect(events[1].defaultPrevented).toBe(true);+ expect(harness.drawer.style.transform).toBe(`translate3d(${DRAWER_WIDTH - 200}px, 0, 0)`);+ expect(harness.pane.style.transform).toBe('translate3d(-200px, 0, 0)');++ harness.pane.dispatchEvent(touchEvent('touchend', [], 120));++ expect(harness.onOpenChange).toHaveBeenCalledWith(true);+ expect(harness.drawer.style.transform).toBe('translate3d(0, 0, 0)');+ expect(harness.pane.style.transform).toBe(MOBILE_PANE_SHIFT);+ harness.unmount();+ });++ it('ignores a rightward swipe while closed', () => {+ const harness = setupRtl(false);+ harness.swipe(harness.pane, [+ { x: 20, y: 100, t: 0 },+ { x: 220, y: 100, t: 50 },+ ]);++ expect(harness.onOpenChange).not.toHaveBeenCalled();+ expect(harness.drawer.style.transform).toBe('');+ harness.unmount();+ });++ it('reverts a slow swipe to the right-hand offscreen position', () => {+ const harness = setupRtl(false);+ harness.swipe(harness.pane, [+ { x: 355, y: 100, t: 0 },+ { x: 315, y: 100, t: 200 },+ { x: 295, y: 100, t: 400 },+ ]);++ expect(harness.onOpenChange).not.toHaveBeenCalled();+ expect(harness.drawer.style.transform).toBe('translate3d(100%, 0, 0)');+ expect(harness.pane.style.transform).toBe('translate3d(0, 0, 0)');+ harness.unmount();+ });++ it('commits a fast leftward flick short of the distance threshold', () => {+ const harness = setupRtl(false);+ harness.swipe(harness.pane, [+ { x: 355, y: 100, t: 0 },+ { x: 325, y: 100, t: 20 },+ { x: 295, y: 100, t: 40 },+ ]);++ expect(harness.onOpenChange).toHaveBeenCalledWith(true);+ harness.unmount();+ });++ it('closes on a committed rightward swipe and ignores a leftward one', () => {+ const ignored = setupRtl(true);+ ignored.swipe(ignored.drawer, [+ { x: 350, y: 100, t: 0 },+ { x: 150, y: 100, t: 50 },+ ]);+ expect(ignored.onOpenChange).not.toHaveBeenCalled();+ ignored.unmount();++ const harness = setupRtl(true);+ harness.swipe(harness.drawer, [+ { x: 50, y: 100, t: 0 },+ { x: 150, y: 100, t: 50 },+ { x: 250, y: 100, t: 100 },+ ]);++ expect(harness.onOpenChange).toHaveBeenCalledWith(false);+ expect(harness.drawer.style.transform).toBe('translate3d(100%, 0, 0)');+ expect(harness.pane.style.transform).toBe('translate3d(0, 0, 0)');+ harness.unmount();+ });++ it('defers to an RTL scroller that can still pan toward the drawer', () => {+ const harness = setupRtl(false);+ const scroller = rtlScroller(-120);+ harness.pane.append(scroller);++ harness.swipe(harness.pane, [+ { x: 355, y: 100, t: 0, target: scroller },+ { x: 155, y: 100, t: 50, target: scroller },+ ]);++ expect(harness.onOpenChange).not.toHaveBeenCalled();+ harness.unmount();+ });++ it('claims the drag when that RTL scroller is parked at its start', () => {+ const harness = setupRtl(false);+ const scroller = rtlScroller(0);+ harness.pane.append(scroller);++ harness.swipe(harness.pane, [+ { x: 355, y: 100, t: 0, target: scroller },+ { x: 155, y: 100, t: 50, target: scroller },+ ]);++ expect(harness.onOpenChange).toHaveBeenCalledWith(true);+ harness.unmount();+ });++ it('slides a button close off the right edge', () => {+ jest.useFakeTimers();+ const harness = setupRtl(true, Math.round(DRAWER_WIDTH / 0.8));++ kickDrawerAnimation(false, jest.fn());++ expect(harness.drawer.style.transform).toBe('translate3d(100%, 0, 0)');+ expect(harness.pane.style.transform).toBe('translate3d(0, 0, 0)');++ harness.rerender({ open: false, enabled: true });+ jest.runAllTimers();+ jest.useRealTimers();+ harness.unmount();+ });+});diff --git a/client/src/hooks/Nav/useDirection.ts b/client/src/hooks/Nav/useDirection.tsnew file mode 100644index 0000000000..457bde5674--- /dev/null+++ b/client/src/hooks/Nav/useDirection.ts@@ -0,0 +1,28 @@+import { useSyncExternalStore } from 'react';++export type Direction = 'ltr' | 'rtl';+export type PhysicalSide = 'left' | 'right';++const readDirection = (): Direction =>+ typeof document !== 'undefined' && document.documentElement.dir === 'rtl' ? 'rtl' : 'ltr';++const subscribe = (onChange: () => void) => {+ const observer = new MutationObserver(onChange);+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['dir'] });+ return () => observer.disconnect();+};++/** Whether an element lays out right to left. Reads the element, not the document, so an+ * island forced to `dir="ltr"` keeps its own mapping. */+export const isRtlElement = (element: Element | null): boolean =>+ element != null && window.getComputedStyle(element).direction === 'rtl';++/** The physical side that a logical inline edge lands on. Floating UI and Radix sides are+ * physical, so placements that mean "toward the content" must be resolved per direction. */+export const inlineSide = (direction: Direction, edge: 'start' | 'end'): PhysicalSide =>+ (edge === 'end') === (direction === 'rtl') ? 'left' : 'right';++/** The document's writing direction, kept in sync with the `dir` that i18n writes on `<html>`. */+export default function useDirection(): Direction {+ return useSyncExternalStore(subscribe, readDirection, () => 'ltr');+}diff --git a/client/src/hooks/Nav/useDrawerSwipe.ts b/client/src/hooks/Nav/useDrawerSwipe.tsindex 48dfa4faf5..8d80a515f6 100644--- a/client/src/hooks/Nav/useDrawerSwipe.ts+++ b/client/src/hooks/Nav/useDrawerSwipe.ts@@ -34,6 +34,19 @@ const SETTLE_BUFFER_MS = 80;const drawerCoversPane = (drawer: HTMLElement): boolean =>(drawer.clientWidth || window.innerWidth) >= window.innerWidth;+/**+ * Which physical way "open" points: 1 when the drawer sits on the left (LTR),+ * -1 when it sits on the right (RTL). Read from the drawer itself, the element+ * anchored to the inline-start edge, and multiplied into every horizontal+ * distance, velocity and transform so the gesture logic below reasons in+ * logical terms (positive = toward open).+ */+const drawerSign = (drawer: HTMLElement): 1 | -1 =>+ window.getComputedStyle(drawer).direction === 'rtl' ? -1 : 1;++/** Fully offscreen past the drawer's inline-start edge. */+const closedDrawerTransform = (sign: 1 | -1) => `translate3d(${-100 * sign}%, 0, 0)`;+/** Same kick as the drawer/pane transforms: the scrim must not wait for the* Recoil commit, which a large conversation can delay past the slide. */const setScrimOpacity = (open: boolean) => {@@ -160,7 +173,9 @@ export function kickDrawerAnimation(next: boolean, applyState: () => void): Draw/*** Walks from `start` up to `boundary` looking for a horizontal scroller that* can still consume a pan in `direction` (1 = finger moving right, which- * reveals content to the left, i.e. needs `scrollLeft > 0`). A rightward+ * reveals content to the left, i.e. needs `scrollLeft > 0`). `direction` is+ * physical on purpose: what a scroller can consume depends on where its+ * content sits on screen, not on which way the drawer opens. A rightward* swipe inside a code block only defers to the block while it can actually* scroll that way — parked at its edge, the drawer may claim the drag.*/@@ -211,7 +226,10 @@ type Gesture = {touchId: number;startX: number;startY: number;+ /** Logical travel: positive toward open, whichever side the drawer is on. */dx: number;+ /** See `drawerSign`; captured at touchstart so one gesture never changes sides. */+ sign: 1 | -1;width: number;reducedMotion: boolean;drawer: HTMLElement;@@ -269,8 +287,8 @@ const dragTransforms = (gesture: Gesture): { drawer: string; pane: string } => {? Math.min(Math.max(gesture.dx, 0), gesture.width): Math.min(Math.max(gesture.dx, -gesture.width), 0) + gesture.width;return {- drawer: `translate3d(${progress - gesture.width}px, 0, 0)`,- pane: `translate3d(${progress}px, 0, 0)`,+ drawer: `translate3d(${(progress - gesture.width) * gesture.sign}px, 0, 0)`,+ pane: `translate3d(${progress * gesture.sign}px, 0, 0)`,};};@@ -387,7 +405,9 @@ export default function useDrawerSwipe({const { drawer: drawerEl, pane: paneEl } = gesture;drawerEl.style.transition = MOBILE_DRAWER_TRANSITION;paneEl.style.transition = SIDEBAR_TRANSITION;- drawerEl.style.transform = next ? 'translate3d(0, 0, 0)' : 'translate3d(-100%, 0, 0)';+ drawerEl.style.transform = next+ ? 'translate3d(0, 0, 0)'+ : closedDrawerTransform(gesture.sign);paneEl.style.transform = next ? MOBILE_PANE_SHIFT : 'translate3d(0, 0, 0)';markDrawerAnimationStart();notifyDrawerSlide(next);@@ -470,7 +490,9 @@ export default function useDrawerSwipe({drawer.style.width = next? MOBILE_DRAWER_WIDTH: `${drawer.getBoundingClientRect().width || window.innerWidth}px`;- drawer.style.transform = next ? 'translate3d(0, 0, 0)' : 'translate3d(-100%, 0, 0)';+ drawer.style.transform = next+ ? 'translate3d(0, 0, 0)'+ : closedDrawerTransform(drawerSign(drawer));markDrawerAnimationStart();notifyDrawerSlide(next);setScrimOpacity(next);@@ -519,6 +541,7 @@ export default function useDrawerSwipe({startX: touch.clientX,startY: touch.clientY,dx: 0,+ sign: drawerSign(drawer),width: drawer.clientWidth || window.innerWidth,reducedMotion: window.matchMedia('(prefers-reduced-motion: reduce)').matches,drawer,@@ -560,18 +583,24 @@ export default function useDrawerSwipe({}return;}- const dx = touch.clientX - gesture.startX;+ const physicalDx = touch.clientX - gesture.startX;+ const dx = physicalDx * gesture.sign;const dy = touch.clientY - gesture.startY;if (gesture.phase === 'tracking') {const horizontal = Math.abs(dx) >= ACTIVATION_DISTANCE;const wins = Math.abs(dx) >= Math.abs(dy) * AXIS_LOCK_RATIO;if (horizontal && wins) {- const direction = dx > 0 ? 1 : -1;- const wrongWay = gesture.opening ? direction !== 1 : direction !== -1;+ /** Opening travels away from the edge the drawer hides behind (the+ * inline start), closing travels back toward it. */+ const wrongWay = gesture.opening ? dx <= 0 : dx >= 0;const blocker = wrongWay? null- : findHorizontalScrollBlocker(event.target as Element | null, surface, direction);+ : findHorizontalScrollBlocker(+ event.target as Element | null,+ surface,+ physicalDx > 0 ? 1 : -1,+ );if (wrongWay || blocker != null) {gesture.phase = 'dead';return;@@ -636,7 +665,9 @@ export default function useDrawerSwipe({* velocity is only trusted when release follows the last move promptly. */const held = event.timeStamp - gesture.lastSample.t > VELOCITY_HOLD_MS;const velocity =- !held && elapsed > 0 ? (gesture.lastSample.x - gesture.prevSample.x) / elapsed : 0;+ !held && elapsed > 0+ ? ((gesture.lastSample.x - gesture.prevSample.x) * gesture.sign) / elapsed+ : 0;const towardTarget = gesture.opening ? velocity : -velocity;const committed =progress >= gesture.width * COMMIT_DISTANCE_RATIO ||diff --git a/client/src/routes/Root.tsx b/client/src/routes/Root.tsxindex a7f416258a..4a2fbed2df 100644--- a/client/src/routes/Root.tsx+++ b/client/src/routes/Root.tsx@@ -187,9 +187,11 @@ function RootLayout() {<Banner onHeightChange={setBannerHeight} /><div className="flex" style={{ height: `calc(100dvh - ${bannerHeight}px)` }}><div- className="relative z-0 flex h-full w-full overflow-hidden"+ className="relative z-0 flex h-full w-full overflow-hidden rtl:[--mobile-drawer-sign:-1]"/** The drawer and the pane both read this, so their travel- * cannot disagree about how far the drawer opens. */+ * cannot disagree about how far the drawer opens. The sign+ * above sends the pane the other way when the drawer opens+ * from the right. */style={{[MOBILE_DRAWER_WIDTH_VAR]: drawerStripdiff --git a/e2e/specs/mock/scenarios/rtl-shell.spec.ts b/e2e/specs/mock/scenarios/rtl-shell.spec.tsnew file mode 100644index 0000000000..9534427c10--- /dev/null+++ b/e2e/specs/mock/scenarios/rtl-shell.spec.ts@@ -0,0 +1,347 @@+import { expect, test } from '@playwright/test';+import type { CDPSession, Locator, Page } from '@playwright/test';+import {+ MOCK_ENDPOINTS,+ NEW_CHAT_PATH,+ messagesView,+ selectMockEndpoint,+ sendMessageAndWaitForCompletion,+} from '../helpers';++/**+ * In a right-to-left locale the app shell mirrors: the sidebar and the mobile drawer sit on the+ * right, the drawer slides in from the right and a swipe follows the finger, the resize handle+ * sits on the sidebar's left edge and grows it toward the left, submenus and rail tooltips open+ * toward the content, and the artifacts panel lands on the inline end while its handle still+ * follows the pointer.+ *+ * Arabic is chosen through the stored language, the same path the language setting writes, so+ * `<html dir="rtl">` comes from i18n rather than from the test. Controls are found by test id,+ * role or untranslated text because the visible copy is Arabic.+ */++const DESKTOP = { width: 1280, height: 800 };+const PHONE = { width: 390, height: 844 };+const HTML_ARTIFACT = 'E2E HTML Artifact';++async function useArabic(page: Page, navVisible?: boolean) {+ await page.addInitScript((visible) => {+ localStorage.setItem('lang', JSON.stringify('ar'));+ if (visible != null) {+ localStorage.setItem('navVisible', JSON.stringify(visible));+ }+ }, navVisible ?? null);+}++async function openRtl(page: Page, path = NEW_CHAT_PATH) {+ await page.goto(path, { timeout: 15000 });+ await expect(page.locator('html')).toHaveAttribute('dir', 'rtl', { timeout: 30000 });+ await expect(page.locator('html')).toHaveAttribute('lang', 'ar');+}++async function box(locator: Locator) {+ const rect = await locator.boundingBox();+ expect(rect).not.toBeNull();+ return rect!;+}++async function firstVisible(candidates: Locator): Promise<Locator> {+ await expect+ .poll(async () => {+ for (const candidate of await candidates.all()) {+ if (await candidate.isVisible()) {+ return true;+ }+ }+ return false;+ })+ .toBe(true);+ for (const candidate of await candidates.all()) {+ if (await candidate.isVisible()) {+ return candidate;+ }+ }+ throw new Error('no visible candidate');+}++/** Resolves once two reads of the element's box agree, so a transition has finished. */+async function still(locator: Locator) {+ let last = '';+ await expect+ .poll(async () => {+ const rect = await box(locator);+ const current = [rect.x, rect.width].map(Math.round).join(',');+ const same = current === last;+ last = current;+ return same;+ })+ .toBe(true);+}++/**+ * A slide hands its inline transform back to the classes a beat after it lands, and the gesture+ * ignores touches until then, so a swipe waits for that hand-off like a finger would.+ */+async function settled(drawer: Locator) {+ await expect+ .poll(() => drawer.evaluate((node) => (node as HTMLElement).style.transform))+ .toBe('');+}++/** A one-finger horizontal drag through the protocol, in small steps like a real swipe. */+async function swipe(session: CDPSession, from: { x: number; y: number }, dx: number) {+ const steps = 12;+ await session.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [from] });+ for (let step = 1; step <= steps; step++) {+ await session.send('Input.dispatchTouchEvent', {+ type: 'touchMove',+ touchPoints: [{ x: from.x + (dx * step) / steps, y: from.y }],+ });+ }+ await session.send('Input.dispatchTouchEvent', { type: 'touchEnd', touchPoints: [] });+}++/** Asserts the open artifacts panel's placement and drag in RTL. */+async function expectArtifactsHandleFollowsPointer(page: Page, panel: Locator) {+ const handle = page.locator('[role="separator"]:not([aria-label="Resize sidebar"])').first();+ await expect(handle).toBeVisible();+ /** The panel opens with a transition; measure once the handle has stopped moving. */+ await still(handle);+ const panelBox = await box(panel);+ const handleBox = await box(handle);+ const messagesBefore = await box(messagesView(page));+ /** Inline end is the left in RTL: artifacts, then the handle, then the messages. */+ expect(panelBox.x + panelBox.width / 2).toBeLessThan(handleBox.x);+ expect(handleBox.x + handleBox.width).toBeLessThanOrEqual(messagesBefore.x + 2);++ /**+ * Dragging the handle right by 80px moves it 80px right, widening the artifacts and narrowing+ * the messages by as much. The drag runs toward the messages so the pointer never crosses the+ * preview iframe, which takes pointer events for itself in either direction.+ */+ const x = handleBox.x + handleBox.width / 2;+ const y = handleBox.y + handleBox.height / 2;+ await page.mouse.move(x, y);+ await page.mouse.down();+ await page.mouse.move(x + 40, y, { steps: 4 });+ await page.mouse.move(x + 80, y, { steps: 4 });+ await page.mouse.up();+ await expect+ .poll(async () => Math.round((await box(handle)).x - handleBox.x))+ .toBeGreaterThanOrEqual(70);+ const moved = await box(handle);+ expect(moved.x - handleBox.x).toBeLessThanOrEqual(90);+ const messagesAfter = await box(messagesView(page));+ expect(messagesBefore.width - messagesAfter.width).toBeGreaterThan(60);+}++test.describe('phone', () => {+ test.use({ viewport: PHONE, hasTouch: true, isMobile: true });++ test('the mobile drawer opens from the right edge and follows a swipe in RTL @scenario:rtl-mobile-drawer-opens-from-the-right-and-follows-swipes', async ({+ page,+ }) => {+ await useArabic(page);+ await openRtl(page);+ await expect(page.locator('#prompt-textarea')).toBeVisible({ timeout: 30000 });++ const drawer = page.locator('#mobile-drawer');+ const closeButton = drawer.getByTestId('close-sidebar-button');+ if (!(await closeButton.isVisible())) {+ await page.getByTestId('header-open-sidebar-button').click();+ }+ await expect(closeButton).toBeVisible();+ await expect(drawer).not.toHaveAttribute('inert');+ /** Anchored to the inline start, which is the right edge in RTL. */+ await expect+ .poll(async () => {+ const rect = await box(drawer);+ return Math.round(rect.x + rect.width);+ })+ .toBe(PHONE.width);++ const session = await page.context().newCDPSession(page);+ try {+ /** Closing travels toward the edge the drawer hides behind: rightward in RTL. */+ await settled(drawer);+ const open = await box(drawer);+ await swipe(session, { x: open.x + open.width / 2, y: open.y + open.height / 2 }, 240);+ await expect+ .poll(async () => Math.round((await box(drawer)).x))+ .toBeGreaterThanOrEqual(PHONE.width);+ await expect(page.getByTestId('header-open-sidebar-button')).toBeVisible();++ /** Opening from the pane travels away from that edge: leftward in RTL. */+ await settled(drawer);+ await swipe(session, { x: PHONE.width - 60, y: PHONE.height / 3 }, -260);+ await expect+ .poll(async () => {+ const rect = await box(drawer);+ return Math.round(rect.x + rect.width);+ })+ .toBe(PHONE.width);+ await expect(closeButton).toBeVisible();+ } finally {+ await session.detach();+ }++ /** The close control's icon mirrors with the layout. */+ const icon = closeButton.locator('svg').first();+ const scale = await icon.evaluate((node) => getComputedStyle(node).scale);+ expect(scale.split(' ')[0]).toBe('-1');+ });+});++test.describe('desktop', () => {+ test.use({ viewport: DESKTOP, hasTouch: false, isMobile: false });++ test('the sidebar resize handle grows the sidebar toward the left in RTL @scenario:rtl-sidebar-resize-follows-pointer-and-arrow-keys', async ({+ page,+ }) => {+ await useArabic(page, true);+ await openRtl(page);++ const handle = page.getByRole('separator', { name: 'Resize sidebar' });+ await expect(handle).toBeVisible({ timeout: 30000 });+ const sidebar = handle.locator('xpath=..');+ const initial = await box(sidebar);+ /** The sidebar hugs the right edge and its handle sits on its left edge. */+ expect(Math.round(initial.x + initial.width)).toBe(DESKTOP.width);+ const handleBox = await box(handle);+ expect(handleBox.x).toBeLessThan(initial.x + 8);++ /** Arrow keys: the arrow pointing away from the sidebar (left) grows it. */+ await handle.focus();+ const valueOf = async () => Number(await handle.getAttribute('aria-valuenow'));+ const start = await valueOf();+ await page.keyboard.press('ArrowLeft');+ await expect.poll(valueOf).toBeGreaterThan(start);+ const grown = await valueOf();+ await page.keyboard.press('ArrowRight');+ await expect.poll(valueOf).toBeLessThan(grown);++ /** Pointer: dragging left by 60px widens the sidebar by the same 60px. */+ await still(sidebar);+ await still(handle);+ const before = await box(sidebar);+ const grab = await box(handle);+ const x = grab.x + grab.width / 2;+ const y = grab.y + grab.height / 2;+ await page.mouse.move(x, y);+ await page.mouse.down();+ await page.mouse.move(x - 30, y, { steps: 4 });+ await page.mouse.move(x - 60, y, { steps: 4 });+ await page.mouse.up();+ await expect+ .poll(async () => Math.round((await box(sidebar)).width - before.width))+ .toBeGreaterThanOrEqual(55);+ const after = await box(sidebar);+ expect(after.width - before.width).toBeLessThanOrEqual(65);+ expect(Math.round(after.x + after.width)).toBe(DESKTOP.width);+ });++ test('account menu submenus open toward the content and by the left arrow in RTL @scenario:rtl-account-submenu-opens-toward-the-content', async ({+ page,+ }) => {+ await useArabic(page, true);+ await openRtl(page);++ await (await firstVisible(page.getByTestId('nav-user'))).click();+ const menu = page.getByRole('menu').first();+ await expect(menu).toBeVisible();+ const help = menu.locator('[role="menuitem"][aria-haspopup]').first();+ await expect(help).toBeVisible();++ await help.focus();+ await page.keyboard.press('ArrowLeft');+ const submenu = page.getByRole('menu').nth(1);+ await expect(submenu).toBeVisible();+ await expect(help).toHaveAttribute('aria-expanded', 'true');++ const helpBox = await box(help);+ const submenuBox = await box(submenu);+ /** Toward the content is leftward in RTL, where the sidebar is on the right. */+ expect(submenuBox.x + submenuBox.width).toBeLessThanOrEqual(helpBox.x + 8);+ });++ test('collapsed rail tooltips open toward the content in RTL @scenario:rtl-rail-tooltips-open-toward-the-content', async ({+ page,+ }) => {+ await useArabic(page, false);+ await openRtl(page);++ const newChat = await firstVisible(page.getByTestId('new-chat-button'));+ const buttonBox = await box(newChat);+ /** The rail sits on the right edge. */+ expect(buttonBox.x).toBeGreaterThan(DESKTOP.width / 2);++ await newChat.hover();+ const tooltip = page.getByRole('tooltip').first();+ await expect(tooltip).toBeVisible();+ const tooltipBox = await box(tooltip);+ expect(tooltipBox.x + tooltipBox.width).toBeLessThanOrEqual(buttonBox.x + 2);+ });++ test('the artifacts panel sits on the inline end and its handle follows the pointer in RTL @scenario:rtl-artifacts-panel-on-inline-end-and-handle-follows-pointer', async ({+ page,+ }) => {+ test.setTimeout(150000);++ /** The reply is produced in English, where the shared helpers find their controls. */+ await page.goto(NEW_CHAT_PATH, { timeout: 15000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await sendMessageAndWaitForCompletion(page, 'E2E_HTML_ARTIFACT_REPLY', { timeout: 60000 });+ await expect(page).toHaveURL(/\/c\/(?!new)/);+ const conversationPath = new URL(page.url()).pathname;++ await page.evaluate(() => localStorage.setItem('lang', JSON.stringify('ar')));+ await openRtl(page, conversationPath);++ await messagesView(page)+ .getByRole('button', { name: new RegExp(HTML_ARTIFACT) })+ .click();+ const panel = page.getByRole('region', { name: HTML_ARTIFACT });+ await expect(panel).toBeVisible({ timeout: 30000 });++ await expectArtifactsHandleFollowsPointer(page, panel);+ });++ test('switching to RTL with the artifacts panel open keeps its handle following the pointer @scenario:rtl-live-language-switch-keeps-artifacts-handle-following-pointer', async ({+ page,+ }) => {+ test.setTimeout(150000);++ await page.goto(NEW_CHAT_PATH, { timeout: 15000 });+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);+ await sendMessageAndWaitForCompletion(page, 'E2E_HTML_ARTIFACT_REPLY', { timeout: 60000 });+ await expect(page).toHaveURL(/\/c\/(?!new)/);+ await messagesView(page)+ .getByRole('button', { name: new RegExp(HTML_ARTIFACT) })+ .click();+ const panel = page.getByRole('region', { name: HTML_ARTIFACT });+ await expect(panel).toBeVisible({ timeout: 30000 });+ await expect(page.locator('html')).not.toHaveAttribute('dir', 'rtl');++ /** The panels mount in LTR order; Arabic is then picked in Settings without a reload. */+ await page.getByTestId('nav-user').click();+ await page.getByRole('menuitem', { name: 'Settings' }).click();+ await page.getByRole('combobox', { name: /^Language/ }).click();+ await page.getByRole('option', { name: 'العربية' }).click();+ await expect(page.locator('html')).toHaveAttribute('dir', 'rtl', { timeout: 30000 });+ await page.keyboard.press('Escape');+ await expect(page.getByRole('dialog')).toHaveCount(0);++ await expect(panel).toBeVisible();+ await expectArtifactsHandleFollowsPointer(page, panel);++ /** The arrow keys move the handle the way they point, as they did before the switch. */+ const handle = page.locator('[role="separator"]:not([aria-label="Resize sidebar"])').first();+ await handle.focus();+ const before = await box(handle);+ await page.keyboard.press('ArrowRight');+ await expect.poll(async () => (await box(handle)).x - before.x).toBeGreaterThan(10);+ const after = await box(handle);+ await page.keyboard.press('ArrowLeft');+ await expect.poll(async () => after.x - (await box(handle)).x).toBeGreaterThan(10);+ });+});diff --git a/eslint-suppressions.json b/eslint-suppressions.jsonindex 526a30c6a7..e550d2abe9 100644--- a/eslint-suppressions.json+++ b/eslint-suppressions.json@@ -778,7 +778,7 @@},"client/src/components/Nav/AccountSettings.tsx": {"shadcn/no-inline-styles": {- "count": 3+ "count": 1}},"client/src/components/Nav/KeyboardShortcutsDialog.tsx": {