diff --git a/apps/desktop/src/app/session/hooks/use-hermes-config.ts b/apps/desktop/src/app/session/hooks/use-hermes-config.ts index ebf6a85dd9..a4ce3785b0 100644 --- a/apps/desktop/src/app/session/hooks/use-hermes-config.ts +++ b/apps/desktop/src/app/session/hooks/use-hermes-config.ts @@ -22,6 +22,7 @@ import { applyThinkingSoundFromConfig, applyVoiceStopPhraseFromConfig } from '@/store/voice-prefs' +import { setChatFontFamilyFromConfig } from '@/themes/chat-font' const DEFAULT_VOICE_SECONDS = 120 const FAST_TIERS = new Set(['fast', 'priority', 'on']) @@ -140,6 +141,7 @@ export function useHermesConfig({ activeSessionIdRef }: HermesConfigOptions) { setDisplayTimestampsFromConfig(config.display?.timestamps) setTerminalFontFamilyFromConfig(config.terminal?.font_family) + setChatFontFamilyFromConfig(config.desktop?.font_family) if (!canPublish()) { return diff --git a/apps/desktop/src/app/settings/appearance-settings.tsx b/apps/desktop/src/app/settings/appearance-settings.tsx index aefcf3e249..5f87600a84 100644 --- a/apps/desktop/src/app/settings/appearance-settings.tsx +++ b/apps/desktop/src/app/settings/appearance-settings.tsx @@ -63,6 +63,7 @@ import { $marketplaceInstalls, isUserTheme, removeUserTheme } from '@/themes/use import { setHermesConfigCache, useHermesConfigRecord } from '../hooks/use-config-record' +import { ChatFontSetting } from './chat-font-setting' import { MODE_OPTIONS } from './constants' import { setNested } from './helpers' import { PetSettings } from './pet-settings' @@ -642,6 +643,8 @@ export function AppearanceSettings() { title={a.uiScaleTitle} /> + + ({ + cache: vi.fn(), + loadedConfig: {} as Record, + notifyError: vi.fn(), + save: vi.fn() +})) + +vi.mock('@/hermes', () => ({ + saveHermesConfig: (config: Record) => mocks.save(config) +})) + +vi.mock('@/i18n', () => ({ + useI18n: () => ({ + t: { + settings: { + appearance: { + chatFontDesc: 'Choose a font.', + chatFontPlaceholder: 'OpenDyslexic or a CSS font stack', + chatFontPreview: 'Preview', + chatFontReset: 'Use theme font', + chatFontSample: 'The quick brown fox', + chatFontTitle: 'Chat Font' + }, + config: { autosaveFailed: 'Autosave failed' } + } + } + }) +})) + +vi.mock('@/store/notifications', () => ({ + notifyError: (...args: unknown[]) => mocks.notifyError(...args) +})) + +vi.mock('../hooks/use-config-record', () => ({ + setHermesConfigCache: (config: Record) => mocks.cache(config), + useHermesConfigRecord: () => ({ data: mocks.loadedConfig }) +})) + +vi.mock('../hooks/use-on-profile-switch', () => ({ + useOnProfileSwitch: () => {} +})) + +async function flushAutosave() { + await act(async () => { + vi.advanceTimersByTime(550) + await Promise.resolve() + await Promise.resolve() + }) +} + +describe('ChatFontSetting', () => { + beforeEach(() => { + vi.useFakeTimers() + mocks.loadedConfig = { desktop: { font_family: '', repo_scan_enabled: true } } + mocks.save.mockResolvedValue({ ok: true }) + $chatFontFamily.set('') + }) + + afterEach(() => { + cleanup() + vi.clearAllMocks() + vi.useRealTimers() + }) + + it('publishes the live family and persists only desktop.font_family, keeping sibling keys', async () => { + render() + + fireEvent.change(screen.getByRole('combobox', { name: 'Chat Font' }), { target: { value: 'OpenDyslexic' } }) + expect($chatFontFamily.get()).toBe('OpenDyslexic') + + await flushAutosave() + + expect(mocks.save).toHaveBeenCalledWith({ desktop: { font_family: 'OpenDyslexic' } }) + expect(mocks.cache).toHaveBeenCalledWith({ desktop: { font_family: 'OpenDyslexic', repo_scan_enabled: true } }) + }) + + it('rolls back the optimistic family when autosave fails', async () => { + mocks.loadedConfig = { desktop: { font_family: 'Lexend' } } + mocks.save.mockRejectedValue(new Error('disk full')) + render() + const input = screen.getByRole('combobox', { name: 'Chat Font' }) as HTMLInputElement + + fireEvent.change(input, { target: { value: 'OpenDyslexic' } }) + await flushAutosave() + + expect(input.value).toBe('Lexend') + expect($chatFontFamily.get()).toBe('Lexend') + expect(mocks.notifyError).toHaveBeenCalledWith(expect.any(Error), 'Autosave failed') + }) +}) + +describe('resolveChatFontFamily', () => { + const theme = '"Segoe UI", system-ui, sans-serif' + + it('layers a bare family in front of the theme stack and leaves the theme alone when empty', () => { + expect(resolveChatFontFamily('', theme)).toBe(theme) + expect(resolveChatFontFamily(' ', theme)).toBe(theme) + expect(resolveChatFontFamily('OpenDyslexic', theme)).toBe(`'OpenDyslexic', ${theme}`) + expect(resolveChatFontFamily("'Atkinson Hyperlegible', serif", theme)).toBe(`'Atkinson Hyperlegible', serif, ${theme}`) + }) +}) diff --git a/apps/desktop/src/app/settings/chat-font-setting.tsx b/apps/desktop/src/app/settings/chat-font-setting.tsx new file mode 100644 index 0000000000..dbd1f4e7b0 --- /dev/null +++ b/apps/desktop/src/app/settings/chat-font-setting.tsx @@ -0,0 +1,153 @@ +import { useEffect, useRef, useState } from 'react' + +import { Button } from '@/components/ui/button' +import { Input } from '@/components/ui/input' +import { saveHermesConfig } from '@/hermes' +import { useI18n } from '@/i18n' +import { notifyError } from '@/store/notifications' +import { CHAT_FONT_SUGGESTIONS, normalizeChatFontFamily, setChatFontFamilyFromConfig } from '@/themes/chat-font' +import type { HermesConfigRecord } from '@/types/hermes' + +import { setHermesConfigCache, useHermesConfigRecord } from '../hooks/use-config-record' +import { useOnProfileSwitch } from '../hooks/use-on-profile-switch' + +import { getNested, setNested } from './helpers' +import { ListRow } from './primitives' + +const AUTOSAVE_DELAY_MS = 550 +const CONFIG_PATH = 'desktop.font_family' + +function fontFamilyFromConfig(config: HermesConfigRecord): string { + return normalizeChatFontFamily(getNested(config, CONFIG_PATH)) +} + +/** + * Chat / UI face picker. Same seed → autosave → rollback contract as + * `TerminalFontSetting`; the live value publishes through `$chatFontFamily` + * so the theme paint (`--dt-font-sans`) follows every keystroke. + */ +export function ChatFontSetting() { + const { t } = useI18n() + const copy = t.settings.appearance + const { data: loadedConfig } = useHermesConfigRecord() + const [draft, setDraft] = useState(null) + const [staleConfig, setStaleConfig] = useState(null) + const [saveVersion, setSaveVersion] = useState(0) + const saveVersionRef = useRef(0) + + const cancelPendingSave = () => { + saveVersionRef.current = 0 + } + + useEffect(() => { + if (!loadedConfig || draft !== null || loadedConfig === staleConfig) { + return + } + + const value = fontFamilyFromConfig(loadedConfig) + setDraft(value) + setChatFontFamilyFromConfig(value) + }, [draft, loadedConfig, staleConfig]) + + useOnProfileSwitch(() => { + saveVersionRef.current += 1 + setDraft(null) + setStaleConfig(loadedConfig ?? null) + setSaveVersion(0) + setChatFontFamilyFromConfig('') + }) + + useEffect(() => { + if (draft === null || saveVersion === 0 || !loadedConfig) { + return + } + + const version = saveVersion + const value = normalizeChatFontFamily(draft) + + if (value === fontFamilyFromConfig(loadedConfig)) { + return + } + + const rollback = fontFamilyFromConfig(loadedConfig) + + const timeout = window.setTimeout(() => { + const next = setNested(loadedConfig, CONFIG_PATH, value) + + // Sparse patch: PUT /api/config deep-merges; echoing the cached snapshot + // would overwrite keys other surfaces changed since it loaded. + void saveHermesConfig(setNested({}, CONFIG_PATH, value)) + .then(result => { + if (!result.ok) { + throw new Error(t.settings.config.autosaveFailed) + } + + if (saveVersionRef.current !== version) { + return + } + + setHermesConfigCache(next) + }) + .catch(error => { + if (saveVersionRef.current !== version) { + return + } + + cancelPendingSave() + setSaveVersion(0) + setDraft(rollback) + setChatFontFamilyFromConfig(rollback) + notifyError(error, t.settings.config.autosaveFailed) + }) + }, AUTOSAVE_DELAY_MS) + + return () => window.clearTimeout(timeout) + }, [draft, loadedConfig, saveVersion, t.settings.config.autosaveFailed]) + + const update = (value: string) => { + saveVersionRef.current += 1 + setDraft(value) + setSaveVersion(saveVersionRef.current) + setChatFontFamilyFromConfig(value) + } + + const value = draft ?? '' + + return ( + +
+ update(event.target.value)} + placeholder={copy.chatFontPlaceholder} + value={value} + /> + +
+ + {CHAT_FONT_SUGGESTIONS.map(font => ( + + {/* Inherits --dt-font-sans, so it IS the live result, not a simulation. */} +
+ + {copy.chatFontPreview} + + {copy.chatFontSample} +
+ + } + description={copy.chatFontDesc} + title={copy.chatFontTitle} + wide + /> + ) +} diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts index 562a864a9d..f54453e3c4 100644 --- a/apps/desktop/src/i18n/en.ts +++ b/apps/desktop/src/i18n/en.ts @@ -725,6 +725,13 @@ export const en: Translations = { terminalFontPlaceholder: 'MesloLGS NF or a CSS font stack', terminalFontPreview: 'Glyph preview', terminalFontReset: 'Use default', + chatFontTitle: 'Chat Font', + chatFontDesc: + 'Choose an installed font for chat and the rest of the app. Handy for readability faces such as OpenDyslexic; leave blank to use the theme\'s font.', + chatFontPlaceholder: 'OpenDyslexic or a CSS font stack', + chatFontPreview: 'Preview', + chatFontSample: 'The quick brown fox jumps over the lazy dog. 0123456789', + chatFontReset: 'Use theme font', translucencyTitle: 'Window Translucency', translucencyDesc: 'See your desktop through the whole window, text and all. Tuned separately for light and dark.', translucencyGlassDesc: diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.ts index 61dddd8668..636d5e6173 100644 --- a/apps/desktop/src/i18n/ja.ts +++ b/apps/desktop/src/i18n/ja.ts @@ -513,6 +513,13 @@ export const ja = defineLocale({ terminalFontPlaceholder: 'MesloLGS NF または CSS フォントスタック', terminalFontPreview: 'グリフのプレビュー', terminalFontReset: '既定値を使用', + chatFontTitle: 'チャットフォント', + chatFontDesc: + 'チャットとアプリ全体に使うインストール済みフォントを選択します。OpenDyslexic などの読みやすいフォントに便利です。空欄ならテーマのフォントを使います。', + chatFontPlaceholder: 'OpenDyslexic または CSS フォントスタック', + chatFontPreview: 'プレビュー', + chatFontSample: 'いろはにほへと ちりぬるを 0123456789', + chatFontReset: 'テーマのフォントを使用', translucencyTitle: 'ウィンドウの透過', translucencyDesc: 'テキストも含めウィンドウ全体を透過させてデスクトップを表示します。', translucencyGlassDesc: 'マットガラス: デスクトップが滑らかなぼかしとして透け、テキストは鮮明なまま。', diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.ts index c44c37ea2e..0862449f1b 100644 --- a/apps/desktop/src/i18n/ru.ts +++ b/apps/desktop/src/i18n/ru.ts @@ -581,6 +581,13 @@ export const ru = defineLocale({ terminalFontPlaceholder: 'MesloLGS NF или CSS-стек шрифтов', terminalFontPreview: 'Предпросмотр глифов', terminalFontReset: 'Использовать по умолчанию', + chatFontTitle: 'Шрифт чата', + chatFontDesc: + 'Выберите установленный шрифт для чата и всего интерфейса. Удобно для шрифтов повышенной читаемости, например OpenDyslexic; оставьте пустым, чтобы использовать шрифт темы.', + chatFontPlaceholder: 'OpenDyslexic или CSS-стек шрифтов', + chatFontPreview: 'Предпросмотр', + chatFontSample: 'Съешь же ещё этих мягких французских булок. 0123456789', + chatFontReset: 'Шрифт темы', translucencyTitle: 'Полупрозрачность окна', translucencyDesc: 'Рабочий стол виден сквозь всё окно, включая текст. Отдельная настройка для светлой и тёмной тем.', diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts index 788143ab91..134a12361a 100644 --- a/apps/desktop/src/i18n/types.ts +++ b/apps/desktop/src/i18n/types.ts @@ -607,6 +607,12 @@ export interface Translations { terminalFontPlaceholder: string terminalFontPreview: string terminalFontReset: string + chatFontTitle: string + chatFontDesc: string + chatFontPlaceholder: string + chatFontPreview: string + chatFontSample: string + chatFontReset: string translucencyTitle: string translucencyDesc: string translucencyGlassDesc: string diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.ts index 846b41d5ec..e87601c50c 100644 --- a/apps/desktop/src/i18n/zh-hant.ts +++ b/apps/desktop/src/i18n/zh-hant.ts @@ -497,6 +497,12 @@ export const zhHant = defineLocale({ terminalFontPlaceholder: 'MesloLGS NF 或 CSS 字型堆疊', terminalFontPreview: '字形預覽', terminalFontReset: '使用預設字型', + chatFontTitle: '聊天字型', + chatFontDesc: '為聊天與應用程式介面選擇已安裝的字型,適合 OpenDyslexic 等易讀字型;留空則使用主題字型。', + chatFontPlaceholder: 'OpenDyslexic 或 CSS 字型堆疊', + chatFontPreview: '預覽', + chatFontSample: '敏捷的棕色狐狸跳過懶狗。0123456789', + chatFontReset: '使用主題字型', translucencyTitle: '視窗透明', translucencyDesc: '讓整個視窗(包括文字)透出桌面。', translucencyGlassDesc: '霧面玻璃:桌面以柔和模糊透出,文字保持清晰。', diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts index b8ed05784f..63d358eab5 100644 --- a/apps/desktop/src/i18n/zh.ts +++ b/apps/desktop/src/i18n/zh.ts @@ -701,6 +701,12 @@ export const zh = defineLocale({ terminalFontPlaceholder: 'MesloLGS NF 或 CSS 字体栈', terminalFontPreview: '字形预览', terminalFontReset: '使用默认字体', + chatFontTitle: '聊天字体', + chatFontDesc: '为聊天及应用界面选择已安装的字体,适合 OpenDyslexic 等易读字体;留空则使用主题字体。', + chatFontPlaceholder: 'OpenDyslexic 或 CSS 字体栈', + chatFontPreview: '预览', + chatFontSample: '敏捷的棕色狐狸跳过懒狗。0123456789', + chatFontReset: '使用主题字体', translucencyTitle: '窗口透明', translucencyDesc: '让整个窗口(包括文字)透出桌面。', translucencyGlassDesc: '磨砂玻璃:桌面以柔和模糊透出,文字保持清晰。', diff --git a/apps/desktop/src/themes/chat-font.ts b/apps/desktop/src/themes/chat-font.ts new file mode 100644 index 0000000000..31a949e01f --- /dev/null +++ b/apps/desktop/src/themes/chat-font.ts @@ -0,0 +1,45 @@ +import { atom } from 'nanostores' + +/** Families users ask for by name; the app face is otherwise whatever the theme declares. */ +export const CHAT_FONT_SUGGESTIONS = [ + 'OpenDyslexic', + 'Atkinson Hyperlegible', + 'Lexend', + 'Inter', + 'IBM Plex Sans', + 'Source Sans 3', + 'Noto Sans', + 'Segoe UI', + 'SF Pro Text' +] as const + +/** The profile-backed value as written in config.yaml. Empty means the theme's face. */ +export const $chatFontFamily = atom('') + +export function normalizeChatFontFamily(value: unknown): string { + return typeof value === 'string' ? value.trim() : '' +} + +function quoteSingleFamily(value: string): string { + return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'` +} + +/** + * Accept a friendly single family name or an authored CSS font stack; the + * theme's own stack stays behind it so missing glyphs (CJK, emoji) still resolve. + */ +export function resolveChatFontFamily(value: unknown, themeFontSans: string): string { + const configured = normalizeChatFontFamily(value) + + if (!configured) { + return themeFontSans + } + + const preferred = configured.includes(',') || /['"]/.test(configured) ? configured : quoteSingleFamily(configured) + + return `${preferred}, ${themeFontSans}` +} + +export function setChatFontFamilyFromConfig(value: unknown): void { + $chatFontFamily.set(normalizeChatFontFamily(value)) +} diff --git a/apps/desktop/src/themes/context.tsx b/apps/desktop/src/themes/context.tsx index cc556225af..5c65b145cd 100644 --- a/apps/desktop/src/themes/context.tsx +++ b/apps/desktop/src/themes/context.tsx @@ -21,6 +21,7 @@ import { setAppearance } from '@/store/translucency' import { $accentOverride } from './accent-override' import { $backendThemes, $pendingSkinApply } from './backend-sync' +import { $chatFontFamily, resolveChatFontFamily } from './chat-font' import { harmonize, readableInk } from './color' import { BUILTIN_THEME_LIST, DEFAULT_SKIN_NAME, DEFAULT_TYPOGRAPHY, nousTheme } from './presets' import { retintTheme } from './retint' @@ -206,7 +207,7 @@ const mixesFor = (isDark: boolean): Record => ({ '--theme-mix-bubble': isDark ? '46%' : '0%' }) -function applyTheme(theme: DesktopTheme, mode: 'light' | 'dark') { +function applyTheme(theme: DesktopTheme, mode: 'light' | 'dark', chatFontFamily = $chatFontFamily.get()) { if (typeof document === 'undefined') { return } @@ -275,7 +276,7 @@ function applyTheme(theme: DesktopTheme, mode: 'light' | 'dark') { // `harmonize`); a blue one turns the sidebar's finished dots teal rather // than leaving eight emerald spots fighting the theme. '--ui-success': harmonize('#10b981', midground, 0.25), - '--dt-font-sans': typo.fontSans, + '--dt-font-sans': resolveChatFontFamily(chatFontFamily, typo.fontSans), '--dt-font-mono': typo.fontMono, '--noise-opacity-mul': isDark ? 'calc(0.04 / 0.21)' : 'calc(0.34 / 0.21)' } @@ -477,7 +478,11 @@ export function ThemeProvider({ children }: { children: ReactNode }) { // What actually gets painted (matches the `.dark` class applyTheme toggles). const renderedMode = useMemo(() => renderedModeFor(paintedTheme.colors, paintedMode), [paintedTheme, paintedMode]) - useEffect(() => applyTheme(paintedTheme, paintedMode), [paintedTheme, paintedMode]) + // The chat face rides on the theme paint: the config-backed family is layered + // in front of the theme's own stack, so an empty value is exactly the theme. + const chatFontFamily = useStore($chatFontFamily) + + useEffect(() => applyTheme(paintedTheme, paintedMode, chatFontFamily), [paintedTheme, paintedMode, chatFontFamily]) // Keep the native window appearance pinned to the app theme (vibrancy // material, titlebar, new-window pre-paint background). diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts index a65b43b97e..eac2e664a7 100644 --- a/apps/desktop/src/types/hermes.ts +++ b/apps/desktop/src/types/hermes.ts @@ -415,6 +415,7 @@ export interface HermesConfig { timestamps?: boolean } desktop?: { + font_family?: string repo_scan_enabled?: boolean repo_scan_roots?: string[] repo_scan_exclude_paths?: string[] diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py index 2d759a2251..c6dbf284ce 100644 --- a/hermes_cli/config_defaults.py +++ b/hermes_cli/config_defaults.py @@ -2331,6 +2331,10 @@ DEFAULT_CONFIG = { "extra_allowed_hosts": [], }, "desktop": { # Hermes Desktop (Electron) launch options; only affect `hermes desktop`. + # CSS font-family for the app's chat and UI text (e.g. "OpenDyslexic"). Layered in front + # of the active theme's own sans stack so missing glyphs still fall through. Empty = the + # theme's face. The terminal pane is terminal.font_family. + "font_family": "", # Git repo discovery for the Projects sidebar; empty roots = bounded scan of $HOME. "repo_scan_enabled": True, "repo_scan_roots": [], diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md index b73afaadd5..fc70c52a3d 100644 --- a/website/docs/user-guide/configuration.md +++ b/website/docs/user-guide/configuration.md @@ -229,6 +229,8 @@ swept hourly by gateway housekeeping and once per process on CLI-only installs. Set `temp_dir` to an existing absolute path to redirect session temp anywhere else; user-set paths are never auto-pruned. +`desktop.font_family` sets the font for chat and the rest of the Hermes Desktop interface (the terminal pane has its own key above). Give it one installed family name (for example, `OpenDyslexic` or `Atkinson Hyperlegible`) or a CSS font stack; Hermes keeps the active theme's own stack behind it so CJK and emoji glyphs still resolve, and an empty value uses the theme's font. Edit it in **Settings → Appearance → Chat Font**. + `terminal.font_family` controls the embedded terminal in Hermes Desktop. It accepts either one locally installed family name (for example, `MesloLGS NF`) or a CSS font stack. Hermes appends its bundled JetBrains Mono stack as a fallback, and an empty value keeps the default. You can edit the same profile-scoped setting in **Settings → Appearance → Terminal Font**; no Google Fonts download or system-font permission is required. For cloud sandboxes such as Modal, Daytona, and Vercel Sandbox, `container_persistent: true` means Hermes will try to preserve filesystem state across sandbox recreation. It does not promise that the same live sandbox, PID space, or background processes will still be running later. diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md index 01e448ac15..d360173c66 100644 --- a/website/docs/user-guide/desktop.md +++ b/website/docs/user-guide/desktop.md @@ -69,6 +69,13 @@ The bar along the bottom of the chat shows live session state and exposes quick Chatting against a Hermes instance on another machine instead of the bundled local backend? See [Connecting to a remote backend](#connecting-to-a-remote-backend) below — and for the full picture of how the remote-hosted dashboard connection works (the auth gate, the `/api/ws` chat socket, and WebSocket close-code triage), see [Web Dashboard → Connecting Hermes Desktop to a remote backend](./features/web-dashboard.md#connecting-hermes-desktop-to-a-remote-backend). +#### Fonts + +Two independent font settings live in **Settings → Appearance**, both stored per profile in `config.yaml`: + +- **Chat Font** (`desktop.font_family`) — chat and the rest of the app's UI. Readability faces such as OpenDyslexic or Atkinson Hyperlegible work as soon as they are installed on the system; the active theme's stack stays behind your pick so missing glyphs still render. Blank means the theme's font. +- **Terminal Font** (`terminal.font_family`) — the embedded terminal pane; Nerd Fonts render shell icons here. Blank means the bundled JetBrains Mono. + #### Repository discovery Hermes Desktop discovers local Git repositories for the Projects sidebar by scanning your home directory to a bounded depth. You can change this per profile in **Settings → Workspace**, or in `config.yaml`: