Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(settings): add global interface font setting and per-locale font stacks (#18712)

Innei2164a2343d8a
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index a810beebc6d..649972a6cc6 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -1225,6 +1225,23 @@ outside the harness's remit: mark the dark case untested and say why, rather tha
flipping a device-level preference. Note the setting write is not free — it syncs to
the account and affects other surfaces; restore it (`auto`) at teardown if you set it.
+#### A cold desktop boot renders English copy while `status.language` already says zh-CN
+
+**Situation:** asserting anything about localized UI copy on a freshly started
+`electron-dev.sh` instance — a label's text, or that a settings section rendered at all.
+
+**Doesn't work:** grepping the rendered text for the Chinese label while
+`window.__LOBE_STORES.global().status.language` reports `zh-CN`. The persisted language is
+restored into the store, but i18next is still on English until `switchLocale` runs once, so every
+Chinese-text assertion comes back false and reads as "the section never rendered". A full-reload
+`goto` puts it back into that state, so it recurs mid-run after each navigation.
+
+**Works:** never infer the rendered language from `status.language`. Decide from the DOM
+(test for both the Chinese and English label, or read a known-localized node), or normalize first
+by calling `window.__LOBE_STORES.global().switchLocale('<locale>')` — the same action the language
+select calls — and only then assert. When the check under test IS the language, drive the real
+select, and re-read `status.language` plus the DOM copy after every switch: the two can disagree.
+
#### `app-probe.sh goto /` cannot reach the desktop Home route — seed the tab first
**Situation:** driving the Electron shell to the Home route (`/`) to check the nav
@@ -1272,6 +1289,16 @@ On `cloud`, verify open / render / close only, treat every submit as a user-owne
prove afterwards that nothing was written (re-read the relevant store count). Note this also makes
the whole local-server bring-up unnecessary — check the target before spending minutes on it.
+**Corollary — a preference key your branch ADDS cannot be proven to persist here.** The cloud
+server validates `user.updatePreference` against its own deployed `UserPreferenceSchema`, so a key
+that exists only in your working tree is accepted with HTTP 200 and then silently dropped: the
+next `user.getUserState` comes back without it and a reload shows the setting reverted, which
+reads exactly like a broken write path. Attribute it before reporting a defect — wrap `fetch`,
+confirm the request body carries the key, and confirm an ALREADY-shipped sibling key
+(`terminalFontFamily`) round-trips in the same response. Then mark persistence blocked on the
+server schema version rather than failing the change; only a local full stack running the branch's
+schema can close that loop.
+
#### A global `indexedDB.open` stall holds the boot on web but kills the Electron renderer
**Situation:** needing to freeze the boot at a pre-app phase long enough to capture it,
diff --git a/apps/desktop/src/main/controllers/SystemCtr.ts b/apps/desktop/src/main/controllers/SystemCtr.ts
index 2c74bfd7e0c..390f3fc213b 100644
--- a/apps/desktop/src/main/controllers/SystemCtr.ts
+++ b/apps/desktop/src/main/controllers/SystemCtr.ts
@@ -23,14 +23,14 @@ import RemoteServerConfigCtr from './RemoteServerConfigCtr';
const logger = createLogger('controllers:SystemCtr');
-interface SystemMonospaceFont {
+interface SystemFont {
label: string;
value: string;
}
export default class SystemController extends ControllerModule {
static override readonly groupName = 'system';
- private systemMonospaceFontsPromise?: Promise<SystemMonospaceFont[]>;
+ private systemFontsPromises = new Map<string, Promise<SystemFont[]>>();
private systemThemeListenerInitialized = false;
/**
@@ -236,34 +236,46 @@ export default class SystemController extends ControllerModule {
}
@IpcMethod()
- async getSystemMonospaceFonts(): Promise<SystemMonospaceFont[]> {
- if (!this.systemMonospaceFontsPromise) {
- this.systemMonospaceFontsPromise = import('font-list')
- .then(({ getFonts2 }) => getFonts2())
- .then((fonts) => {
- const families = new Map<string, SystemMonospaceFont>();
-
- for (const font of fonts) {
- const label = font.name.trim();
- const value = font.familyName.trim();
- if (!font.monospace || !label || !value) continue;
-
- const normalizedName = label.toLocaleLowerCase();
- if (!families.has(normalizedName)) families.set(normalizedName, { label, value });
- }
-
- return [...families.values()].sort((left, right) =>
- left.label.localeCompare(right.label),
- );
- })
- .catch((error) => {
- this.systemMonospaceFontsPromise = undefined;
- logger.error('Failed to enumerate system monospace fonts:', error);
- throw error;
- });
- }
+ async getSystemMonospaceFonts(): Promise<SystemFont[]> {
+ return this.loadSystemFonts(true);
+ }
+
+ @IpcMethod()
+ async getSystemFonts(): Promise<SystemFont[]> {
+ return this.loadSystemFonts(false);
+ }
+
+ private loadSystemFonts(monospaceOnly: boolean): Promise<SystemFont[]> {
+ const cacheKey = monospaceOnly ? 'monospace' : 'all';
+ let cached = this.systemFontsPromises.get(cacheKey);
+ if (cached) return cached;
+
+ cached = import('font-list')
+ .then(({ getFonts2 }) => getFonts2())
+ .then((fonts) => {
+ const families = new Map<string, SystemFont>();
+
+ for (const font of fonts) {
+ const label = font.name.trim();
+ const value = font.familyName.trim();
+ if (!label || !value) continue;
+ if (monospaceOnly && !font.monospace) continue;
+
+ const normalizedName = label.toLocaleLowerCase();
+ if (!families.has(normalizedName)) families.set(normalizedName, { label, value });
+ }
+
+ return [...families.values()].sort((left, right) => left.label.localeCompare(right.label));
+ })
+ .catch((error) => {
+ this.systemFontsPromises.delete(cacheKey);
+ logger.error('Failed to enumerate system fonts:', error);
+ throw error;
+ });
+
+ this.systemFontsPromises.set(cacheKey, cached);
- return this.systemMonospaceFontsPromise;
+ return cached;
}
@IpcMethod()
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 7bd0cb83e28..3c00771f348 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -898,6 +898,17 @@
"settingAppearance.contextMenuMode.disabled": "Disabled",
"settingAppearance.contextMenuMode.title": "Right-Click Menu Mode",
"settingAppearance.desktop.title": "Desktop",
+ "settingAppearance.font.fontFamily.default": "System Default",
+ "settingAppearance.font.fontFamily.desc": "Choose a font installed on this device for the whole interface. System Default follows the built-in font stack of your current language.",
+ "settingAppearance.font.fontFamily.loadError": "System fonts could not be loaded. System Default remains available.",
+ "settingAppearance.font.fontFamily.title": "Interface Font",
+ "settingAppearance.font.fontFamily.unavailable": "{{font}} (Unavailable on this device)",
+ "settingAppearance.font.monospace.default": "System Default",
+ "settingAppearance.font.monospace.desc": "Used by code blocks and the built-in terminal. Choose a monospaced font installed on this device.",
+ "settingAppearance.font.monospace.loadError": "System fonts could not be loaded. System Default remains available.",
+ "settingAppearance.font.monospace.title": "Monospace Font",
+ "settingAppearance.font.monospace.unavailable": "{{font}} (Unavailable on this device)",
+ "settingAppearance.font.title": "Font",
"settingAppearance.neutralColor.desc": "Custom grayscale with different color tendencies",
"settingAppearance.neutralColor.title": "Neutral Color",
"settingAppearance.noAnimation.desc": "Disable all animation effects in the application",
@@ -905,12 +916,6 @@
"settingAppearance.preview.title": "Color Palette",
"settingAppearance.primaryColor.desc": "Custom theme color",
"settingAppearance.primaryColor.title": "Theme Color",
- "settingAppearance.terminal.fontFamily.default": "Application Default",
- "settingAppearance.terminal.fontFamily.desc": "Choose a monospaced font installed on this device. Select Application Default to use the application code font.",
- "settingAppearance.terminal.fontFamily.loadError": "System fonts could not be loaded. Application Default remains available.",
- "settingAppearance.terminal.fontFamily.title": "Monospace Font",
- "settingAppearance.terminal.fontFamily.unavailable": "{{font}} (Unavailable on this device)",
- "settingAppearance.terminal.title": "Terminal",
"settingAppearance.title": "Application Appearance",
"settingChat.chatStyleType.title": "Chat Window Style",
"settingChat.chatStyleType.type.chat": "Conversation Mode",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 8c1eff50207..48f2d4db106 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -898,6 +898,17 @@
"settingAppearance.contextMenuMode.disabled": "不使用",
"settingAppearance.contextMenuMode.title": "右键菜单方案",
"settingAppearance.desktop.title": "桌面",
+ "settingAppearance.font.fontFamily.default": "跟随系统",
+ "settingAppearance.font.fontFamily.desc": "为整个界面选择本机已安装的字体。选择「跟随系统」将使用当前语言对应的内置字体方案。",
+ "settingAppearance.font.fontFamily.loadError": "无法加载系统字体,仍可选择「跟随系统」。",
+ "settingAppearance.font.fontFamily.title": "界面字体",
+ "settingAppearance.font.fontFamily.unavailable": "{{font}}(本机未安装)",
+ "settingAppearance.font.monospace.default": "跟随系统",
+ "settingAppearance.font.monospace.desc": "用于代码块与内置终端。可选择本机已安装的等宽字体。",
+ "settingAppearance.font.monospace.loadError": "无法加载系统字体,仍可选择「跟随系统」。",
+ "settingAppearance.font.monospace.title": "等宽字体",
+ "settingAppearance.font.monospace.unavailable": "{{font}}(本机未安装)",
+ "settingAppearance.font.title": "字体",
"settingAppearance.neutralColor.desc": "不同色彩倾向的灰阶自定义",
"settingAppearance.neutralColor.title": "中性色",
"settingAppearance.noAnimation.desc": "禁用应用程序中的所有动画效果",
@@ -905,12 +916,6 @@
"settingAppearance.preview.title": "调色盘",
"settingAppearance.primaryColor.desc": "自定义主题色",
"settingAppearance.primaryColor.title": "主题色",
- "settingAppearance.terminal.fontFamily.default": "应用默认字体",
- "settingAppearance.terminal.fontFamily.desc": "选择此设备已安装的等宽字体;选择“应用默认字体”时使用应用的代码字体。",
- "settingAppearance.terminal.fontFamily.loadError": "无法加载系统字体,仍可选择应用默认字体。",
- "settingAppearance.terminal.fontFamily.title": "等宽字体",
- "settingAppearance.terminal.fontFamily.unavailable": "{{font}}(此设备不可用)",
- "settingAppearance.terminal.title": "终端",
"settingAppearance.title": "应用外观",
"settingChat.chatStyleType.title": "聊天窗口样式",
"settingChat.chatStyleType.type.chat": "对话模式",
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 0ef94a761ff..47f793f351b 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -1032,6 +1032,21 @@ export default {
'settingAppearance.contextMenuMode.disabled': 'Disabled',
'settingAppearance.contextMenuMode.title': 'Right-Click Menu Mode',
'settingAppearance.desktop.title': 'Desktop',
+ 'settingAppearance.font.fontFamily.default': 'System Default',
+ 'settingAppearance.font.fontFamily.desc':
+ 'Choose a font installed on this device for the whole interface. System Default follows the built-in font stack of your current language.',
+ 'settingAppearance.font.fontFamily.loadError':
+ 'System fonts could not be loaded. System Default remains available.',
+ 'settingAppearance.font.fontFamily.title': 'Interface Font',
+ 'settingAppearance.font.fontFamily.unavailable': '{{font}} (Unavailable on this device)',
+ 'settingAppearance.font.monospace.default': 'System Default',
+ 'settingAppearance.font.monospace.desc':
+ 'Used by code blocks and the built-in terminal. Choose a monospaced font installed on this device.',
+ 'settingAppearance.font.monospace.loadError':
+ 'System fonts could not be loaded. System Default remains available.',
+ 'settingAppearance.font.monospace.title': 'Monospace Font',
+ 'settingAppearance.font.monospace.unavailable': '{{font}} (Unavailable on this device)',
+ 'settingAppearance.font.title': 'Font',
'settingAppearance.neutralColor.desc': 'Custom grayscale with different color tendencies',
'settingAppearance.neutralColor.title': 'Neutral Color',
'settingAppearance.noAnimation.desc': 'Disable all animation effects in the application',
@@ -1039,14 +1054,6 @@ export default {
'settingAppearance.preview.title': 'Color Palette',
'settingAppearance.primaryColor.desc': 'Custom theme color',
'settingAppearance.primaryColor.title': 'Theme Color',
- 'settingAppearance.terminal.fontFamily.desc':
- 'Choose a monospaced font installed on this device. Select Application Default to use the application code font.',
- 'settingAppearance.terminal.fontFamily.default': 'Application Default',
- 'settingAppearance.terminal.fontFamily.loadError':
- 'System fonts could not be loaded. Application Default remains available.',
- 'settingAppearance.terminal.fontFamily.title': 'Monospace Font',
- 'settingAppearance.terminal.fontFamily.unavailable': '{{font}} (Unavailable on this device)',
- 'settingAppearance.terminal.title': 'Terminal',
'settingAppearance.title': 'Application Appearance',
'settingChat.chatStyleType.title': 'Chat Window Style',
'settingChat.chatStyleType.type.chat': 'Conversation Mode',
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index 2ccd96283a7..278e86b5ce8 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -241,6 +241,11 @@ export interface UserPreference {
* @deprecated Use lab.enableInputMarkdown instead
*/
disableInputMarkdownRender?: boolean;
+ /**
+ * CSS font-family value used as the global default UI font.
+ * Empty or whitespace-only values fall back to the application font stack.
+ */
+ fontFamily?: string;
guide?: UserGuide;
hideSyncAlert?: boolean;
/**
@@ -334,6 +339,7 @@ export interface SSOProvider {
export const UserPreferenceSchema = z
.object({
defaultOpenInApp: z.string().optional(),
+ fontFamily: z.string().optional(),
guide: UserGuideSchema.optional(),
hideSyncAlert: z.boolean().optional(),
lab: UserLabSchema.optional(),
diff --git a/src/const/font.test.ts b/src/const/font.test.ts
new file mode 100644
index 00000000000..173d8c7fe0c
--- /dev/null
+++ b/src/const/font.test.ts
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest';
+
+import { genFontFamily } from './font';
+
+describe('genFontFamily', () => {
+ it('puts japanese families ahead of the SC fallback for ja-JP', () => {
+ const stack = genFontFamily({ locale: 'ja-JP' });
+
+ expect(stack.indexOf('"Hiragino Sans"')).toBeGreaterThan(-1);
+ expect(stack.indexOf('"Hiragino Sans"')).toBeLessThan(stack.indexOf('"HarmonyOS Sans SC"'));
+ });
+
+ it('keeps the SC stack first for zh-CN and unknown locales', () => {
+ for (const locale of ['zh-CN', 'de-DE', undefined]) {
+ const stack = genFontFamily({ locale });
+
+ expect(stack).toContain('"HarmonyOS Sans SC"');
+ expect(stack).not.toContain('"PingFang TC"');
+ expect(stack).not.toContain('"Hiragino Sans"');
+ }
+ });
+
+ it('prefers TC families for zh-TW', () => {
+ const stack = genFontFamily({ locale: 'zh-TW' });
+
+ expect(stack.indexOf('"PingFang TC"')).toBeLessThan(stack.indexOf('"PingFang SC"'));
+ });
+
+ it('puts the user font first, then the env custom font', () => {
+ const stack = genFontFamily({
+ customFontFamily: 'Env Font',
+ locale: 'en-US',
+ userFontFamily: ' LXGW WenKai ',
+ });
+
+ expect(stack.startsWith('"LXGW WenKai","Env Font",Geist')).toBe(true);
+ });
+
+ it('leaves an already composed font-family list untouched', () => {
+ expect(
+ genFontFamily({ customFontFamily: 'Foo, "Bar Baz"' }).startsWith('Foo, "Bar Baz",Geist'),
+ ).toBe(true);
+ });
+});
diff --git a/src/const/font.ts b/src/const/font.ts
new file mode 100644
index 00000000000..4563d764c0d
--- /dev/null
+++ b/src/const/font.ts
@@ -0,0 +1,107 @@
+const FONT_EN = [
+ 'Geist',
+ '-apple-system',
+ 'BlinkMacSystemFont',
+ 'Segoe UI Variable Display',
+ 'Segoe UI',
+ 'Roboto',
+ 'Helvetica Neue',
+ 'Arial',
+];
+
+const FONT_SC = [
+ 'HarmonyOS Sans SC',
+ 'PingFang SC',
+ 'Hiragino Sans GB',
+ 'Microsoft YaHei UI',
+ 'Microsoft YaHei',
+ 'Source Han Sans SC',
+ 'Noto Sans CJK SC',
+];
+
+const FONT_TC = [
+ 'PingFang TC',
+ 'Hiragino Sans CNS',
+ 'Microsoft JhengHei UI',
+ 'Microsoft JhengHei',
+ 'Source Han Sans TC',
+ 'Noto Sans CJK TC',
+];
+
+const FONT_JP = [
+ 'Hiragino Sans',
+ 'Hiragino Kaku Gothic ProN',
+ 'Yu Gothic UI',
+ 'Yu Gothic',
+ 'Meiryo',
+ 'Source Han Sans JP',
+ 'Noto Sans CJK JP',
+];
+
+const FONT_KR = ['Apple SD Gothic Neo', 'Malgun Gothic', 'Source Han Sans KR', 'Noto Sans CJK KR'];
+
+const FONT_CODE = [
+ 'Geist Mono',
+ 'ui-monospace',
+ 'SFMono-Regular',
+ 'SF Mono',
+ 'Menlo',
+ 'Cascadia Code',
+ 'Consolas',
+ 'Liberation Mono',
+];
+
+const FALLBACK = ['ui-sans-serif', 'system-ui', 'sans-serif'];
+
+const FALLBACK_CODE = ['monospace'];
+
+const FONT_EMOJI = ['Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'];
+
+// Han glyphs differ per region, so the locale's own CJK family must win over the
+// SC families that stay in the stack as the last-resort CJK fallback.
+const LOCALE_CJK_FONTS: Record<string, string[]> = {
+ 'ja-JP': FONT_JP,
+ 'ko-KR': FONT_KR,
+ 'zh-TW': FONT_TC,
+};
+
+// user / env values may already be a full CSS font-family list, so leave those alone
+const quote = (font: string) =>
+ font.includes(',') || font.includes('"') || !font.includes(' ') ? font : `"${font}"`;
+
+interface GenFontFamilyParams {
+ customFontFamily?: string;
+ locale?: string;
+ userFontFamily?: string;
+}
+
+export const genFontFamily = ({
+ customFontFamily,
+ locale,
+ userFontFamily,
+}: GenFontFamilyParams = {}) =>
+ [
+ userFontFamily?.trim(),
+ customFontFamily?.trim(),
+ ...FONT_EN,
+ ...(locale ? (LOCALE_CJK_FONTS[locale] ?? []) : []),
+ ...FONT_SC,
+ ...FALLBACK,
+ ...FONT_EMOJI,
+ ]
+ .filter(Boolean)
+ .map((font) => quote(font as string))
+ .join(',');
+
+export const genFontFamilyCode = ({ locale, userFontFamily }: GenFontFamilyParams = {}) =>
+ [
+ userFontFamily?.trim(),
+ ...FONT_CODE,
+ ...(locale ? (LOCALE_CJK_FONTS[locale] ?? []) : []),
+ ...FONT_SC,
+ ...FALLBACK_CODE,
+ ...FONT_EMOJI,
+ ]
+ .filter(Boolean)
+ .map((font) => quote(font as string))
+ .join(',');
diff --git a/src/features/Settings/appearance/features/Font/index.tsx b/src/features/Settings/appearance/features/Font/index.tsx
new file mode 100644
index 00000000000..876b88d1eb1
--- /dev/null
+++ b/src/features/Settings/appearance/features/Font/index.tsx
@@ -0,0 +1,118 @@
+'use client';
+
+import { isDesktop } from '@lobechat/const';
+import type { FormGroupItemType } from '@lobehub/ui';
+import { Form } from '@lobehub/ui';
+import { Select } from '@lobehub/ui/base-ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AutoSaveHint from '@/components/Editor/AutoSaveHint';
+import { FORM_STYLE } from '@/const/layoutTokens';
+import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';
+import { useSaveState } from '@/hooks/useSaveState';
+import { useUserStore } from '@/store/user';
+import { preferenceSelectors } from '@/store/user/selectors';
+
+import { APPLICATION_DEFAULT_FONT, useSystemFontOptions } from '../useSystemFontOptions';
+
+const FontSettings = memo(() => {
+ const { t } = useTranslation('setting');
+ const [fontFamily, monospaceFontFamily] = useUserStore((s) => [
+ preferenceSelectors.fontFamily(s),
+ preferenceSelectors.terminalFontFamily(s),
+ ]);
+ const updatePreference = useUserStore((s) => s.updatePreference);
+ const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();
+
+ const interfaceFonts = useSystemFontOptions({
+ defaultLabel: t('settingAppearance.font.fontFamily.default'),
+ unavailableLabel: (font) => t('settingAppearance.font.fontFamily.unavailable', { font }),
+ value: fontFamily,
+ });
+ const monospaceFonts = useSystemFontOptions({
+ defaultLabel: t('settingAppearance.font.monospace.default'),
+ monospaceOnly: true,
+ unavailableLabel: (font) => t('settingAppearance.font.monospace.unavailable', { font }),
+ value: monospaceFontFamily,
+ });
+
+ const font: FormGroupItemType = {
+ children: [
+ {
+ children: (
+ <Select
+ showSearch
+ aria-label={t('settingAppearance.font.fontFamily.title')}
+ loading={interfaceFonts.isLoading}
+ options={interfaceFonts.options}
+ style={{ width: 320 }}
+ value={fontFamily || APPLICATION_DEFAULT_FONT}
+ onChange={(value: string) =>
+ save(() =>
+ updatePreference({ fontFamily: value === APPLICATION_DEFAULT_FONT ? '' : value }),
+ )
+ }
+ />
+ ),
+ desc: interfaceFonts.hasLoadError
+ ? t('settingAppearance.font.fontFamily.loadError')
+ : t('settingAppearance.font.fontFamily.desc'),
+ label: (
+ <SettingsSearchAnchor id={'appearance-font-family'}>
+ {t('settingAppearance.font.fontFamily.title')}
+ </SettingsSearchAnchor>
+ ),
+ minWidth: undefined,
+ },
+ {
+ children: (
+ <Select
+ showSearch
+ aria-label={t('settingAppearance.font.monospace.title')}
+ loading={monospaceFonts.isLoading}
+ options={monospaceFonts.options}
+ style={{ width: 320 }}
+ value={monospaceFontFamily || APPLICATION_DEFAULT_FONT}
+ onChange={(value: string) =>
+ save(() =>
+ updatePreference({
+ terminalFontFamily: value === APPLICATION_DEFAULT_FONT ? '' : value,
+ }),
+ )
+ }
+ />
+ ),
+ desc: monospaceFonts.hasLoadError
+ ? t('settingAppearance.font.monospace.loadError')
+ : t('settingAppearance.font.monospace.desc'),
+ label: (
+ <SettingsSearchAnchor id={'appearance-monospace-font'}>
+ {t('settingAppearance.font.monospace.title')}
+ </SettingsSearchAnchor>
+ ),
+ minWidth: undefined,
+ },
+ ],
+ extra: <AutoSaveHint lastUpdatedTime={lastSavedAt} saveStatus={saveStatus} onRetry={retry} />,
+ title: t('settingAppearance.font.title'),
+ };
+
+ return (
+ <Form
+ collapsible={false}
+ items={[font]}
+ itemsType={'group'}
+ variant={'filled'}
+ {...FORM_STYLE}
+ />
+ );
+});
+
+const Font = () => {
+ if (!isDesktop) return null;
+
+ return <FontSettings />;
+};
+
+export default Font;
diff --git a/src/features/Settings/appearance/features/Terminal/index.test.tsx b/src/features/Settings/appearance/features/Terminal/index.test.tsx
deleted file mode 100644
index edde06aa2d4..00000000000
--- a/src/features/Settings/appearance/features/Terminal/index.test.tsx
+++ /dev/null
@@ -1,142 +0,0 @@
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
-import type { ReactNode } from 'react';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { electronSystemService } from '@/services/electron/system';
-import { useUserStore } from '@/store/user';
-
-import Terminal from './index';
-
-vi.mock('@lobechat/const', async (importOriginal) => ({
- ...(await importOriginal()),
- isDesktop: true,
-}));
-
-vi.mock('react-i18next', () => ({
- useTranslation: () => ({ t: (key: string) => key }),
-}));
-
-vi.mock('@lobehub/ui', () => ({
- Form: ({
- items,
- }: {
- items: {
- children: { children?: ReactNode; desc?: ReactNode; label: ReactNode }[];
- title: string;
- }[];
- }) => (
- <div>
- {items.map((group) => (
- <section key={group.title}>
- <h2>{group.title}</h2>
- {group.children.map((item, index) => (
- <div key={index}>
- <span>{item.label}</span>
- <span>{item.desc}</span>
- {item.children}
- </div>
- ))}
- </section>
- ))}
- </div>
- ),
-}));
-
-vi.mock('@lobehub/ui/base-ui', () => ({
- Select: ({
- 'aria-label': ariaLabel,
- options,
- value,
- onChange,
- }: {
- 'aria-label'?: string;
- 'onChange': (value: string) => void;
- 'options': { label: string; value: string }[];
- 'value': string;
- }) => (
- <select aria-label={ariaLabel} value={value} onChange={(event) => onChange(event.target.value)}>
- {options.map((option) => (
- <option key={option.value} value={option.value}>
- {option.label}
- </option>
- ))}
- </select>
- ),
-}));
-
-vi.mock('@/components/Editor/AutoSaveHint', () => ({ default: () => null }));
-
-vi.mock('@/features/SettingsSearch/anchor', () => ({
- SettingsSearchAnchor: ({ children }: { children: ReactNode }) => <>{children}</>,
-}));
-
-vi.mock('@/hooks/useSaveState', () => ({
- useSaveState: () => ({
- lastSavedAt: undefined,
- retry: vi.fn(),
- save: (action: () => unknown) => action(),
- status: 'idle',
- }),
-}));
-
-vi.mock('@/services/electron/system', () => ({
- electronSystemService: {
- getSystemMonospaceFonts: vi.fn(),
- },
-}));
-
-const initialUserStoreState = useUserStore.getState();
-
-beforeEach(() => {
- vi.clearAllMocks();
- vi.mocked(electronSystemService.getSystemMonospaceFonts).mockResolvedValue([
- { label: 'Courier New', value: '"Courier New"' },
- { label: 'Menlo', value: 'Menlo' },
- ]);
-});
-
-afterEach(() => {
- cleanup();
- useUserStore.setState(initialUserStoreState, true);
-});
-
-describe('Terminal appearance settings', () => {
- it('shows installed monospace fonts and persists the selection', async () => {
- const updatePreference = vi.fn();
- useUserStore.setState({
- updatePreference,
- });
-
- render(<Terminal />);
-
- expect(screen.getByText('settingAppearance.terminal.title')).toBeDefined();
- const select = screen.getByRole('combobox', {
- name: 'settingAppearance.terminal.fontFamily.title',
- });
-
- await waitFor(() => expect(screen.getByRole('option', { name: 'Menlo' })).toBeDefined());
- fireEvent.change(select, { target: { value: '"Courier New"' } });
-
- expect(electronSystemService.getSystemMonospaceFonts).toHaveBeenCalledOnce();
- expect(updatePreference).toHaveBeenCalledWith({ terminalFontFamily: '"Courier New"' });
- });
-
- it('stores an empty value when the application default is selected', async () => {
- const updatePreference = vi.fn();
- useUserStore.setState({
- preference: { terminalFontFamily: 'Menlo' },
- updatePreference,
- });
-
- render(<Terminal />);
-
- const select = screen.getByRole('combobox', {
- name: 'settingAppearance.terminal.fontFamily.title',
- });
-
- await waitFor(() => expect(screen.getByRole('option', { name: 'Menlo' })).toBeDefined());
- fireEvent.change(select, { target: { value: '__application_default__' } });
-
- expect(updatePreference).toHaveBeenCalledWith({ terminalFontFamily: '' });
- });
-});
diff --git a/src/features/Settings/appearance/features/Terminal/index.tsx b/src/features/Settings/appearance/features/Terminal/index.tsx
deleted file mode 100644
index fff4c50367f..00000000000
--- a/src/features/Settings/appearance/features/Terminal/index.tsx
+++ /dev/null
@@ -1,132 +0,0 @@
-'use client';
-
-import { isDesktop } from '@lobechat/const';
-import type { FormGroupItemType } from '@lobehub/ui';
-import { Form } from '@lobehub/ui';
-import { Select } from '@lobehub/ui/base-ui';
-import { memo, useEffect, useMemo, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import AutoSaveHint from '@/components/Editor/AutoSaveHint';
-import { FORM_STYLE } from '@/const/layoutTokens';
-import { SettingsSearchAnchor } from '@/features/SettingsSearch/anchor';
-import { useSaveState } from '@/hooks/useSaveState';
-import type { SystemMonospaceFont } from '@/services/electron/system';
-import { electronSystemService } from '@/services/electron/system';
-import { useUserStore } from '@/store/user';
-import { preferenceSelectors } from '@/store/user/selectors';
-
-const APPLICATION_DEFAULT_FONT = '__application_default__';
-
-const TerminalSettings = memo(() => {
- const { t } = useTranslation('setting');
- const terminalFontFamily = useUserStore(preferenceSelectors.terminalFontFamily);
- const updatePreference = useUserStore((s) => s.updatePreference);
- const { status: saveStatus, lastSavedAt, save, retry } = useSaveState();
- const [systemFonts, setSystemFonts] = useState<SystemMonospaceFont[]>([]);
- const [isLoading, setIsLoading] = useState(true);
- const [hasLoadError, setHasLoadError] = useState(false);
-
- useEffect(() => {
- let active = true;
-
- electronSystemService
- .getSystemMonospaceFonts()
- .then((fonts) => {
- if (!active) return;
-
- setSystemFonts(fonts);
- setHasLoadError(false);
- })
- .catch((error) => {
- if (!active) return;
-
- console.error('Failed to load system monospace fonts:', error);
- setHasLoadError(true);
- })
- .finally(() => {
- if (active) setIsLoading(false);
- });
-
- return () => {
- active = false;
- };
- }, []);
-
- const selectedFont = terminalFontFamily || APPLICATION_DEFAULT_FONT;
- const options = useMemo(() => {
- const fontOptions = [...systemFonts];
-
- if (terminalFontFamily && !systemFonts.some(({ value }) => value === terminalFontFamily)) {
- fontOptions.unshift({
- label: t('settingAppearance.terminal.fontFamily.unavailable', {
- font: terminalFontFamily,
- }),
- value: terminalFontFamily,
- });
- }
-
- return [
- {
- label: t('settingAppearance.terminal.fontFamily.default'),
- value: APPLICATION_DEFAULT_FONT,
- },
- ...fontOptions,
- ];
- }, [systemFonts, t, terminalFontFamily]);
-
- const handleChange = (value: string) => {
- save(() =>
- updatePreference({
- terminalFontFamily: value === APPLICATION_DEFAULT_FONT ? '' : value,
- }),
- );
- };
-
- const terminal: FormGroupItemType = {
- children: [
- {
- children: (
- <Select
- showSearch
- aria-label={t('settingAppearance.terminal.fontFamily.title')}
- loading={isLoading}
- options={options}
- style={{ width: 320 }}
- value={selectedFont}
- onChange={handleChange}
- />
- ),
- desc: hasLoadError
- ? t('settingAppearance.terminal.fontFamily.loadError')
- : t('settingAppearance.terminal.fontFamily.desc'),
- label: (
- <SettingsSearchAnchor id={'appearance-terminal-font'}>
- {t('settingAppearance.terminal.fontFamily.title')}
- </SettingsSearchAnchor>
- ),
- minWidth: undefined,
- },
- ],
- extra: <AutoSaveHint lastUpdatedTime={lastSavedAt} saveStatus={saveStatus} onRetry={retry} />,
- title: t('settingAppearance.terminal.title'),
- };
-
- return (
- <Form
- collapsible={false}
- items={[terminal]}
- itemsType={'group'}
- variant={'filled'}
- {...FORM_STYLE}
- />
- );
-});
-
-const Terminal = () => {
- if (!isDesktop) return null;
-
- return <TerminalSettings />;
-};
-
-export default Terminal;
diff --git a/src/features/Settings/appearance/features/useSystemFontOptions.test.ts b/src/features/Settings/appearance/features/useSystemFontOptions.test.ts
new file mode 100644
index 00000000000..8b4015241a3
--- /dev/null
+++ b/src/features/Settings/appearance/features/useSystemFontOptions.test.ts
@@ -0,0 +1,78 @@
+import { renderHook, waitFor } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { electronSystemService } from '@/services/electron/system';
+
+import { APPLICATION_DEFAULT_FONT, useSystemFontOptions } from './useSystemFontOptions';
+
+vi.mock('@/services/electron/system', () => ({
+ electronSystemService: {
+ getSystemFonts: vi.fn(),
+ getSystemMonospaceFonts: vi.fn(),
+ },
+}));
+
+const params = {
+ defaultLabel: 'default',
+ unavailableLabel: (font: string) => `${font} (unavailable)`,
+};
+
+beforeEach(() => {
+ vi.mocked(electronSystemService.getSystemFonts).mockResolvedValue([
+ { label: 'Georgia', value: 'Georgia' },
+ { label: 'LXGW WenKai', value: '"LXGW WenKai"' },
+ ]);
+ vi.mocked(electronSystemService.getSystemMonospaceFonts).mockResolvedValue([
+ { label: 'Menlo', value: 'Menlo' },
+ ]);
+});
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe('useSystemFontOptions', () => {
+ it('puts the default entry first and keeps the loaded fonts after it', async () => {
+ const { result } = renderHook(() => useSystemFontOptions(params));
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ expect(result.current.options.map((o) => o.value)).toEqual([
+ APPLICATION_DEFAULT_FONT,
+ 'Georgia',
+ '"LXGW WenKai"',
+ ]);
+ expect(electronSystemService.getSystemMonospaceFonts).not.toHaveBeenCalled();
+ });
+
+ it('loads only monospace fonts when monospaceOnly is set', async () => {
+ const { result } = renderHook(() => useSystemFontOptions({ ...params, monospaceOnly: true }));
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ expect(result.current.options.map((o) => o.value)).toEqual([APPLICATION_DEFAULT_FONT, 'Menlo']);
+ expect(electronSystemService.getSystemFonts).not.toHaveBeenCalled();
+ });
+
+ it('keeps a selected font that is not installed on this device', async () => {
+ const { result } = renderHook(() => useSystemFontOptions({ ...params, value: 'Gone Sans' }));
+
+ await waitFor(() => expect(result.current.isLoading).toBe(false));
+
+ expect(result.current.options[1]).toEqual({
+ label: 'Gone Sans (unavailable)',
+ value: 'Gone Sans',
+ });
+ });
+
+ it('reports a load failure while still offering the default entry', async () => {
+ vi.mocked(electronSystemService.getSystemFonts).mockRejectedValue(new Error('nope'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ const { result } = renderHook(() => useSystemFontOptions(params));
+
+ await waitFor(() => expect(result.current.hasLoadError).toBe(true));
+
+ expect(result.current.options).toEqual([{ label: 'default', value: APPLICATION_DEFAULT_FONT }]);
+ });
+});
diff --git a/src/features/Settings/appearance/features/useSystemFontOptions.ts b/src/features/Settings/appearance/features/useSystemFontOptions.ts
new file mode 100644
index 00000000000..05886054edb
--- /dev/null
+++ b/src/features/Settings/appearance/features/useSystemFontOptions.ts
@@ -0,0 +1,65 @@
+import { useEffect, useMemo, useState } from 'react';
+
+import type { SystemFont } from '@/services/electron/system';
+import { electronSystemService } from '@/services/electron/system';
+
+export const APPLICATION_DEFAULT_FONT = '__application_default__';
+
+interface UseSystemFontOptionsParams {
+ defaultLabel: string;
+ monospaceOnly?: boolean;
+ unavailableLabel: (font: string) => string;
+ value?: string;
+}
+
+export const useSystemFontOptions = ({
+ defaultLabel,
+ monospaceOnly,
+ unavailableLabel,
+ value,
+}: UseSystemFontOptionsParams) => {
+ const [systemFonts, setSystemFonts] = useState<SystemFont[]>([]);
+ const [isLoading, setIsLoading] = useState(true);
+ const [hasLoadError, setHasLoadError] = useState(false);
+
+ useEffect(() => {
+ let active = true;
+
+ const load = monospaceOnly
+ ? electronSystemService.getSystemMonospaceFonts()
+ : electronSystemService.getSystemFonts();
+
+ load
+ .then((fonts) => {
+ if (!active) return;
+
+ setSystemFonts(fonts);
+ setHasLoadError(false);
+ })
+ .catch((error) => {
+ if (!active) return;
+
+ console.error('Failed to load system fonts:', error);
+ setHasLoadError(true);
+ })
+ .finally(() => {
+ if (active) setIsLoading(false);
+ });
+
+ return () => {
+ active = false;
+ };
+ }, [monospaceOnly]);
+
+ const options = useMemo(() => {
+ const fontOptions = [...systemFonts];
+
+ if (value && !systemFonts.some((font) => font.value === value)) {
+ fontOptions.unshift({ label: unavailableLabel(value), value });
+ }
+
+ return [{ label: defaultLabel, value: APPLICATION_DEFAULT_FONT }, ...fontOptions];
+ }, [systemFonts, value, defaultLabel, unavailableLabel]);
+
+ return { hasLoadError, isLoading, options };
+};
diff --git a/src/features/Settings/appearance/index.tsx b/src/features/Settings/appearance/index.tsx
index 04fafe2d7c0..1edc916b932 100644
--- a/src/features/Settings/appearance/index.tsx
+++ b/src/features/Settings/appearance/index.tsx
@@ -6,7 +6,7 @@ import ChatAppearance from '../chat-appearance/features/ChatAppearance';
import Appearance from '../common/features/Appearance';
import Common from '../common/features/Common/Common';
import Desktop from './features/Desktop';
-import Terminal from './features/Terminal';
+import Font from './features/Font';
interface PageProps {
showSettingHeader?: boolean;
@@ -20,7 +20,7 @@ const Page = ({ showSettingHeader = true }: PageProps) => {
<Common />
<Appearance />
<Desktop />
- <Terminal />
+ <Font />
<ChatAppearance />
</>
);
diff --git a/src/features/SettingsSearch/items.ts b/src/features/SettingsSearch/items.ts
index 5a07464c558..3542f9c4cd6 100644
--- a/src/features/SettingsSearch/items.ts
+++ b/src/features/SettingsSearch/items.ts
@@ -340,10 +340,18 @@ export const SETTINGS_SEARCH_ITEMS: SettingsSearchItem[] = [
visible: (ctx) => ctx.isDesktop,
},
{
- anchor: 'appearance-terminal-font',
- descKey: 'settingAppearance.terminal.fontFamily.desc',
- keywords: ['terminal font', 'monospace', 'font family'],
- labelKey: 'settingAppearance.terminal.fontFamily.title',
+ anchor: 'appearance-font-family',
+ descKey: 'settingAppearance.font.fontFamily.desc',
+ keywords: ['font', 'font family', 'typeface', 'interface font'],
+ labelKey: 'settingAppearance.font.fontFamily.title',
+ tab: SettingsTabs.Appearance,
+ visible: (ctx) => ctx.isDesktop,
+ },
+ {
+ anchor: 'appearance-monospace-font',
+ descKey: 'settingAppearance.font.monospace.desc',
+ keywords: ['terminal font', 'monospace', 'code font', 'font family'],
+ labelKey: 'settingAppearance.font.monospace.title',
tab: SettingsTabs.Appearance,
visible: (ctx) => ctx.isDesktop,
},
diff --git a/src/layout/GlobalProvider/AppTheme.tsx b/src/layout/GlobalProvider/AppTheme.tsx
index 12f068d5004..8071f922431 100644
--- a/src/layout/GlobalProvider/AppTheme.tsx
+++ b/src/layout/GlobalProvider/AppTheme.tsx
@@ -4,13 +4,14 @@ import 'antd/dist/reset.css';
import { type NeutralColors, type PrimaryColors } from '@lobehub/ui';
import { ConfigProvider, FontLoader, ThemeProvider } from '@lobehub/ui';
-import { createStaticStyles, cx, useTheme } from 'antd-style';
+import { createStaticStyles, cx } from 'antd-style';
import * as m from 'motion/react-m';
import { type ReactNode } from 'react';
-import { memo, useEffect, useState } from 'react';
+import { memo, useEffect, useMemo, useState } from 'react';
import AntdStaticMethods from '@/components/AntdStaticMethods';
import Link from '@/components/Link';
+import { genFontFamily, genFontFamilyCode } from '@/const/font';
import { LOBE_THEME_NEUTRAL_COLOR, LOBE_THEME_PRIMARY_COLOR } from '@/const/theme';
import { useIsDark } from '@/hooks/useIsDark';
import { getUILocaleAndResources } from '@/libs/getUILocaleAndResources';
@@ -20,7 +21,7 @@ import Image from '@/libs/next/Image';
import { useGlobalStore } from '@/store/global';
import { systemStatusSelectors } from '@/store/global/selectors';
import { useUserStore } from '@/store/user';
-import { userGeneralSettingsSelectors } from '@/store/user/selectors';
+import { preferenceSelectors, userGeneralSettingsSelectors } from '@/store/user/selectors';
import { GlobalStyle } from '@/styles';
import { setCookie } from '@/utils/client/cookie';
@@ -99,7 +100,6 @@ const AppTheme = memo<AppThemeProps>(
customFontFamily,
}) => {
const language = useGlobalStore(systemStatusSelectors.language);
- const antdTheme = useTheme();
const isDark = useIsDark();
const [primaryColor, neutralColor, animationMode] = useUserStore((s) => [
@@ -107,6 +107,27 @@ const AppTheme = memo<AppThemeProps>(
userGeneralSettingsSelectors.neutralColor(s),
userGeneralSettingsSelectors.animationMode(s),
]);
+ const [userFontFamily, userFontFamilyCode] = useUserStore((s) => [
+ preferenceSelectors.fontFamily(s),
+ preferenceSelectors.terminalFontFamily(s),
+ ]);
+ const fontFamily = useMemo(
+ () =>
+ genFontFamily({
+ customFontFamily,
+ locale: resolveUILocale(language).normalizedLocale,
+ userFontFamily,
+ }),
+ [customFontFamily, language, userFontFamily],
+ );
+ const fontFamilyCode = useMemo(
+ () =>
+ genFontFamilyCode({
+ locale: resolveUILocale(language).normalizedLocale,
+ userFontFamily: userFontFamilyCode,
+ }),
+ [language, userFontFamilyCode],
+ );
const [uiResources, setUIResources] = useState<UILocaleResources>();
const [uiLocale, setUILocale] = useState(() => resolveUILocale(language).uiLocale);
@@ -151,9 +172,8 @@ const AppTheme = memo<AppThemeProps>(
theme={{
cssVar: { key: 'lobe-vars' },
token: {
- fontFamily: customFontFamily
- ? `${customFontFamily},${antdTheme.fontFamily}`
- : undefined,
+ fontFamily,
+ fontFamilyCode,
motion: animationMode !== 'disabled',
motionUnit: animationMode === 'agile' ? 0.05 : 0.1,
},
diff --git a/src/services/electron/system.ts b/src/services/electron/system.ts
index 2f79ea55719..f5c1118e290 100644
--- a/src/services/electron/system.ts
+++ b/src/services/electron/system.ts
@@ -8,11 +8,13 @@ import type {
import { ensureElectronIpc } from '@/utils/electron/ipc';
-export interface SystemMonospaceFont {
+export interface SystemFont {
label: string;
value: string;
}
+export type SystemMonospaceFont = SystemFont;
+
/**
* Service class for interacting with Electron's system-level information and actions.
*/
@@ -39,10 +41,14 @@ class ElectronSystemService {
return this.ipc.system.setLastWorkspaceSlug(slug);
}
- async getSystemMonospaceFonts(): Promise<SystemMonospaceFont[]> {
+ async getSystemMonospaceFonts(): Promise<SystemFont[]> {
return this.ipc.system.getSystemMonospaceFonts();
}
+ async getSystemFonts(): Promise<SystemFont[]> {
+ return this.ipc.system.getSystemFonts();
+ }
+
async closeWindow(): Promise<void> {
return this.ipc.windows.closeWindow();
}
diff --git a/src/store/user/slices/preference/selectors/preference.ts b/src/store/user/slices/preference/selectors/preference.ts
index 1e83d5adc68..b8343faac01 100644
--- a/src/store/user/slices/preference/selectors/preference.ts
+++ b/src/store/user/slices/preference/selectors/preference.ts
@@ -21,11 +21,14 @@ const shouldTriggerFileInKnowledgeBaseTip = (s: UserStore) =>
!(typeof s.preference.guide?.moveSettingsToAvatar === 'boolean');
const isPreferenceInit = (s: UserStore) => s.isUserStateInit;
+const fontFamily = (s: UserStore): string | undefined =>
+ s.preference.fontFamily?.trim() || undefined;
const terminalFontFamily = (s: UserStore): string | undefined =>
s.preference.terminalFontFamily?.trim() || undefined;
export const preferenceSelectors = {
defaultOpenInApp,
+ fontFamily,
hideSettingsMoveGuide,
hideSyncAlert,
isPreferenceInit,