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.

🐛 fix(desktop): resolve UI language from the OS instead of the pruned app locale (#17804)

Innei59f16c15f780
diff --git a/apps/desktop/index.html b/apps/desktop/index.html
index 24873132b34..1c5db837adc 100644
--- a/apps/desktop/index.html
+++ b/apps/desktop/index.html
@@ -68,16 +68,20 @@
if (resolvedTheme === 'dark' || resolvedTheme === 'light') {
document.documentElement.setAttribute('data-theme', resolvedTheme);
}
- // Renderer-side reloads (Cmd+R / webContents.reload) don't go through
- // the main process's `?lng=` injection, so prefer the i18next cache —
- // the actual user setting persisted by the language switcher — before
- // falling back to the URL param or navigator detection.
+ // The main process resolves `lng` from the stored setting, or from the OS
+ // language when that setting is `auto`, so it always wins. The i18next
+ // cache is only a fallback for renderer-side reloads (Cmd+R) that landed
+ // on a client-routed URL without the query param. `navigator.language`
+ // is last — packaging prunes the app's locales, which makes it report
+ // English on a non-English system.
var urlParams = new URLSearchParams(window.location.search);
- var locale;
- try {
- locale = localStorage.getItem('i18nextLng');
- } catch (_) {}
- if (!locale) locale = urlParams.get('lng') || navigator.language || 'en-US';
+ var locale = urlParams.get('lng');
+ if (!locale) {
+ try {
+ locale = localStorage.getItem('i18nextLng');
+ } catch (_) {}
+ }
+ if (!locale) locale = navigator.language || 'en-US';
document.documentElement.lang = locale;
var rtl = ['ar', 'arc', 'dv', 'fa', 'ha', 'he', 'khw', 'ks', 'ku', 'ps', 'ur', 'yi'];
document.documentElement.dir =
diff --git a/apps/desktop/src/common/systemLanguage.test.ts b/apps/desktop/src/common/systemLanguage.test.ts
new file mode 100644
index 00000000000..7b8811e09a2
--- /dev/null
+++ b/apps/desktop/src/common/systemLanguage.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ normalizeSystemLanguage,
+ readSystemLanguageArg,
+ SYSTEM_LANGUAGE_ARG_PREFIX,
+} from './systemLanguage';
+
+describe('normalizeSystemLanguage', () => {
+ it.each([
+ ['zh-Hans-CN', 'zh-CN'],
+ ['zh-Hans', 'zh-CN'],
+ ['zh-SG', 'zh-CN'],
+ ['zh', 'zh-CN'],
+ ['zh-CN', 'zh-CN'],
+ ['zh-Hant-TW', 'zh-TW'],
+ ['zh-TW', 'zh-TW'],
+ ['zh-HK', 'zh-TW'],
+ ])('maps the Chinese tag %s to %s', (input, expected) => {
+ expect(normalizeSystemLanguage(input)).toBe(expected);
+ });
+
+ it.each([
+ ['en-US', 'en-US'],
+ ['en-SG', 'en-US'],
+ ['fr-FR', 'fr-FR'],
+ ['fr', 'fr-FR'],
+ ['ja-JP', 'ja-JP'],
+ ['pt-PT', 'pt-BR'],
+ ['ar-EG', 'ar'],
+ ['fa', 'fa-IR'],
+ ['zh_CN', 'zh-CN'],
+ ])('maps %s to the supported locale %s', (input, expected) => {
+ expect(normalizeSystemLanguage(input)).toBe(expected);
+ });
+
+ it.each([undefined, '', 'xx-XX'])('falls back to en-US for %s', (input) => {
+ expect(normalizeSystemLanguage(input)).toBe('en-US');
+ });
+});
+
+describe('readSystemLanguageArg', () => {
+ it('reads the language injected via additionalArguments', () => {
+ expect(
+ readSystemLanguageArg(['--some-flag', `${SYSTEM_LANGUAGE_ARG_PREFIX}zh-CN`, '--other']),
+ ).toBe('zh-CN');
+ });
+
+ it('returns undefined when the argument is absent or empty', () => {
+ expect(readSystemLanguageArg(['--some-flag'])).toBeUndefined();
+ expect(readSystemLanguageArg([SYSTEM_LANGUAGE_ARG_PREFIX])).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/common/systemLanguage.ts b/apps/desktop/src/common/systemLanguage.ts
new file mode 100644
index 00000000000..054400e2879
--- /dev/null
+++ b/apps/desktop/src/common/systemLanguage.ts
@@ -0,0 +1,51 @@
+export const SYSTEM_LANGUAGE_ARG_PREFIX = '--lobe-system-language=';
+
+export const FALLBACK_LOCALE = 'en-US';
+
+const SUPPORTED_LOCALES = [
+ 'ar',
+ 'bg-BG',
+ 'de-DE',
+ 'en-US',
+ 'es-ES',
+ 'fa-IR',
+ 'fr-FR',
+ 'it-IT',
+ 'ja-JP',
+ 'ko-KR',
+ 'nl-NL',
+ 'pl-PL',
+ 'pt-BR',
+ 'ru-RU',
+ 'tr-TR',
+ 'vi-VN',
+ 'zh-CN',
+ 'zh-TW',
+];
+
+export const normalizeSystemLanguage = (locale?: string): string => {
+ if (!locale) return FALLBACK_LOCALE;
+
+ const lower = locale.toLowerCase().replaceAll('_', '-');
+
+ if (lower.startsWith('ar')) return 'ar';
+ if (lower.startsWith('fa')) return 'fa-IR';
+ // Traditional-Chinese regions must be matched before the generic `zh` branch
+ if (/^zh-(?:hant|tw|hk|mo)/.test(lower)) return 'zh-TW';
+ if (lower.startsWith('zh')) return 'zh-CN';
+
+ const exact = SUPPORTED_LOCALES.find((item) => item.toLowerCase() === lower);
+ if (exact) return exact;
+
+ const base = lower.split('-')[0];
+
+ return (
+ SUPPORTED_LOCALES.find((item) => item.toLowerCase().split('-')[0] === base) ?? FALLBACK_LOCALE
+ );
+};
+
+export const readSystemLanguageArg = (argv: readonly string[]): string | undefined => {
+ const arg = argv.find((item) => item.startsWith(SYSTEM_LANGUAGE_ARG_PREFIX));
+
+ return arg ? arg.slice(SYSTEM_LANGUAGE_ARG_PREFIX.length) || undefined : undefined;
+};
diff --git a/apps/desktop/src/main/__mocks__/electron.ts b/apps/desktop/src/main/__mocks__/electron.ts
index ca1513ae853..6bdf9fae880 100644
--- a/apps/desktop/src/main/__mocks__/electron.ts
+++ b/apps/desktop/src/main/__mocks__/electron.ts
@@ -18,6 +18,7 @@ export const app = {
getLocale: vi.fn(() => 'en-US'),
getName: vi.fn(() => 'LobeHub'),
getPath: vi.fn((name: string) => `/mock/${name}`),
+ getPreferredSystemLanguages: vi.fn(() => ['en-US']),
getVersion: vi.fn(() => '0.0.0-test'),
isPackaged: false,
on: vi.fn(),
diff --git a/apps/desktop/src/main/controllers/SystemCtr.ts b/apps/desktop/src/main/controllers/SystemCtr.ts
index e7d1d538f0d..b2016243cf6 100644
--- a/apps/desktop/src/main/controllers/SystemCtr.ts
+++ b/apps/desktop/src/main/controllers/SystemCtr.ts
@@ -19,6 +19,7 @@ import {
requestMicrophoneAccess,
requestScreenCaptureAccess,
} from '@/utils/permissions';
+import { getSystemLanguage, resolveUILocale } from '@/utils/system-language';
import { ControllerModule, IpcMethod } from './index';
@@ -219,7 +220,7 @@ export default class SystemController extends ControllerModule {
@IpcMethod()
getSystemLocale(): string {
- return app.getLocale();
+ return getSystemLanguage();
}
@IpcMethod()
@@ -256,7 +257,7 @@ export default class SystemController extends ControllerModule {
async updateLocale(locale: string) {
this.app.storeManager.set('locale', locale);
- await this.app.i18n.changeLanguage(locale === 'auto' ? app.getLocale() : locale);
+ await this.app.i18n.changeLanguage(resolveUILocale(locale));
this.app.browserManager.broadcastToAllWindows('localeChanged', { locale });
return { success: true };
diff --git a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts
index 5a17836e483..6953d127404 100644
--- a/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/SystemCtr.test.ts
@@ -66,6 +66,7 @@ vi.mock('electron', () => ({
getAppPath: vi.fn(() => '/mock/app/path'),
getLocale: vi.fn(() => 'en-US'),
getPath: vi.fn((name: string) => `/mock/path/${name}`),
+ getPreferredSystemLanguages: vi.fn(() => ['en-US']),
},
desktopCapturer: {
getSources: vi.fn(async () => []),
diff --git a/apps/desktop/src/main/core/browser/Browser.ts b/apps/desktop/src/main/core/browser/Browser.ts
index 0d521b7b375..caaec3510d6 100644
--- a/apps/desktop/src/main/core/browser/Browser.ts
+++ b/apps/desktop/src/main/core/browser/Browser.ts
@@ -12,6 +12,8 @@ import RemoteServerConfigCtr from '@/controllers/RemoteServerConfigCtr';
import { backendProxyProtocolManager } from '@/core/infrastructure/BackendProxyProtocolManager';
import { appendVercelCookie, setResponseHeader } from '@/utils/http-headers';
import { createLogger } from '@/utils/logger';
+import { getSystemLanguage, resolveUILocale } from '@/utils/system-language';
+import { SYSTEM_LANGUAGE_ARG_PREFIX } from '~common/systemLanguage';
import type { App } from '../App';
import { WindowStateManager } from './WindowStateManager';
@@ -177,6 +179,7 @@ export default class Browser {
show: false,
title,
webPreferences: {
+ additionalArguments: [`${SYSTEM_LANGUAGE_ARG_PREFIX}${getSystemLanguage()}`],
backgroundThrottling: false,
contextIsolation: true,
preload: path.join(preloadDir, 'index.js'),
@@ -529,11 +532,12 @@ export default class Browser {
};
private buildUrlWithLocale(initUrl: string): string {
- const storedLocale = this.app.storeManager.get('locale', 'auto');
- if (storedLocale && storedLocale !== 'auto') {
- return `${initUrl}${initUrl.includes('?') ? '&' : '?'}lng=${storedLocale}`;
- }
- return initUrl;
+ // Always inject `lng` — including for `auto`, where the main process is the
+ // only side that can resolve the real OS language (the renderer's
+ // `navigator.language` reports English once packaging prunes the app's locales).
+ const locale = resolveUILocale(this.app.storeManager.get('locale', 'auto'));
+
+ return `${initUrl}${initUrl.includes('?') ? '&' : '?'}lng=${locale}`;
}
private async handleLoadError(urlWithLocale: string): Promise<void> {
diff --git a/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts b/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
index 55fe4fa225b..b7050b0fbe5 100644
--- a/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
+++ b/apps/desktop/src/main/core/browser/__tests__/Browser.test.ts
@@ -60,6 +60,8 @@ const {
setBadge: vi.fn(),
show: vi.fn(),
},
+ getLocale: vi.fn(() => 'en-US'),
+ getPreferredSystemLanguages: vi.fn(() => ['en-US']),
getVersion: vi.fn(() => '1.2.3'),
setActivationPolicy: vi.fn(),
setBadgeCount: vi.fn(),
@@ -504,7 +506,51 @@ describe('Browser', () => {
autoLoadUrlSpy?.mockRestore();
await browser.loadUrl('/test-path');
- expect(mockBrowserWindow.loadURL).toHaveBeenCalledWith('http://localhost:3000/test-path');
+ expect(mockBrowserWindow.loadURL).toHaveBeenCalledWith(
+ 'http://localhost:3000/test-path?lng=en-US',
+ );
+ });
+
+ it('injects the OS language when the stored locale is auto', async () => {
+ autoLoadUrlSpy?.mockRestore();
+ mockStoreManagerGet.mockImplementation((key: string) =>
+ key === 'locale' ? 'auto' : undefined,
+ );
+ mockAppModule.getPreferredSystemLanguages.mockReturnValue(['zh-Hans-CN']);
+
+ await browser.loadUrl('/test-path');
+
+ expect(mockBrowserWindow.loadURL).toHaveBeenCalledWith(
+ 'http://localhost:3000/test-path?lng=zh-CN',
+ );
+ });
+
+ it('injects an explicit locale choice ahead of the OS language', async () => {
+ autoLoadUrlSpy?.mockRestore();
+ mockStoreManagerGet.mockImplementation((key: string) =>
+ key === 'locale' ? 'ja-JP' : undefined,
+ );
+ mockAppModule.getPreferredSystemLanguages.mockReturnValue(['zh-Hans-CN']);
+
+ await browser.loadUrl('/test-path');
+
+ expect(mockBrowserWindow.loadURL).toHaveBeenCalledWith(
+ 'http://localhost:3000/test-path?lng=ja-JP',
+ );
+ });
+
+ it('appends lng to a URL that already carries a query string', async () => {
+ autoLoadUrlSpy?.mockRestore();
+ mockAppModule.getPreferredSystemLanguages.mockReturnValue(['en-US']);
+ (mockApp.buildRendererUrl as any).mockResolvedValueOnce(
+ 'http://localhost:3000/test-path?foo=1',
+ );
+
+ await browser.loadUrl('/test-path');
+
+ expect(mockBrowserWindow.loadURL).toHaveBeenCalledWith(
+ 'http://localhost:3000/test-path?foo=1&lng=en-US',
+ );
});
it('should load error page on failure', async () => {
diff --git a/apps/desktop/src/main/core/infrastructure/I18nManager.ts b/apps/desktop/src/main/core/infrastructure/I18nManager.ts
index fc7dffccb82..55bed1d0081 100644
--- a/apps/desktop/src/main/core/infrastructure/I18nManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/I18nManager.ts
@@ -1,9 +1,9 @@
-import { app } from 'electron';
import i18next from 'i18next';
import type { App } from '@/core/App';
import { loadResources } from '@/locales/resources';
import { createLogger } from '@/utils/logger';
+import { resolveUILocale } from '@/utils/system-language';
// Create logger
const logger = createLogger('core:I18nManager');
@@ -30,8 +30,7 @@ export class I18nManager {
// Priority: parameter language > stored locale > system language
const storedLocale = this.app.storeManager.get('locale', 'auto') as string;
- const defaultLanguage =
- lang || (storedLocale !== 'auto' ? storedLocale : app.getLocale()) || 'en';
+ const defaultLanguage = lang || resolveUILocale(storedLocale);
logger.info(
`Initializing i18n, app locale: ${defaultLanguage}, stored locale: ${storedLocale}`,
@@ -89,7 +88,7 @@ export class I18nManager {
createNamespacedT(namespace: string) {
return (key: string, options: any = {}) => {
// Copy options to avoid modifying the original object
- const mergedOptions = { ...options , ns: namespace,};
+ const mergedOptions = { ...options, ns: namespace };
// Set namespace
return this.t(key, mergedOptions);
diff --git a/apps/desktop/src/main/core/infrastructure/__tests__/I18nManager.test.ts b/apps/desktop/src/main/core/infrastructure/__tests__/I18nManager.test.ts
index 2e9f7ff55df..7a07fe9f185 100644
--- a/apps/desktop/src/main/core/infrastructure/__tests__/I18nManager.test.ts
+++ b/apps/desktop/src/main/core/infrastructure/__tests__/I18nManager.test.ts
@@ -19,6 +19,7 @@ const { mockApp, mockI18nextInstance, mockLoadResources, mockCreateInstance } =
return {
mockApp: {
getLocale: vi.fn().mockReturnValue('en-US'),
+ getPreferredSystemLanguages: vi.fn().mockReturnValue(['en-US']),
},
mockCreateInstance,
mockI18nextInstance,
@@ -73,6 +74,7 @@ describe('I18nManager', () => {
// Reset electron app mock
mockApp.getLocale.mockReturnValue('en-US');
+ mockApp.getPreferredSystemLanguages.mockReturnValue(['en-US']);
// Create mock App core
mockStoreManagerGet = vi.fn().mockReturnValue('auto');
@@ -138,7 +140,7 @@ describe('I18nManager', () => {
it('should use system locale when stored locale is auto', async () => {
mockStoreManagerGet.mockReturnValue('auto');
- mockApp.getLocale.mockReturnValue('fr-FR');
+ mockApp.getPreferredSystemLanguages.mockReturnValue(['fr-FR']);
await manager.init();
@@ -149,6 +151,20 @@ describe('I18nManager', () => {
);
});
+ it('should prefer the OS language over a getLocale() poisoned by pruned app locales', async () => {
+ mockStoreManagerGet.mockReturnValue('auto');
+ mockApp.getPreferredSystemLanguages.mockReturnValue(['zh-Hans-CN']);
+ mockApp.getLocale.mockReturnValue('en-US');
+
+ await manager.init();
+
+ expect(mockI18nextInstance.init).toHaveBeenCalledWith(
+ expect.objectContaining({
+ lng: 'zh-CN',
+ }),
+ );
+ });
+
it('should skip initialization if already initialized', async () => {
await manager.init();
vi.clearAllMocks();
diff --git a/apps/desktop/src/main/menus/impls/macOS.locale.test.ts b/apps/desktop/src/main/menus/impls/macOS.locale.test.ts
new file mode 100644
index 00000000000..d98ce5399ca
--- /dev/null
+++ b/apps/desktop/src/main/menus/impls/macOS.locale.test.ts
@@ -0,0 +1,100 @@
+import { Menu } from 'electron';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { App } from '@/core/App';
+import { I18nManager } from '@/core/infrastructure/I18nManager';
+
+import { MacOSMenu } from './macOS';
+
+const { mockAppModule } = vi.hoisted(() => ({
+ mockAppModule: {
+ dock: { setMenu: vi.fn() },
+ getAppPath: vi.fn(() => '/mock/app/path'),
+ getLocale: vi.fn(() => 'en-US'),
+ getName: vi.fn(() => 'LobeHub'),
+ getPath: vi.fn((type: string) => `/mock/path/${type}`),
+ getPreferredSystemLanguages: vi.fn(() => ['en-US']),
+ },
+}));
+
+vi.mock('electron', () => ({
+ app: mockAppModule,
+ Menu: {
+ buildFromTemplate: vi.fn((template) => ({ template })),
+ setApplicationMenu: vi.fn(),
+ },
+ shell: { openExternal: vi.fn(), openPath: vi.fn(() => Promise.resolve('')) },
+}));
+
+vi.mock('electron-is', () => ({ macOS: vi.fn(() => true) }));
+
+vi.mock('@/const/env', () => ({ isDev: false }));
+
+vi.mock('@/utils/logger', () => ({
+ createLogger: () => ({ debug: vi.fn(), error: vi.fn(), info: vi.fn(), warn: vi.fn() }),
+}));
+
+const createAppCore = () => {
+ const appCore = {
+ browserManager: {
+ getMainWindow: vi.fn(() => ({ broadcast: vi.fn(), loadUrl: vi.fn(), show: vi.fn() })),
+ retrieveByIdentifier: vi.fn(() => ({ show: vi.fn() })),
+ showMainWindow: vi.fn(),
+ },
+ menuManager: { rebuildAppMenu: vi.fn(), refreshMenus: vi.fn() },
+ screenCaptureManager: { startSession: vi.fn() },
+ storeManager: { get: vi.fn(() => 'auto'), openInEditor: vi.fn(), set: vi.fn() },
+ updaterManager: { getUpdaterState: vi.fn(() => ({ stage: 'idle' })) },
+ } as unknown as App;
+
+ return appCore;
+};
+
+const buildMenuLabels = async () => {
+ const appCore = createAppCore();
+ const i18n = new I18nManager(appCore);
+ await i18n.init();
+ (appCore as any).i18n = i18n;
+
+ new MacOSMenu(appCore).buildAndSetAppMenu();
+
+ // buildAndSetAppMenu also builds the dock menu; the app menu is built first
+ const template = (Menu.buildFromTemplate as any).mock.calls[0][0];
+
+ return {
+ topLevel: template.map((item: any) => item.label),
+ windowSubmenu: template
+ .find((item: any) => item.role === 'windowMenu')
+ .submenu.map((item: any) => item.label)
+ .filter(Boolean),
+ };
+};
+
+describe('macOS menu bar language on first launch', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockAppModule.getName.mockReturnValue('LobeHub');
+ });
+
+ it('renders the menu bar in the OS language when nothing is stored yet', async () => {
+ // A packaged build reports en-US here because `electronLanguages` prunes the
+ // app's locales — the OS language is the only trustworthy signal.
+ mockAppModule.getLocale.mockReturnValue('en-US');
+ mockAppModule.getPreferredSystemLanguages.mockReturnValue(['zh-Hans-CN']);
+
+ const { topLevel, windowSubmenu } = await buildMenuLabels();
+
+ expect(topLevel).toEqual(['LobeHub', '文件', '编辑', '视图', '前往', '窗口', '帮助']);
+ expect(windowSubmenu).toEqual(['最小化', '缩放', '前置所有窗口']);
+ });
+
+ it('still renders English on an English system', async () => {
+ mockAppModule.getLocale.mockReturnValue('en-US');
+ mockAppModule.getPreferredSystemLanguages.mockReturnValue(['en-US']);
+
+ const { topLevel, windowSubmenu } = await buildMenuLabels();
+
+ expect(topLevel).toEqual(['LobeHub', 'File', 'Edit', 'View', 'Go', 'Window', 'Help']);
+ expect(windowSubmenu).toEqual(['Minimize', 'Zoom', 'Bring All Windows to Front']);
+ });
+});
diff --git a/apps/desktop/src/main/menus/impls/macOS.ts b/apps/desktop/src/main/menus/impls/macOS.ts
index ef493f80a90..50ad1cde620 100644
--- a/apps/desktop/src/main/menus/impls/macOS.ts
+++ b/apps/desktop/src/main/menus/impls/macOS.ts
@@ -242,7 +242,15 @@ export class MacOSMenu extends BaseMenuPlatform implements IMenuPlatform {
},
{
label: t('window.title'),
+ // Keep the role so macOS still appends the open-window list, but supply
+ // the submenu — Electron's generated one carries its own English labels.
role: 'windowMenu',
+ submenu: [
+ { label: t('window.minimize'), role: 'minimize' },
+ { label: t('window.zoom'), role: 'zoom' },
+ { type: 'separator' },
+ { label: t('window.front'), role: 'front' },
+ ],
},
{
label: t('help.title'),
diff --git a/apps/desktop/src/main/utils/__tests__/system-language.test.ts b/apps/desktop/src/main/utils/__tests__/system-language.test.ts
new file mode 100644
index 00000000000..40d4d2ecd3d
--- /dev/null
+++ b/apps/desktop/src/main/utils/__tests__/system-language.test.ts
@@ -0,0 +1,43 @@
+import { app } from 'electron';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { getSystemLanguage, resolveUILocale } from '../system-language';
+
+const mockApp = vi.mocked(app);
+
+describe('getSystemLanguage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('reads the OS language rather than the app locale', () => {
+ mockApp.getPreferredSystemLanguages.mockReturnValue(['zh-Hans-CN']);
+ // What a packaged build reports once `electronLanguages` prunes the locales
+ mockApp.getLocale.mockReturnValue('en-US');
+
+ expect(getSystemLanguage()).toBe('zh-CN');
+ });
+
+ it('falls back to the app locale when the OS reports nothing', () => {
+ mockApp.getPreferredSystemLanguages.mockReturnValue([]);
+ mockApp.getLocale.mockReturnValue('ja-JP');
+
+ expect(getSystemLanguage()).toBe('ja-JP');
+ });
+});
+
+describe('resolveUILocale', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockApp.getPreferredSystemLanguages.mockReturnValue(['zh-Hans-CN']);
+ mockApp.getLocale.mockReturnValue('en-US');
+ });
+
+ it('keeps an explicit user choice untouched', () => {
+ expect(resolveUILocale('ja-JP')).toBe('ja-JP');
+ });
+
+ it.each([undefined, 'auto'])('resolves %s to the OS language', (stored) => {
+ expect(resolveUILocale(stored)).toBe('zh-CN');
+ });
+});
diff --git a/apps/desktop/src/main/utils/system-language.ts b/apps/desktop/src/main/utils/system-language.ts
new file mode 100644
index 00000000000..b9bd0de8cc6
--- /dev/null
+++ b/apps/desktop/src/main/utils/system-language.ts
@@ -0,0 +1,15 @@
+import { app } from 'electron';
+
+import { normalizeSystemLanguage } from '~common/systemLanguage';
+
+/**
+ * `app.getLocale()` resolves against the locales bundled with the app, so a
+ * packaging step that prunes them (see `electronLanguages`) makes it — and the
+ * renderer's `navigator.language` — report English on a non-English system.
+ * `getPreferredSystemLanguages()` reads the OS setting directly and survives.
+ */
+export const getSystemLanguage = (): string =>
+ normalizeSystemLanguage(app.getPreferredSystemLanguages()[0] || app.getLocale());
+
+export const resolveUILocale = (storedLocale?: string): string =>
+ !storedLocale || storedLocale === 'auto' ? getSystemLanguage() : storedLocale;
diff --git a/apps/desktop/src/preload/electronApi.ts b/apps/desktop/src/preload/electronApi.ts
index 7c6d5601665..f6f1b4d21fd 100644
--- a/apps/desktop/src/preload/electronApi.ts
+++ b/apps/desktop/src/preload/electronApi.ts
@@ -2,6 +2,8 @@ import { electronAPI } from '@electron-toolkit/preload';
import type { ScreenCaptureSession } from '@lobechat/electron-client-ipc';
import { contextBridge, ipcRenderer } from 'electron';
+import { readSystemLanguageArg } from '~common/systemLanguage';
+
import { invoke } from './invoke';
import { onStreamInvoke } from './streamer';
@@ -55,6 +57,7 @@ export const setupElectronApi = () => {
isMacTahoe: process.platform === 'darwin' && darwinMajorVersion >= 25,
nodeVersion: process.versions.node,
platform: process.platform,
+ systemLanguage: readSystemLanguageArg(process.argv),
});
};
diff --git a/src/helpers/parserPlaceholder/index.ts b/src/helpers/parserPlaceholder/index.ts
index 86101287270..fb47bd44268 100644
--- a/src/helpers/parserPlaceholder/index.ts
+++ b/src/helpers/parserPlaceholder/index.ts
@@ -6,6 +6,7 @@ import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/selectors';
+import { getSystemLanguage } from '@/utils/client/systemLanguage';
import { resolveEffectiveWorkingDirectory } from '../effectiveWorkingDirectory';
import { globalAgentContextManager } from '../GlobalAgentContextManager';
@@ -132,7 +133,7 @@ export const VARIABLE_GENERATORS = {
* | `{{user_agent}}` | Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36 Edg/132.0.0.0 |
*
*/
- language: () => (typeof navigator !== 'undefined' ? navigator.language : ''),
+ language: () => (typeof navigator !== 'undefined' ? getSystemLanguage() : ''),
platform: () => (typeof navigator !== 'undefined' ? navigator.platform : ''),
user_agent: () => (typeof navigator !== 'undefined' ? navigator.userAgent : ''),
diff --git a/src/store/global/selectors/general.ts b/src/store/global/selectors/general.ts
index d1c10078d06..2c97e406fde 100644
--- a/src/store/global/selectors/general.ts
+++ b/src/store/global/selectors/general.ts
@@ -1,5 +1,6 @@
import { DEFAULT_LANG } from '@/const/locale';
import { type Locales } from '@/locales/resources';
+import { getSystemLanguage } from '@/utils/client/systemLanguage';
import { isOnServerSide } from '@/utils/env';
import { type GlobalState } from '../initialState';
@@ -13,7 +14,7 @@ const currentLanguage = (s: GlobalState) => {
if (locale === 'auto') {
if (isOnServerSide) return DEFAULT_LANG;
- return navigator.language as Locales;
+ return getSystemLanguage() as Locales;
}
return locale as Locales;
diff --git a/src/store/user/slices/settings/selectors/general.ts b/src/store/user/slices/settings/selectors/general.ts
index b2c5ec9cc66..d9d5c68f77b 100644
--- a/src/store/user/slices/settings/selectors/general.ts
+++ b/src/store/user/slices/settings/selectors/general.ts
@@ -2,6 +2,7 @@ import { isDesktop } from '@lobechat/const';
import { DEFAULT_LANG } from '@/const/locale';
import { type Locales, normalizeLocale } from '@/locales/resources';
+import { getSystemLanguage } from '@/utils/client/systemLanguage';
import { isOnServerSide } from '@/utils/env';
import { type UserStore } from '../../../store';
@@ -28,7 +29,7 @@ const currentResponseLanguage = (s: UserStore): Locales => {
if (locale) return normalizeLocale(locale);
if (isOnServerSide) return DEFAULT_LANG;
- return normalizeLocale(navigator.language);
+ return normalizeLocale(getSystemLanguage());
};
const telemetry = (s: UserStore) => generalConfig(s).telemetry;
const enableAutoScrollOnStreaming = (s: UserStore) =>
diff --git a/src/types/global.d.ts b/src/types/global.d.ts
index 61975e62531..88d64dde74b 100644
--- a/src/types/global.d.ts
+++ b/src/types/global.d.ts
@@ -35,6 +35,7 @@ declare global {
isMacTahoe?: boolean;
nodeVersion?: string;
platform?: NodeJS.Platform;
+ systemLanguage?: string;
};
}
diff --git a/src/utils/client/switchLang.test.ts b/src/utils/client/switchLang.test.ts
index 8c86d54fd79..af1c1626c9b 100644
--- a/src/utils/client/switchLang.test.ts
+++ b/src/utils/client/switchLang.test.ts
@@ -39,4 +39,16 @@ describe('switchLang', () => {
expect(document.documentElement.lang).toBe(navigatorLanguage);
expect(setCookie).toHaveBeenCalledWith(LOBE_LOCALE_COOKIE, undefined, 365);
});
+
+ it('should prefer the desktop system language over a poisoned navigator.language', () => {
+ vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US');
+ vi.stubGlobal('lobeEnv', { systemLanguage: 'zh-CN' });
+
+ switchLang('auto');
+
+ expect(changeLanguage).toHaveBeenCalledWith('zh-CN');
+ expect(document.documentElement.lang).toBe('zh-CN');
+
+ vi.unstubAllGlobals();
+ });
});
diff --git a/src/utils/client/switchLang.ts b/src/utils/client/switchLang.ts
index b805c099adf..0b656aa2d64 100644
--- a/src/utils/client/switchLang.ts
+++ b/src/utils/client/switchLang.ts
@@ -3,9 +3,10 @@ import { changeLanguage } from 'i18next';
import { LOBE_LOCALE_COOKIE } from '@/const/locale';
import { type LocaleMode } from '@/types/locale';
+import { getSystemLanguage } from '@/utils/client/systemLanguage';
export const switchLang = (locale: LocaleMode) => {
- const lang = locale === 'auto' ? navigator.language : locale;
+ const lang = locale === 'auto' ? getSystemLanguage() : locale;
changeLanguage(lang);
document.documentElement.lang = lang;
diff --git a/src/utils/client/systemLanguage.ts b/src/utils/client/systemLanguage.ts
new file mode 100644
index 00000000000..8fd8efbc7ad
--- /dev/null
+++ b/src/utils/client/systemLanguage.ts
@@ -0,0 +1,7 @@
+/**
+ * On desktop, `navigator.language` reports English regardless of the OS setting
+ * because packaging prunes the locales Chromium resolves its app locale from.
+ * The main process reads the OS language directly and hands it to the preload.
+ */
+export const getSystemLanguage = (): string =>
+ (typeof window !== 'undefined' && window.lobeEnv?.systemLanguage) || navigator.language;