Skip to content

The agent that grows with you

fix(desktop): reload language for the active profile and connection

Kevin Rajan51ff85255af8
diff --git a/apps/desktop/src/i18n/context.tsx b/apps/desktop/src/i18n/context.tsx
index 4db2d8763aa..5648d97ff35 100644
--- a/apps/desktop/src/i18n/context.tsx
+++ b/apps/desktop/src/i18n/context.tsx
@@ -90,18 +90,25 @@ export interface I18nProviderProps {
children: ReactNode
configClient?: I18nConfigClient | null
initialLocale?: unknown
+ /** Reconcile when the window's config owner changes, without remounting its children. */
+ scopeKey?: string
}
-export function I18nProvider({ children, configClient = defaultConfigClient, initialLocale }: I18nProviderProps) {
+export function I18nProvider({
+ children,
+ configClient = defaultConfigClient,
+ initialLocale,
+ scopeKey
+}: I18nProviderProps) {
const [locale, setLocaleState] = useState<Locale>(() => normalizeLocale(initialLocale))
const [isLoadingConfig, setIsLoadingConfig] = useState(false)
const [isSavingLocale, setIsSavingLocale] = useState(false)
const [configLoadError, setConfigLoadError] = useState<Error | null>(null)
const [saveError, setSaveError] = useState<Error | null>(null)
const localeRef = useRef(locale)
- // Set once the user picks a language through setLocale: a startup read that
- // resolves (or fails) after that must never overwrite an explicit choice.
+ // An explicit pick beats a late read in its own scope, not in other profiles.
const userLocaleRef = useRef(false)
+ const scopeGenerationRef = useRef(0)
// eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)
useEffect(() => {
@@ -110,7 +117,13 @@ export function I18nProvider({ children, configClient = defaultConfigClient, ini
applyDocumentLocale(locale)
}, [locale])
+ // eslint-disable-next-line no-restricted-syntax -- scope-local request generation and user intent, not an atom mirror
useEffect(() => {
+ scopeGenerationRef.current += 1
+ userLocaleRef.current = false
+ setSaveError(null)
+ setIsSavingLocale(false)
+
if (!configClient) {
return
}
@@ -182,16 +195,18 @@ export function I18nProvider({ children, configClient = defaultConfigClient, ini
return () => {
cancelled = true
+ scopeGenerationRef.current += 1
if (retryTimer) {
clearTimeout(retryTimer)
}
}
- }, [configClient, initialLocale])
+ }, [configClient, initialLocale, scopeKey])
const setLocale = useCallback(
async (next: Locale) => {
const previousLocale = localeRef.current
+ const generation = scopeGenerationRef.current
userLocaleRef.current = true
setSaveError(null)
@@ -213,12 +228,18 @@ export function I18nProvider({ children, configClient = defaultConfigClient, ini
} catch (error) {
const nextError = toError(error)
- setLocaleState(previousLocale)
- setSaveError(nextError)
+ // The write still belongs to the GET's captured origin, but its late
+ // outcome must not roll another profile's chrome back to this one.
+ if (generation === scopeGenerationRef.current) {
+ setLocaleState(previousLocale)
+ setSaveError(nextError)
+ }
throw nextError
} finally {
- setIsSavingLocale(false)
+ if (generation === scopeGenerationRef.current) {
+ setIsSavingLocale(false)
+ }
}
},
[configClient]
diff --git a/apps/desktop/src/i18n/profile-locale.test.tsx b/apps/desktop/src/i18n/profile-locale.test.tsx
new file mode 100644
index 00000000000..ef09bea74af
--- /dev/null
+++ b/apps/desktop/src/i18n/profile-locale.test.tsx
@@ -0,0 +1,147 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { afterEach, expect, it, vi } from 'vitest'
+
+import { setApiRequestConnection } from '@/api/client'
+import type { HermesApiRequest } from '@/global'
+import type { HermesConfigRecord } from '@/hermes'
+import { $activeGatewayProfile } from '@/store/profile'
+import { $connection } from '@/store/session'
+
+import { useI18n } from './context'
+import { ProfileI18nProvider as I18nProvider } from './profile-provider'
+
+function Probe() {
+ const { locale, setLocale, saveError, isSavingLocale } = useI18n()
+
+ return (
+ <>
+ <span data-testid="locale">{locale}</span>
+ <span data-testid="error">{saveError?.message}</span>
+ <span data-testid="saving">{String(isSavingLocale)}</span>
+ <button onClick={() => void setLocale('ja').catch(() => undefined)}>Japanese</button>
+ </>
+ )
+}
+
+function route(profile: string, connectionId: string | null = null) {
+ setApiRequestConnection(connectionId)
+ $connection.set(connectionId ? ({ connectionId } as never) : null)
+ $activeGatewayProfile.set(profile)
+}
+
+afterEach(() => {
+ cleanup()
+ route('default')
+ Reflect.deleteProperty(window, 'hermesDesktop')
+ vi.restoreAllMocks()
+})
+
+// Regression for #113980: exercise the real provider, API origin binding and
+// profile routing, including an explicit pick before leaving and a fresh mount.
+it('reads and persists the owning profile through A → B → A and restart', async () => {
+ const configs: Record<string, HermesConfigRecord> = {
+ default: { display: { language: 'en' } },
+ coder: { display: { language: 'zh', skin: 'mono' } }
+ }
+
+ const api = vi.fn(async (request: HermesApiRequest) => {
+ const key = request.profile || 'default'
+
+ if (request.method === 'PUT') {
+ configs[key] = structuredClone((request.body as { config: HermesConfigRecord }).config)
+
+ return { ok: true }
+ }
+
+ return structuredClone(configs[key])
+ })
+
+ window.hermesDesktop = { api } as never
+
+ const view = render(
+ <I18nProvider>
+ <Probe />
+ </I18nProvider>
+ )
+
+ await waitFor(() => expect(api).toHaveBeenCalled())
+ act(() => route('coder'))
+ await waitFor(() => expect(screen.getByTestId('locale').textContent).toBe('zh'))
+ fireEvent.click(screen.getByText('Japanese'))
+ await waitFor(() => expect(configs.coder.display).toEqual({ language: 'ja', skin: 'mono' }))
+ act(() => route('default'))
+ await waitFor(() => expect(screen.getByTestId('locale').textContent).toBe('en'))
+ act(() => route('coder'))
+ await waitFor(() => expect(screen.getByTestId('locale').textContent).toBe('ja'))
+ expect(configs.default.display).toEqual({ language: 'en' })
+ view.unmount()
+ render(
+ <I18nProvider>
+ <Probe />
+ </I18nProvider>
+ )
+ await waitFor(() => expect(screen.getByTestId('locale').textContent).toBe('ja'))
+})
+
+it('isolates stale reads and failed saves when the same profile moves between connections', async () => {
+ let finishBoot!: (config: HermesConfigRecord) => void
+ let finishSaveRead!: (config: HermesConfigRecord) => void
+ let rejectSave!: (reason: Error) => void
+ let reads = 0
+
+ const api = vi.fn((request: HermesApiRequest) => {
+ if (request.method === 'PUT') {
+ return new Promise((_, reject) => {
+ rejectSave = reject
+ })
+ }
+
+ reads += 1
+
+ if (reads === 1) {
+ return new Promise(resolve => {
+ finishBoot = resolve
+ })
+ }
+
+ if (reads === 3) {
+ return new Promise(resolve => {
+ finishSaveRead = resolve
+ })
+ }
+
+ return Promise.resolve({ display: { language: request.connectionId === 'remote' ? 'zh' : 'en' } })
+ })
+
+ window.hermesDesktop = { api } as never
+ render(
+ <I18nProvider>
+ <Probe />
+ </I18nProvider>
+ )
+ act(() => route('default', 'remote'))
+ await waitFor(() => expect(screen.getByTestId('locale').textContent).toBe('zh'))
+ await act(async () => finishBoot({ display: { language: 'ar' } }))
+ expect(screen.getByTestId('locale').textContent).toBe('zh')
+ fireEvent.click(screen.getByText('Japanese'))
+ await waitFor(() => expect(reads).toBe(3))
+ act(() => route('default', 'local'))
+ await waitFor(() => expect(screen.getByTestId('locale').textContent).toBe('en'))
+ await act(async () => finishSaveRead({ display: { language: 'zh' } }))
+ expect(api).toHaveBeenLastCalledWith(expect.objectContaining({ connectionId: 'remote', method: 'PUT' }))
+ await act(async () => rejectSave(new Error('remote save refused')))
+ expect(screen.getByTestId('locale').textContent).toBe('en')
+ expect(screen.getByTestId('error').textContent).toBe('')
+ expect(screen.getByTestId('saving').textContent).toBe('false')
+
+ // Legacy remotes may not have registry IDs. A new backend URL is still a
+ // new config owner even when the visible profile retains its name.
+ act(() => {
+ setApiRequestConnection(null)
+ $connection.set({ baseUrl: 'https://first.example' } as never)
+ })
+ await waitFor(() => expect(reads).toBe(5))
+ api.mockImplementation(() => Promise.resolve({ display: { language: 'ar' } }))
+ act(() => $connection.set({ baseUrl: 'https://second.example' } as never))
+ await waitFor(() => expect(screen.getByTestId('locale').textContent).toBe('ar'))
+})
diff --git a/apps/desktop/src/i18n/profile-provider.tsx b/apps/desktop/src/i18n/profile-provider.tsx
new file mode 100644
index 00000000000..e707ec3b8e5
--- /dev/null
+++ b/apps/desktop/src/i18n/profile-provider.tsx
@@ -0,0 +1,25 @@
+import { useStore } from '@nanostores/react'
+import type { ReactNode } from 'react'
+
+import { $activeGatewayProfile } from '@/store/profile'
+import { $connection } from '@/store/session'
+
+import { I18nProvider } from './context'
+
+/** Keep gateway/store imports outside the shared i18n context's import graph. */
+export function ProfileI18nProvider({ children }: { children: ReactNode }) {
+ const profile = useStore($activeGatewayProfile)
+ const connection = useStore($connection)
+
+ // The API captures the real read origin (including legacy profile overrides).
+ // This is an invalidation key, not an explicit local/registry request pin.
+ const scopeKey = JSON.stringify([
+ connection?.connectionId ?? null,
+ connection?.registryScoped ?? false,
+ connection?.baseUrl,
+ connection?.profile,
+ profile
+ ])
+
+ return <I18nProvider scopeKey={scopeKey}>{children}</I18nProvider>
+}
diff --git a/apps/desktop/src/main.tsx b/apps/desktop/src/main.tsx
index 24218d56634..0e9b8cc2507 100644
--- a/apps/desktop/src/main.tsx
+++ b/apps/desktop/src/main.tsx
@@ -24,7 +24,7 @@ import App from './app'
import { RootErrorBoundary } from './components/error-boundary'
import { HapticsProvider } from './components/haptics-provider'
import { RootTooltipProvider } from './components/ui/tooltip'
-import { I18nProvider } from './i18n'
+import { ProfileI18nProvider as I18nProvider } from './i18n/profile-provider'
import { installClipboardShim } from './lib/clipboard'
import { queryClient } from './lib/query-client'
import { installRendererAnimationPauseState } from './lib/renderer-loop-pause'