The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): add Appearance text direction setting (Auto / RTL / LTR)
brooklyn!32eeacdf7c1e
diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsxindex 5b16bbf6e9f..c27685fec85 100644--- a/apps/desktop/src/app/chat/composer/index.tsx+++ b/apps/desktop/src/app/chat/composer/index.tsx@@ -37,6 +37,7 @@ import { sessionBlockingPrompt } from '@/store/prompts'import { toggleReview } from '@/store/review'import { $gatewayState } from '@/store/session'import { $botChatSessionIds, $sessionStates, $sessionTiles, isBotChatSession } from '@/store/session-states'+import { useForcedTextDirection } from '@/store/text-direction'import { $threadScrolledUpBySession } from '@/store/thread-scroll'import { $autoSpeakReplies } from '@/store/voice-prefs'import { useTheme } from '@/themes'@@ -195,6 +196,7 @@ export function ChatBar({)const autoSpeak = useStore($autoSpeakReplies)+ const textDirection = useForcedTextDirection()// The turn is parked on the user (clarify / approval / sudo / secret). Esc must// not interrupt it — there's nothing actively running to stop, and stopping// would discard a question the user may want to come back to. The blocking@@ -1168,6 +1170,7 @@ export function ChatBar({contentEditable={!inputDisabled}data-placeholder={placeholder}data-slot={RICH_INPUT_SLOT}+ dir={textDirection}onBeforeInput={handleEditorBeforeInput}onBlur={() => {// A composition never survives focus loss (Chromium commits thediff --git a/apps/desktop/src/app/settings/appearance-settings.tsx b/apps/desktop/src/app/settings/appearance-settings.tsxindex 25ff3a83962..9d38106a30e 100644--- a/apps/desktop/src/app/settings/appearance-settings.tsx+++ b/apps/desktop/src/app/settings/appearance-settings.tsx@@ -31,6 +31,7 @@ import { $reactionsEnabled, setReactionsEnabled } from '@/store/reactions-enableimport { $reasoningCollapsedByDefault, setReasoningCollapsedByDefault } from '@/store/reasoning-disclosure'import { $sessionListDensity, type SessionListDensity, setSessionListDensity } from '@/store/session-list-density'import { $tabStripDefault, setTabStripDefault, type TabStripDefault } from '@/store/tabstrip-prefs'+import { $textDirection, setTextDirection, TEXT_DIRECTIONS, type TextDirection } from '@/store/text-direction'import { $hideThreadTimeline, setHideThreadTimeline } from '@/store/thread-timeline'import { $spentTipCount, $tipsEnabled, resetTips, setTipsEnabled } from '@/store/tips'import {@@ -433,6 +434,7 @@ export function AppearanceSettings({ subpage }: AppearanceSettingsProps = {}) {const translucency = useStore($translucency)const glassMode = translucency.mode === 'glass' && GLASS_SUPPORTEDconst userBubbleTransparency = useStore($userBubbleTransparency)+ const textDirection = useStore($textDirection)const reactionsEnabled = useStore($reactionsEnabled)const tipsEnabled = useStore($tipsEnabled)const toursEnabled = useStore($toursEnabled)@@ -538,6 +540,11 @@ export function AppearanceSettings({ subpage }: AppearanceSettingsProps = {}) {{ id: 'left', label: a.appActionsLeft }] as const satisfies readonly { id: TitlebarAppActionsSide; label: string }[]+ const textDirectionOptions = TEXT_DIRECTIONS.map(id => ({+ id,+ label: a.textDirection[id]+ })) satisfies readonly { id: TextDirection; label: string }[]+const embedOptions = [{ id: 'ask', label: a.embedsAsk },{ id: 'always', label: a.embedsAlways },@@ -880,6 +887,24 @@ export function AppearanceSettings({ subpage }: AppearanceSettingsProps = {}) {/>)}+ {show('chat-display') && (+ <ListRow+ action={+ <SegmentedControl+ onChange={id => {+ triggerHaptic('selection')+ setTextDirection(id)+ }}+ options={textDirectionOptions}+ value={textDirection}+ />+ }+ description={a.textDirectionDesc}+ id={appearanceSettingElementId(APPEARANCE_SETTING_IDS.textDirection)}+ title={a.textDirectionTitle}+ />+ )}+{show('window-layout') && (<ListRowaction={diff --git a/apps/desktop/src/app/settings/appearance-subpages.ts b/apps/desktop/src/app/settings/appearance-subpages.tsindex e67ae0966e7..ca1c67a484b 100644--- a/apps/desktop/src/app/settings/appearance-subpages.ts+++ b/apps/desktop/src/app/settings/appearance-subpages.ts@@ -20,6 +20,7 @@ const SETTING_SUBPAGES: Readonly<Record<string, AppearanceSubpageId>> = {'appearance.language': 'general','appearance.minimize-to-tray': 'window-layout','appearance.pet': 'pet',+ 'appearance.text-direction': 'chat-display','appearance.theme': 'theme','appearance.tool-view': 'chat-display','appearance.interface-mode': 'window-layout',diff --git a/apps/desktop/src/app/settings/settings-search.ts b/apps/desktop/src/app/settings/settings-search.tsindex 135b78e150f..3e768e1b204 100644--- a/apps/desktop/src/app/settings/settings-search.ts+++ b/apps/desktop/src/app/settings/settings-search.ts@@ -20,6 +20,7 @@ export const APPEARANCE_SETTING_IDS = {introSplash: 'appearance.intro-splash',language: 'appearance.language',minimizeToTray: 'appearance.minimize-to-tray',+ textDirection: 'appearance.text-direction',theme: 'appearance.theme',toolView: 'appearance.tool-view',interfaceMode: 'appearance.interface-mode',diff --git a/apps/desktop/src/app/settings/use-settings-search.ts b/apps/desktop/src/app/settings/use-settings-search.tsindex 36ed0ee91ae..fbf0d928365 100644--- a/apps/desktop/src/app/settings/use-settings-search.ts+++ b/apps/desktop/src/app/settings/use-settings-search.ts@@ -188,6 +188,15 @@ export function useSettingsSearchCatalog(enabled: boolean) {label: appearance.userBubbleTitle,target: { setting: APPEARANCE_SETTING_IDS.userBubble, view: 'config:appearance' }},+ {+ context: appearanceContext,+ description: appearance.textDirectionDesc,+ icon: Palette,+ id: `setting:${APPEARANCE_SETTING_IDS.textDirection}`,+ keywords: ['rtl', 'ltr', 'right to left', 'left to right', 'bidi', 'arabic', 'hebrew', 'persian', 'align'],+ label: appearance.textDirectionTitle,+ target: { setting: APPEARANCE_SETTING_IDS.textDirection, view: 'config:appearance' }+ },{context: appearanceContext,description: appearance.backdropDesc,diff --git a/apps/desktop/src/components/assistant-ui/markdown-text.tsx b/apps/desktop/src/components/assistant-ui/markdown-text.tsxindex 237750d650e..73d8eb47dba 100644--- a/apps/desktop/src/components/assistant-ui/markdown-text.tsx+++ b/apps/desktop/src/components/assistant-ui/markdown-text.tsx@@ -40,6 +40,7 @@ import { previewTargetFromMarkdownHref } from '@/lib/preview-targets'import { sessionRefFromMarkdownHref } from '@/lib/session-refs'import { isDirectiveInProgress } from '@/lib/transcript-directives'import { cn } from '@/lib/utils'+import { useForcedTextDirection } from '@/store/text-direction'import { ArtifactCard } from './artifact-card'import { SessionRefLink } from './directive-text'@@ -468,6 +469,10 @@ interface MarkdownTextSurfaceProps {* routed @mentions) without owning the Markdown pipeline. Nested inline* markup and code are left as rendered. */decorateText?: (children: ReactNode) => ReactNode+ /** The reader's explicit Text direction (Appearance). Stamped on the root+ * and on list/quote boxes in place of their `dir="auto"`, so every prose+ * block follows it; undefined is Auto and leaves the DOM attribute-free. */+ textDirection?: 'ltr' | 'rtl'}// Headings shrink to chat scale rather than the prose default (h1≈xl). Kept@@ -587,9 +592,19 @@ function MarkdownTextSurface({defer,disableArtifacts,previewOnly,- scratchpad+ scratchpad,+ textDirection}: MarkdownTextSurfaceProps) {const { status, text } = useMessagePartText()+ // List/quote boxes resolve from content under Auto (see the ul/ol/blockquote+ // notes below); an explicit choice replaces that vote rather than nesting it.+ const boxDir = textDirection ?? 'auto'++ const surfaceContainerProps = useMemo(+ () => (textDirection ? { ...containerProps, dir: textDirection } : containerProps),+ [containerProps, textDirection]+ )+const isStreaming = status.type === 'running'// Keep code parsing enabled while streaming so incomplete fenced blocks still@@ -654,7 +669,7 @@ function MarkdownTextSurface({return (<blockquoteclassName={cn('border-s-2 border-(--ui-stroke-tertiary) ps-3 text-muted-foreground italic', className)}- dir="auto"+ dir={boxDir}{...props}>{children}@@ -662,10 +677,10 @@ function MarkdownTextSurface({)},ul: ({ className, ...props }: ComponentProps<'ul'>) => (- <ul className={cn('my-1 gap-0', className)} dir="auto" {...props} />+ <ul className={cn('my-1 gap-0', className)} dir={boxDir} {...props} />),ol: ({ className, ...props }: ComponentProps<'ol'>) => (- <ol className={cn('my-1 gap-0', className)} dir="auto" {...props} />+ <ol className={cn('my-1 gap-0', className)} dir={boxDir} {...props} />),li: ({ children, className, ...props }: ComponentProps<'li'>) => (<li className={cn('leading-(--dt-line-height)', className)} {...props}>@@ -708,7 +723,7 @@ function MarkdownTextSurface({)}}) as StreamdownTextComponents,- [decorateText, disableArtifacts, isStreaming, previewOnly, scratchpad]+ [boxDir, decorateText, disableArtifacts, isStreaming, previewOnly, scratchpad])if (text.length > MAX_MARKDOWN_CHARS) {@@ -741,7 +756,7 @@ function MarkdownTextSurface({<StreamdownTextPrimitivecomponents={components}containerClassName={cn(MARKDOWN_CONTAINER_CLASS_NAME, containerClassName)}- containerProps={containerProps}+ containerProps={surfaceContainerProps}defer={defer}lineNumbers={false}mode="streaming"@@ -803,7 +818,9 @@ export function MarkdownTextContent({ isRunning, text, ...surfaceProps }: Markdo}const MarkdownTextImpl = () => {- return <MarkdownTextSurface defer />+ const textDirection = useForcedTextDirection()++ return <MarkdownTextSurface defer textDirection={textDirection} />}export const MarkdownText = memo(MarkdownTextImpl)diff --git a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsxindex e0a0afa7978..69762b37d99 100644--- a/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/message-parts.tsx@@ -31,6 +31,7 @@ import { isTodoToolName } from '@/lib/todos'import { useEnterAnimation } from '@/lib/use-enter-animation'import { cn } from '@/lib/utils'import { $reasoningCollapsedByDefault, $showReasoning } from '@/store/reasoning-disclosure'+import { useForcedTextDirection } from '@/store/text-direction'type TimelineToolCallProps = ToolCallMessagePartProps & { completedAt?: number; timestamp?: number }@@ -390,6 +391,7 @@ const ReasoningTextPart: ReasoningMessagePartComponent = () => {// rendered without a ReasoningGroup wrapper (assistant-ui drops the group// when a ChainOfThought component is registered).const showReasoning = useStore($showReasoning)+ const textDirection = useForcedTextDirection()if (!showReasoning) {return null@@ -402,6 +404,7 @@ const ReasoningTextPart: ReasoningMessagePartComponent = () => {isRunning={status.type === 'running' || messageRunning}scratchpadtext={separateGluedReasoningBlocks(text.trimStart())}+ textDirection={textDirection}/>)}diff --git a/apps/desktop/src/components/assistant-ui/thread/text-direction.test.tsx b/apps/desktop/src/components/assistant-ui/thread/text-direction.test.tsxnew file mode 100644index 00000000000..20b3ee64a97--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/thread/text-direction.test.tsx@@ -0,0 +1,209 @@+// Appearance → Text direction. Auto is the shipped per-block first-strong+// behavior and must leave the DOM exactly as it was; RTL/LTR stamp one `dir`+// on each chat prose surface and both composers, replacing the list/quote+// boxes' `dir="auto"` vote, while inline code keeps its own `dir="ltr"`.+// jsdom neither resolves `dir` nor applies styles.css, so these pin the+// attribute contract; the stylesheet half is checked in real Chromium.+import { AssistantRuntimeProvider, type ThreadMessage, useExternalStoreRuntime } from '@assistant-ui/react'+import type { ThreadMessageLike } from '@assistant-ui/react'+import { act, cleanup, render, screen } from '@testing-library/react'+import { MemoryRouter } from 'react-router'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { ChatBar } from '@/app/chat/composer'+import { RICH_INPUT_SLOT } from '@/app/chat/composer/rich-editor'+import type { ChatBarState } from '@/app/chat/composer/types'+import { I18nProvider } from '@/i18n'+import { $textDirection, setTextDirection, type TextDirection } from '@/store/text-direction'++import { stubThreadEnvironment, stubThreadViewportSize } from '../test-utils'++import { Thread } from '.'++const createdAt = new Date('2026-06-01T00:00:00.000Z')+stubThreadEnvironment()+stubThreadViewportSize()++afterEach(() => {+ cleanup()+ setTextDirection('auto')+})++// #100280's Latin-majority Arabic quote: first-strong resolves it LTR, which+// is exactly the case a reader needs to override.+const QUOTE =+ 'Ergander و Aspalta وردت عليه. الضبط Care إلى Ozul + Daphne هو Seyir وفريق — Seyir + Ozul + Daphne + Saverio هو Daphne dragonheir.info فريق في'++const ASSISTANT_TEXT = [+ QUOTE,+ '',+ '1. `npm install` ثم Seyir',+ '2. Daphne مع Ozul',+ '',+ '> Ultimate - Desperate Beast يضرب مرتين'+].join('\n')++// #83868's English-leading Arabic line, then an Arabic-leading one.+const USER_TEXT = 'Hello مرحبا كيفك\nمرحبا Hello'++function userMessage(): ThreadMessage {+ return {+ id: 'user-1',+ role: 'user',+ content: [{ type: 'text', text: USER_TEXT }],+ attachments: [],+ createdAt,+ metadata: { custom: {} }+ } as ThreadMessage+}++function assistantMessage(): ThreadMessage {+ return {+ id: 'assistant-1',+ role: 'assistant',+ content: [{ type: 'text', text: ASSISTANT_TEXT }],+ status: { type: 'complete', reason: 'stop' },+ createdAt,+ metadata: { unstable_state: null, unstable_annotations: [], unstable_data: [], steps: [], custom: {} }+ } as ThreadMessage+}++function ThreadHarness() {+ const runtime = useExternalStoreRuntime<ThreadMessage>({+ messages: [userMessage(), assistantMessage()],+ isRunning: false,+ onNew: async () => {}+ })++ return (+ <AssistantRuntimeProvider runtime={runtime}>+ <Thread />+ </AssistantRuntimeProvider>+ )+}++const chatBarState: ChatBarState = {+ model: { canSwitch: false, model: '', provider: '' },+ tools: { enabled: false, label: '' },+ voice: { enabled: false, active: false }+}++function ComposerHarness() {+ const runtime = useExternalStoreRuntime({+ convertMessage: (message: ThreadMessageLike) => message,+ isRunning: false,+ messages: [] as ThreadMessageLike[],+ onNew: async () => {}+ })++ return (+ <AssistantRuntimeProvider runtime={runtime}>+ <MemoryRouter>+ <I18nProvider configClient={null} initialLocale="en">+ <ChatBar+ busy={false}+ disabled={false}+ gateway={null}+ onCancel={vi.fn()}+ onSubmit={vi.fn(async () => true)}+ state={chatBarState}+ />+ </I18nProvider>+ </MemoryRouter>+ </AssistantRuntimeProvider>+ )+}++async function renderThread() {+ const view = render(<ThreadHarness />)+ const quote = await screen.findByText(/Aspalta/)+ const root = quote.closest('.aui-md')+ const list = (await screen.findByText(/Daphne مع Ozul/)).closest('ol')+ const blockquote = (await screen.findByText(/Desperate Beast/)).closest('blockquote')+ const code = await screen.findByText('npm install')+ const userText = view.container.querySelector<HTMLElement>('[data-slot="aui_user-inline-text"]')++ expect(root).not.toBeNull()+ expect(list).not.toBeNull()+ expect(blockquote).not.toBeNull()+ expect(userText?.textContent).toBe(USER_TEXT)++ return { blockquote: blockquote!, code, list: list!, quote, root: root!, userText: userText!, view }+}++function composerEditor(container: HTMLElement) {+ const editor = container.querySelector<HTMLElement>(`[data-slot="${RICH_INPUT_SLOT}"]`)++ expect(editor).not.toBeNull()++ return editor!+}++// Every `dir` in a rendered subtree, so "Auto adds nothing" is one comparison.+function dirAttributes(container: HTMLElement) {+ return [...container.querySelectorAll('[dir]')].map(el => `${el.tagName.toLowerCase()}=${el.getAttribute('dir')}`)+}++describe('Text direction: Auto', () => {+ it('keeps the native first-strong DOM: only list/quote boxes vote, code opts out', async () => {+ const { blockquote, code, list, quote, root, userText, view } = await renderThread()++ expect($textDirection.get()).toBe('auto')+ expect(root.hasAttribute('dir')).toBe(false)+ expect(quote.hasAttribute('dir')).toBe(false)+ expect(userText.hasAttribute('dir')).toBe(false)+ expect(list.getAttribute('dir')).toBe('auto')+ expect(blockquote.getAttribute('dir')).toBe('auto')+ expect(code.getAttribute('dir')).toBe('ltr')+ expect(new Set(dirAttributes(view.container))).toEqual(new Set(['ol=auto', 'blockquote=auto', 'code=ltr']))+ })++ it('leaves the composer attribute-free and stores nothing', () => {+ const { container } = render(<ComposerHarness />)++ expect(composerEditor(container).hasAttribute('dir')).toBe(false)+ expect(window.localStorage.getItem('hermes.desktop.textDirection')).toBeNull()+ })++ it('returns to the identical DOM after a forced direction is cleared', async () => {+ const { view } = await renderThread()+ const autoHtml = view.container.innerHTML++ act(() => setTextDirection('rtl'))+ expect(view.container.innerHTML).not.toBe(autoHtml)++ act(() => setTextDirection('auto'))+ expect(view.container.innerHTML).toBe(autoHtml)+ expect(window.localStorage.getItem('hermes.desktop.textDirection')).toBeNull()+ })+})++describe.each<Exclude<TextDirection, 'auto'>>(['rtl', 'ltr'])('Text direction: %s', direction => {+ it('forces the prose root, list/quote boxes and user lines; inline code stays LTR', async () => {+ setTextDirection(direction)++ const { blockquote, code, list, quote, root, userText } = await renderThread()++ expect(root.getAttribute('dir')).toBe(direction)+ expect(list.getAttribute('dir')).toBe(direction)+ expect(blockquote.getAttribute('dir')).toBe(direction)+ expect(userText.getAttribute('dir')).toBe(direction)+ // Paragraphs inherit from the root rather than carrying their own vote.+ expect(quote.hasAttribute('dir')).toBe(false)+ expect(code.getAttribute('dir')).toBe('ltr')+ // Presentation only: the text itself carries no injected bidi controls.+ expect(quote.textContent).toBe(QUOTE)+ expect(userText.textContent).not.toMatch(/[\u200e\u200f\u202a-\u202e\u2066-\u2069]/)+ })++ it('forces the composer live and persists the choice', () => {+ const { container } = render(<ComposerHarness />)++ act(() => setTextDirection(direction))+ expect(composerEditor(container).getAttribute('dir')).toBe(direction)+ expect(window.localStorage.getItem('hermes.desktop.textDirection')).toBe(direction)++ act(() => setTextDirection('auto'))+ expect(composerEditor(container).hasAttribute('dir')).toBe(false)+ })+})diff --git a/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx b/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsxindex 6cd1b9149a4..185e70abce6 100644--- a/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx@@ -79,6 +79,7 @@ import type { ComposerAttachment } from '@/store/composer'import { notifyError } from '@/store/notifications'import { $terminalBackend } from '@/store/session'import { isSessionRemote } from '@/store/session-states'+import { useForcedTextDirection } from '@/store/text-direction'import { notifyThreadEditClose } from '@/store/thread-scroll'interface UserEditComposerProps {@@ -92,6 +93,7 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sessconst copy = t.assistant.threadconst aui = useAui()const draft = useAuiState(s => s.composer.text)+ const textDirection = useForcedTextDirection()const rootRef = useRef<HTMLDivElement | null>(null)const editorRef = useRef<HTMLDivElement | null>(null)// Capture the original draft immediately before the first edit. The runtime@@ -869,6 +871,7 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sesscontentEditabledata-placeholder={copy.editMessage}data-slot={RICH_INPUT_SLOT}+ dir={textDirection}onBeforeInput={handleBeforeInput}onBlur={() => scheduleTimeout(closeTrigger, 80)}onCompositionEnd={event => {diff --git a/apps/desktop/src/components/assistant-ui/thread/user-message-text.tsx b/apps/desktop/src/components/assistant-ui/thread/user-message-text.tsxindex 15f46495f13..134f91d37e6 100644--- a/apps/desktop/src/components/assistant-ui/thread/user-message-text.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/user-message-text.tsx@@ -4,6 +4,7 @@ import { Fragment, useMemo } from 'react'import { DirectiveContent } from '@/components/assistant-ui/directive-text'import { referenceRe } from '@/components/assistant-ui/reference-kinds'import { cn } from '@/lib/utils'+import { useForcedTextDirection } from '@/store/text-direction'// User messages should render the bare-minimum of markdown: backtick `code`// spans and ``` fenced blocks. We deliberately don't pull in the full@@ -148,11 +149,13 @@ export const UserMessageText: FC<UserMessageTextProps> = ({ className, text }) =const InlineSegmentView: FC<{ text: string }> = ({ text }) => {const nodes = useMemo(() => splitInlineCode(text), [text])+ const textDirection = useForcedTextDirection()return (// styles.css bidi hook (#44150); whitespace-pre-line makes each line its own- // UAX#9 paragraph so it resolves direction independently.- <span className="wrap-anywhere block whitespace-pre-line" data-slot="aui_user-inline-text">+ // UAX#9 paragraph so it resolves direction independently — unless the+ // reader picked an explicit Text direction, which every line then follows.+ <span className="wrap-anywhere block whitespace-pre-line" data-slot="aui_user-inline-text" dir={textDirection}>{nodes.map((node, nodeIndex) =>node.kind === 'inline-code' ? (<codediff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 519f2da05a7..fb1b022ab7c 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -642,6 +642,10 @@ export const ar = defineLocale({backdropDesc: 'اختيار مقدار مزج خلفية سطح المكتب مع سطح Hermes.',userBubbleTitle: 'فقاعة الرسالة',userBubbleDesc: 'مدى شفافية رسائلك. معتمة عند 0؛ يبقى الإطار فقط عند 100.',+ textDirectionTitle: 'اتجاه النص',+ textDirectionDesc:+ 'كيف تحدد رسائل المحادثة وحقل الكتابة اتجاهها. «تلقائي» يتبع أول حرف في كل فقرة؛ اختر اتجاهًا عندما يظهر النص المختلط بترتيب خاطئ. تبقى الشيفرة دائمًا من اليسار إلى اليمين.',+ textDirection: { auto: 'تلقائي', rtl: 'من اليمين إلى اليسار', ltr: 'من اليسار إلى اليمين' },introSplashTitle: 'شاشة المقدمة',introSplashDesc: 'الشعار النصي والعبارة التمهيدية في محادثة فارغة.',reactionsTitle: 'تفاعلات الرسائل',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 69a653318ad..4a0b524887f 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -1099,6 +1099,10 @@ export const en: Translations = {backdropDesc: 'The faint statue image behind the conversation.',userBubbleTitle: 'Message Bubble',userBubbleDesc: 'How see-through your own messages are. Solid at 0; only the outline remains at 100.',+ textDirectionTitle: 'Text direction',+ textDirectionDesc:+ 'How chat messages and the composer choose their direction. Auto follows the first letter of each paragraph; pick a direction when mixed text lines up the wrong way. Code always stays left-to-right.',+ textDirection: { auto: 'Auto', rtl: 'Right-to-left', ltr: 'Left-to-right' },introSplashTitle: 'Intro Splash',introSplashDesc: 'The wordmark and prompt shown on an empty chat.',reactionsTitle: 'Message Reactions',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 6e2616fb671..43fe2f80964 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -643,6 +643,10 @@ export const ja = defineLocale({backdropDesc: '会話の背後に表示される淡い彫像の画像。',userBubbleTitle: 'メッセージの吹き出し',userBubbleDesc: '自分のメッセージの透け具合。0 で不透明、100 で枠線だけが残ります。',+ textDirectionTitle: 'テキストの方向',+ textDirectionDesc:+ 'チャットのメッセージと入力欄の文字方向を設定します。「自動」は各段落の最初の文字で判断します。混在したテキストの並びがおかしいときは方向を選んでください。コードは常に左から右に表示されます。',+ textDirection: { auto: '自動', rtl: '右から左', ltr: '左から右' },introSplashTitle: 'イントロ表示',introSplashDesc: '空のチャットに表示されるワードマークとプロンプト。',reactionsTitle: 'メッセージリアクション',diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex cb434b19e8e..1d02c774512 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -680,6 +680,10 @@ export const ru = defineLocale({backdropDesc: 'Блёклый силуэт позади диалога.',userBubbleTitle: 'Пузырь сообщения',userBubbleDesc: 'Насколько прозрачны ваши сообщения. 0 — сплошная заливка, 100 — остаётся только контур.',+ textDirectionTitle: 'Направление текста',+ textDirectionDesc:+ 'Как сообщения чата и поле ввода выбирают направление. «Авто» ориентируется на первую букву каждого абзаца; выберите направление, если смешанный текст выстраивается неправильно. Код всегда остаётся слева направо.',+ textDirection: { auto: 'Авто', rtl: 'Справа налево', ltr: 'Слева направо' },introSplashTitle: 'Экран приветствия',introSplashDesc: 'Логотип и подсказка, показываемые на пустом чате.',reactionsTitle: 'Реакции на сообщения',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 2128bacc844..04d2b550779 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -907,6 +907,9 @@ export interface Translations {backdropDesc: stringuserBubbleTitle: stringuserBubbleDesc: string+ textDirectionTitle: string+ textDirectionDesc: string+ textDirection: { auto: string; rtl: string; ltr: string }introSplashTitle: stringintroSplashDesc: stringreactionsTitle: stringdiff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 3a2e274c299..3e0194cf50b 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -591,6 +591,10 @@ export const zhHant = defineLocale({backdropDesc: '對話後方那張淡淡的雕像圖片。',userBubbleTitle: '訊息氣泡',userBubbleDesc: '你自己的訊息有多透明。0 為不透明,100 時只保留邊框。',+ textDirectionTitle: '文字方向',+ textDirectionDesc:+ '設定聊天訊息和輸入框的文字方向。「自動」依每段的第一個字母判斷;混合文字排列不對時,可手動選擇方向。程式碼一律從左到右顯示。',+ textDirection: { auto: '自動', rtl: '從右到左', ltr: '從左到右' },introSplashTitle: '開場標識',introSplashDesc: '空白對話中顯示的字標和提示語。',reactionsTitle: '訊息回應',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 70d0fbbf21b..41eb6100dc8 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -801,6 +801,10 @@ export const zh = defineLocale({backdropDesc: '对话后方那张淡淡的雕像图片。',userBubbleTitle: '消息气泡',userBubbleDesc: '你自己的消息有多透明。0 为不透明,100 时只保留边框。',+ textDirectionTitle: '文本方向',+ textDirectionDesc:+ '设置聊天消息和输入框的文字方向。“自动”根据每段的第一个字母判断;混合文本排列不对时,可手动选择方向。代码始终从左到右显示。',+ textDirection: { auto: '自动', rtl: '从右到左', ltr: '从左到右' },introSplashTitle: '开场标识',introSplashDesc: '空白对话中显示的字标和提示语。',reactionsTitle: '消息回应',diff --git a/apps/desktop/src/store/text-direction.ts b/apps/desktop/src/store/text-direction.tsnew file mode 100644index 00000000000..781ce8fffa4--- /dev/null+++ b/apps/desktop/src/store/text-direction.ts@@ -0,0 +1,45 @@+import { useStore } from '@nanostores/react'++import { type Codec, persistentAtom } from '@/lib/persisted'++/**+ * How chat prose and the composers pick their base direction.+ *+ * - `auto`: each block resolves its own direction from its first strong+ * character (the `unicode-bidi: plaintext` rules in styles.css). This is the+ * shipped behavior and adds no attribute to the DOM.+ * - `rtl` / `ltr`: the reader's explicit choice, for text whose first strong+ * character does not reflect its language — an Arabic paragraph that opens+ * with a Latin name, or an English one that opens with an Arabic quote. Code+ * (fenced and inline) and KaTeX stay isolated LTR either way.+ */+export type TextDirection = 'auto' | 'ltr' | 'rtl'++export const TEXT_DIRECTIONS = ['auto', 'rtl', 'ltr'] as const satisfies readonly TextDirection[]++// Scope: global to this desktop install (every window and profile). It is a+// reading preference about the person at the keyboard, not about a backend,+// profile or session, so no connection/profile segment belongs in the key.+const STORAGE_KEY = 'hermes.desktop.textDirection'++// Auto is stored as absence, so users who never touch the setting keep an+// untouched storage record as well as today's rendering.+const textDirectionCodec: Codec<TextDirection> = {+ decode: raw => (raw === 'rtl' || raw === 'ltr' ? raw : 'auto'),+ encode: value => (value === 'auto' ? null : value)+}++export const $textDirection = persistentAtom<TextDirection>(STORAGE_KEY, 'auto', textDirectionCodec)++export function setTextDirection(direction: TextDirection) {+ $textDirection.set(direction)+}++/** The `dir` value to stamp on chat prose/composers; undefined keeps Auto attribute-free. */+export function forcedTextDirection(direction: TextDirection): 'ltr' | 'rtl' | undefined {+ return direction === 'auto' ? undefined : direction+}++export function useForcedTextDirection(): 'ltr' | 'rtl' | undefined {+ return forcedTextDirection(useStore($textDirection))+}diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.cssindex bf8f079ecba..b492e4b93a6 100644--- a/apps/desktop/src/styles.css+++ b/apps/desktop/src/styles.css@@ -1674,6 +1674,24 @@ body.guest-pointer-lock :is(webview, iframe) {text-align: start;}+/* Appearance → Text direction. An explicit RTL/LTR choice stamps dir on the+ markdown root, each user line block and both composers; the first-strong+ plaintext vote is exactly what the reader overrode, so it steps aside and+ every block takes the chosen direction (every line of a multi-line draft+ included). Auto stamps no dir, so nothing here matches. Code and KaTeX keep+ their isolated-LTR rules below. */+[data-slot='aui_assistant-message-content'] .aui-md[dir] :where(p, h1, h2, h3, h4, h5, h6, li, blockquote),+[data-slot='aui_user-inline-text'][dir],+[data-slot='composer-rich-input'][dir] {+ unicode-bidi: normal;+}++/* Header cells pin text-left for the Auto (LTR-box) table; a chosen direction+ aligns headers and cells to its own start edge instead. */+[data-slot='aui_assistant-message-content'] .aui-md[dir] :where(th, td) {+ text-align: start;+}+/* Inline code/KaTeX don't vote on direction and keep their own order: isolatemakes bidi treat each as one neutral, so a block that *starts* with `./run.sh`then Arabic still resolves RTL, and the command's neutrals (dots/slashes)