A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!
TypeScript agent-skillsaidsh-pluginhacktoberfestjavascriptmcp-serverreactresume-builderself-hostedtypescript
fix: restore account language on unconfigured devices
Amruth Pillai42e01a0bff6a
diff --git a/apps/mobile/app/(tabs)/settings/preferences.tsx b/apps/mobile/app/(tabs)/settings/preferences.tsxindex 4f84759c3..c8d0e8ffc 100644--- a/apps/mobile/app/(tabs)/settings/preferences.tsx+++ b/apps/mobile/app/(tabs)/settings/preferences.tsx@@ -4,13 +4,20 @@ import { useLingui } from "@lingui/react/macro";import { useMutation, useQueryClient } from "@tanstack/react-query";import { useState } from "react";import { DevSettings, View, useWindowDimensions } from "react-native";+import { isLocale } from "@reactive-resume/utils/locale";import { filterOptions } from "@reactive-resume/utils/string";import { timezoneSchema } from "@reactive-resume/utils/timezone";import { client, orpc } from "@/api/client";import { SettingsGroup, SettingsPage } from "@/features/settings/layout";import { getLocaleOptions } from "@/features/settings/locale-names";import { useProfile } from "@/features/settings/queries";-import { getDeviceLocale, getLocalePreference, selectableLocales, setLocalePreference } from "@/i18n";+import {+ getDeviceLocale,+ getLocalePreference,+ hasLocalePreference,+ selectableLocales,+ setLocalePreference,+} from "@/i18n";import { timeZones } from "@/lib/timezones";import { CharacterShortcutSetting } from "@/shell/shortcut-help";import {@@ -45,6 +52,11 @@ export default function PreferencesScreen() {const profile = useProfile();const queryClient = useQueryClient();const [locale, setLocale] = useState(getLocalePreference);+ const selectedLocale = hasLocalePreference()+ ? locale+ : isLocale(profile.data?.locale) && selectableLocales.includes(profile.data.locale)+ ? profile.data.locale+ : null;const [picker, setPicker] = useState<"language" | "timezone" | null>(null);const [search, setSearch] = useState("");const [zoneLimit, setZoneLimit] = useState(40);@@ -127,7 +139,7 @@ export default function PreferencesScreen() {><ListRowtitle={t`Language`}- subtitle={locale ? languageName(locale) : t`System`}+ subtitle={selectedLocale ? languageName(selectedLocale) : t`System`}leading="translate"chevrononPress={() => openPicker("language")}@@ -174,7 +186,7 @@ export default function PreferencesScreen() {<ListRowtitle={t`System`}subtitle={languageName(getDeviceLocale())}- selected={locale === null}+ selected={selectedLocale === null}disabled={changingLanguage}onPress={() => void chooseLanguage(null)}/>@@ -183,7 +195,7 @@ export default function PreferencesScreen() {key={value}title={label}subtitle={description}- selected={locale === value}+ selected={selectedLocale === value}disabled={changingLanguage}onPress={() => void chooseLanguage(value)}/>diff --git a/apps/mobile/app/_layout.tsx b/apps/mobile/app/_layout.tsxindex df8179189..21d6cc583 100644--- a/apps/mobile/app/_layout.tsx+++ b/apps/mobile/app/_layout.tsx@@ -9,6 +9,7 @@ import { Stack, ThemeProvider } from "expo-router";import * as SplashScreen from "expo-splash-screen";import { StatusBar } from "expo-status-bar";import { useEffect, useState } from "react";+import { DevSettings } from "react-native";import { GestureHandlerRootView } from "react-native-gesture-handler";import { KeyboardProvider } from "react-native-keyboard-controller";import { SafeAreaProvider } from "react-native-safe-area-context";@@ -23,7 +24,7 @@ import { useReviewPrompt } from "@/features/reviews/use-review-prompt";import { useAccountLocale } from "@/features/settings/account-locale";import { i18n, initI18n } from "@/i18n";import { KeyboardShortcuts, ShortcutHelpButton } from "@/shell/shortcut-help";-import { EmptyState, Screen, Toaster, WindowSafeAreaProvider, useReducedMotion, useTheme } from "@/ui";+import { ConfirmDialog, EmptyState, Screen, Toaster, WindowSafeAreaProvider, useReducedMotion, useTheme } from "@/ui";import { fontAssets } from "@/ui/fonts";import { initTheme } from "@/ui/theme";@@ -80,7 +81,7 @@ function RootStack() {const reduced = useReducedMotion();useOpenReminder();useReviewPrompt();- useAccountLocale();+ const accountLocale = useAccountLocale();return (<ThemeProvider value={navigationTheme}>@@ -106,6 +107,18 @@ function RootStack() {<Stack.Screen name="r/[username]/[slug]" options={{ title: t`Resume` }} /></Stack><KeyboardShortcuts />+ <ConfirmDialog+ open={accountLocale.restart}+ title={t`Restart to change text direction`}+ message={t`Your language is saved. Restart Reactive Resume to apply the new left-to-right or right-to-left layout.`}+ confirmLabel={__DEV__ ? t`Reload now` : t`Done`}+ cancelLabel={t`Later`}+ onCancel={accountLocale.dismissRestart}+ onConfirm={() => {+ accountLocale.dismissRestart();+ if (__DEV__) DevSettings.reload();+ }}+ /></ThemeProvider>);}diff --git a/apps/mobile/locales/ar-SA.po b/apps/mobile/locales/ar-SA.poindex 153269cb9..2e6ee0807 100644--- a/apps/mobile/locales/ar-SA.po+++ b/apps/mobile/locales/ar-SA.po@@ -11925,12 +11925,12 @@ msgstr "أقصر"#: src/features/applications/list-screen.tsxmsgid "Show"-msgstr "يعرض"+msgstr "عرض"#: src/features/assistant/messages.tsxmsgctxt "Open a folded edit card"msgid "Show"-msgstr ""+msgstr "عرض"#: src/features/share/web-page.tsxmsgid "Show “Made with Reactive Resume”"diff --git a/apps/mobile/scripts/account-locale.test.mjs b/apps/mobile/scripts/account-locale.test.mjsindex e5ac63751..51f727dae 100644--- a/apps/mobile/scripts/account-locale.test.mjs+++ b/apps/mobile/scripts/account-locale.test.mjs@@ -13,9 +13,13 @@ const code = transformSync(function harness(saved = "en-US") {const state = { scope: "account-A", locale: "ar-SA", data: saved === undefined ? undefined : { locale: saved } };+ state.explicit = true;+ state.session = { status: "signed-in", server: "https://resume.example" };const effects = [];const writes = [];const invalidations = [];+ const activations = [];+ const restarts = [];let finish;const response = new Promise((resolve) => (finish = resolve));const mocks = {@@ -24,15 +28,29 @@ function harness(saved = "en-US") {useQuery: () => ({ data: state.data }),useQueryClient: () => ({ invalidateQueries: (options) => invalidations.push(options) }),},- react: { useEffect: (effect) => effects.push(effect) },- "@reactive-resume/utils/locale": { isLocale: (locale) => ["en-US", "ar-SA"].includes(locale) },+ react: { useEffect: (effect) => effects.push(effect), useState: () => [null, (value) => restarts.push(value)] },+ "@reactive-resume/utils/locale": {+ isLocale: (locale) => ["en-US", "ar-SA"].includes(locale),+ isRTL: (locale) => locale === "ar-SA",+ },+ "react-native": { I18nManager: { isRTL: false } },"@/api/client": {client: { auth: { updateProfile: (...args) => (writes.push(args), response) } },orpc: { auth: { getProfile: { key: () => ["profile"], queryOptions: (options) => options } } },},"@/auth/session": {getAccountScope: () => state.scope,- useSession: () => ({ status: "signed-in", server: "https://resume.example" }),+ getSession: () => state.session,+ useSession: () => state.session,+ },+ "@/i18n": {+ hasLocalePreference: () => state.explicit,+ getDeviceLocale: () => "en-US",+ selectableLocales: ["en-US", "ar-SA"],+ activateLocale: (locale, current) => {+ activations.push({ locale, current });+ return response.then(() => current());+ },},};const module = { exports: {} };@@ -48,6 +66,8 @@ function harness(saved = "en-US") {state,writes,invalidations,+ activations,+ restarts,finish,render: module.exports.useAccountLocale,effect: () => effects.shift()(),@@ -65,6 +85,58 @@ test("language sync stays bound to the rendered account and ignores its late sucassert.deepEqual(h.invalidations, []);});+test("an unconfigured device restores the account without overwriting it", async () => {+ const h = harness();+ h.state.explicit = false;+ h.render();+ h.effect();+ assert.deepEqual(h.writes, []);+ assert.equal(h.activations[0].locale, "en-US");+ assert.equal(h.activations[0].current(), true);+ h.finish();+ await new Promise(setImmediate);+ assert.deepEqual(h.restarts, []);+});++test("account replacement, cleanup and an explicit choice each fence derived catalog activation", () => {+ for (const replace of [+ (h) => (h.state.scope = "account-B"),+ (h) => (h.state.session = { ...h.state.session }),+ (h) => (h.state.explicit = true),+ (_, cleanup) => cleanup(),+ ]) {+ const h = harness();+ h.state.explicit = false;+ h.render();+ const cleanup = h.effect();+ replace(h, cleanup);+ assert.equal(h.activations[0].current(), false);+ }+});++test("missing, unsupported and old-server account languages follow the device without a write", () => {+ for (const data of [{}, { locale: null }, { locale: "unsupported" }]) {+ const h = harness();+ h.state.data = data;+ h.state.explicit = false;+ h.render();+ h.effect();+ assert.equal(h.activations[0].locale, "en-US");+ assert.deepEqual(h.writes, []);+ }+});++test("sign-out returns an unconfigured device to its language", () => {+ const h = harness("ar-SA");+ h.state.explicit = false;+ h.state.scope = null;+ h.state.session = { ...h.state.session, status: "signed-out" };+ h.render();+ h.effect();+ assert.equal(h.activations[0].locale, "en-US");+ assert.deepEqual(h.writes, []);+});+test("account replaced between render and effect sends no old account language", () => {const h = harness();h.render();@@ -82,3 +154,14 @@ test("old servers without language support and already synchronized accounts recassert.deepEqual(h.writes, []);}});++test("derived RTL language shows restart guidance while explicit language leaves it to Preferences", () => {+ const h = harness("ar-SA");+ h.state.explicit = false;+ const view = h.render();+ assert.equal(view.restart, true);+ view.dismissRestart();+ assert.deepEqual(h.restarts, [{ session: h.state.session, locale: "ar-SA" }]);+ h.state.explicit = true;+ assert.equal(h.render().restart, false);+});diff --git a/apps/mobile/scripts/locale.test.mjs b/apps/mobile/scripts/locale.test.mjsindex 7105695cc..f708677ac 100644--- a/apps/mobile/scripts/locale.test.mjs+++ b/apps/mobile/scripts/locale.test.mjs@@ -14,6 +14,7 @@ const code = transformSync(readFileSync(new URL("../src/i18n/index.ts", import.mfunction load(development, deviceLocales) {const storage = new Map([["locale", "zu-ZA"]]);+ const directions = [];let active;const dependencies = {"@reactive-resume/utils/locale": localeUtils,@@ -24,7 +25,14 @@ function load(development, deviceLocales) {setItemSync: (key, value) => storage.set(key, value),removeItemSync: (key) => storage.delete(key),},- "react-native": { I18nManager: { isRTL: false }, Platform: { OS: "android" } },+ "react-native": {+ I18nManager: {+ isRTL: false,+ allowRTL: (rtl) => directions.push(["allow", rtl]),+ forceRTL: (rtl) => directions.push(["force", rtl]),+ },+ Platform: { OS: "android" },+ },};const module = { exports: {} };new Function("require", "module", "exports", "__DEV__", code)(@@ -37,7 +45,7 @@ function load(development, deviceLocales) {module.exports,development,);- return { ...module.exports, storage, active: () => active };+ return { ...module.exports, storage, directions, active: () => active };}test("production recovers saved pseudo-locale to the device language and excludes it from choices", async () => {@@ -48,13 +56,51 @@ test("production recovers saved pseudo-locale to the device language and excludeassert.equal(app.active().locale, "de-DE");assert.match(app.active().messages.catalog, /de-DE\.po$/);await app.setLocalePreference("zu-ZA");- assert.equal(app.storage.has("locale"), false);+ assert.equal(app.storage.get("locale"), "system");+ assert.equal(app.hasLocalePreference(), true);assert.equal(app.active().locale, "de-DE");await app.setLocalePreference("fr-FR");assert.equal(app.getLocalePreference(), "fr-FR");assert.equal(app.active().locale, "fr-FR");});+test("unconfigured and explicit System are distinct, and derived account languages are never saved locally", async () => {+ const app = load(false, [{ languageTag: "de-DE" }]);+ app.storage.clear();+ assert.equal(app.hasLocalePreference(), false);+ await app.activateLocale("fr-FR");+ assert.equal(app.active().locale, "fr-FR");+ assert.equal(app.hasLocalePreference(), false);+ await app.setLocalePreference(null);+ assert.equal(app.active().locale, "de-DE");+ assert.equal(app.getLocalePreference(), null);+ assert.equal(app.hasLocalePreference(), true);+});++test("a replaced account and a newer local choice prevent a late catalog from activating", async () => {+ const app = load(false, [{ languageTag: "de-DE" }]);+ await app.initI18n();+ await app.activateLocale("fr-FR", () => false);+ assert.equal(app.active().locale, "de-DE");+ await Promise.all([app.activateLocale("fr-FR"), app.setLocalePreference("en-US")]);+ assert.equal(app.active().locale, "en-US");+ assert.equal(app.getLocalePreference(), "en-US");+});++test("a restored RTL catalog requests a restart without saving an explicit preference", async () => {+ const app = load(false, [{ languageTag: "en-US" }]);+ app.storage.clear();+ assert.equal(await app.activateLocale("ar-SA"), true);+ assert.equal(app.active().locale, "ar-SA");+ assert.deepEqual(app.directions, [+ ["allow", true],+ ["force", true],+ ]);+ assert.equal(app.hasLocalePreference(), false);+ assert.equal(await app.activateLocale("he-IL", () => false), false);+ assert.equal(app.active().locale, "ar-SA");+});+test("a Zulu device never gets pseudo-English automatically, including in development", () => {for (const development of [false, true]) {const app = load(development, [diff --git a/apps/mobile/src/features/settings/account-locale.ts b/apps/mobile/src/features/settings/account-locale.tsindex 363ed92da..b77a5b70f 100644--- a/apps/mobile/src/features/settings/account-locale.ts+++ b/apps/mobile/src/features/settings/account-locale.ts@@ -1,18 +1,20 @@import { useLingui } from "@lingui/react";import { useQuery, useQueryClient } from "@tanstack/react-query";-import { useEffect } from "react";-import { isLocale } from "@reactive-resume/utils/locale";+import { useEffect, useState } from "react";+import { I18nManager } from "react-native";+import { isLocale, isRTL } from "@reactive-resume/utils/locale";import { client, orpc } from "@/api/client";-import { getAccountScope, useSession } from "@/auth/session";+import { getAccountScope, getSession, useSession } from "@/auth/session";+import { activateLocale, getDeviceLocale, hasLocalePreference, selectableLocales } from "@/i18n";/**- * The account's language follows the interface it was last used in, the same as on the web, so account emails- * (password reset, email change) arrive in it. A server from before accounts had a language reports none; nothing is- * sent to it.+ * Restore the account language on an unconfigured device. Explicit local choices win and update account emails;+ * a server from before accounts had a language reports none and receives no write.*/export function useAccountLocale() {const { i18n } = useLingui();const session = useSession();+ const [dismissed, setDismissed] = useState<{ session: typeof session; locale: string } | null>(null);const scope = getAccountScope();const queryClient = useQueryClient();const profile = useQuery(@@ -25,8 +27,21 @@ export function useAccountLocale() {);const saved = profile.data && "locale" in profile.data ? profile.data.locale : undefined;const locale = i18n.locale;+ const explicit = hasLocalePreference();useEffect(() => {+ if (!explicit) {+ let active = true;+ const current = () => active && getSession() === session && getAccountScope() === scope && !hasLocalePreference();+ const target =+ session.status === "signed-in" && scope && isLocale(saved) && selectableLocales.includes(saved)+ ? saved+ : getDeviceLocale();+ if (target !== locale) void activateLocale(target, current).catch(() => undefined);+ return () => {+ active = false;+ };+ }if (!scope || getAccountScope() !== scope || saved === undefined || saved === locale || !isLocale(locale)) return;// Best effort: an account email falls back to English.client.auth@@ -36,5 +51,13 @@ export function useAccountLocale() {return queryClient.invalidateQueries({ queryKey: [...orpc.auth.getProfile.key(), scope] });}).catch(() => undefined);- }, [scope, saved, locale, queryClient]);+ }, [scope, saved, locale, queryClient, explicit, session]);++ return {+ restart:+ !explicit &&+ isRTL(locale) !== I18nManager.isRTL &&+ (dismissed?.session !== session || dismissed.locale !== locale),+ dismissRestart: () => setDismissed({ session, locale }),+ };}diff --git a/apps/mobile/src/i18n/index.ts b/apps/mobile/src/i18n/index.tsindex 0efa0bda5..6192e599d 100644--- a/apps/mobile/src/i18n/index.ts+++ b/apps/mobile/src/i18n/index.ts@@ -1,4 +1,4 @@-// Interface language: the device locale (expo-localization) unless the user picked one in Settings → Preferences.+// Local language choices win; unconfigured devices restore the account language or follow expo-localization.// Catalogs are apps/mobile/locales/*.po, seeded from the web catalogs by scripts/seed-locales.mjs.import type { Messages } from "@lingui/core";import type { Locale } from "@reactive-resume/utils/locale";@@ -16,6 +16,7 @@ import {} from "@reactive-resume/utils/locale";const storageKey = "locale";+let activation = 0;export const selectableLocales = __DEV__ ? localeSchema.options : supportedLocales;// Static paths, so Metro can bundle each catalog.@@ -88,6 +89,11 @@ export function getLocalePreference(): Locale | null {return isLocale(stored) && selectableLocales.includes(stored) ? stored : null;}+/** An explicit System choice must survive account language restoration. */+export function hasLocalePreference(): boolean {+ return Storage.getItemSync(storageKey) === "system" || getLocalePreference() !== null;+}+/*** Saves the override (null follows the device) and activates it. Changing between a left-to-right and a* right-to-left language only flips the layout after the app restarts: React Native reads the direction at launch.@@ -95,15 +101,16 @@ export function getLocalePreference(): Locale | null {*/export function setLocalePreference(value: Locale | null): Promise<boolean> {const locale = value && selectableLocales.includes(value) ? value : null;- if (locale) Storage.setItemSync(storageKey, locale);- else Storage.removeItemSync(storageKey);+ Storage.setItemSync(storageKey, locale ?? "system");return activateLocale(locale ?? getDeviceLocale());}/** Loads and activates a catalog. Returns true when the layout direction changes on the next launch. */-export async function activateLocale(value: Locale) {+export async function activateLocale(value: Locale, current = () => true) {+ const request = ++activation;const locale = selectableLocales.includes(value) ? value : defaultLocale;const { messages } = await loaders[locale]().catch(() => loaders[defaultLocale]());+ if (request !== activation || !current()) return false;i18n.loadAndActivate({ locale, messages });const rtl = isRTL(locale);diff --git a/apps/web/locales/ar-SA.po b/apps/web/locales/ar-SA.poindex a37102c18..d41c60b24 100644--- a/apps/web/locales/ar-SA.po+++ b/apps/web/locales/ar-SA.po@@ -3347,7 +3347,7 @@ msgstr "تغيير"#: src/features/career/coach-thread.tsxmsgctxt "Change what the coach remembers"msgid "Change"-msgstr ""+msgstr "تغيير"#: src/features/career/coach-chat.tsx#: src/features/settings/ai/web-access.tsx@@ -14829,7 +14829,7 @@ msgstr "عرض"#: src/features/resume/editor/proposals/proposal-list.tsxmsgctxt "Open a folded edit card"msgid "Show"-msgstr ""+msgstr "عرض"#: src/features/resume/share/share-panel.tsxmsgid "Show “Made with Reactive Resume”"diff --git a/apps/web/src/libs/locale.test.ts b/apps/web/src/libs/locale.test.tsindex 7ec955773..63c28f1eb 100644--- a/apps/web/src/libs/locale.test.ts+++ b/apps/web/src/libs/locale.test.ts@@ -2,8 +2,9 @@// @vitest-environment-options {"url":"https://localhost:3000"}import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";+import { i18n } from "@lingui/core";import Cookies from "js-cookie";-import { changeLocale, getLocale } from "./locale";+import { changeLocale, getLocale, hasLocalePreference, loadLocale } from "./locale";beforeEach(() => {Cookies.remove("locale");@@ -19,6 +20,36 @@ afterEach(() => {});describe("first-visit language", () => {+ it("does not activate a catalog whose account was replaced while it loaded", async () => {+ await loadLocale("en-US");+ await loadLocale("ar-SA", () => false);+ expect(i18n.locale).toBe("en-US");+ await loadLocale("de-DE", () => true);+ expect(i18n.locale).toBe("de-DE");+ });++ it("restores the saved account language without making it an explicit browser choice", () => {+ expect(getLocale("de-DE")).toBe("de-DE");+ expect(Cookies.get("locale")).toBeUndefined();+ expect(hasLocalePreference()).toBe(false);+ expect(getLocale("ar-SA")).toBe("ar-SA");+ expect(getLocale()).toBe("en-US");+ });++ it.each([null, undefined, "unsupported"])("falls back to the browser for account locale %s", (saved) => {+ vi.stubGlobal("navigator", { languages: ["fr-CA"] });+ expect(getLocale(saved)).toBe("fr-FR");+ expect(hasLocalePreference()).toBe(false);+ });++ it("keeps explicit local and URL languages ahead of the account", () => {+ Cookies.set("locale", "ja-JP");+ expect(getLocale("de-DE")).toBe("ja-JP");+ expect(hasLocalePreference()).toBe(true);+ window.history.replaceState(null, "", "/?locale=ar-SA");+ expect(getLocale("de-DE")).toBe("ar-SA");+ });+it("follows the browser without persisting an inferred choice", () => {vi.stubGlobal("navigator", { languages: ["unsupported", "de-AT", "fr-FR"] });window.history.replaceState({ key: "visit" }, "", "/ats-checker?campaign=first#check");diff --git a/apps/web/src/libs/locale.ts b/apps/web/src/libs/locale.tsindex c1ef81339..bb2fad305 100644--- a/apps/web/src/libs/locale.ts+++ b/apps/web/src/libs/locale.ts@@ -115,7 +115,10 @@ export function formatRelativeTime(value: Date | string, locale: string, style:: formatter.format(0, "second");}-export const getLocale = () => {+export const hasLocalePreference = () =>+ isLocale(new URLSearchParams(window.location.search).get(storageKey)) || Cookies.get(storageKey) !== undefined;++export const getLocale = (accountLocale?: unknown) => {// A `?locale=` address (the homepage's hreflang alternates) picks the language and keeps it, like the switcher.const requested = new URLSearchParams(window.location.search).get(storageKey);if (isLocale(requested)) {@@ -126,6 +129,7 @@ export const getLocale = () => {const saved = Cookies.get(storageKey);if (saved !== undefined) return resolveLocale(saved);+ if (isLocale(accountLocale) && selectableLocales.includes(accountLocale)) return accountLocale;// Browser hints affect the app only; neither persist them nor vary shared server HTML by Accept-Language.return getPreferredLocale(navigator.languages ?? []);};@@ -152,11 +156,11 @@ export const getLocaleMessages = async (locale: string) => {}};-export const loadLocale = async (locale: string) => {+export const loadLocale = async (locale: string, current = () => true) => {// Re-activating the active locale emits "change" and re-renders every translated component.if (i18n.locale === locale) return;const { locale: resolvedLocale, messages } = await getLocaleMessages(locale);- i18n.loadAndActivate({ locale: resolvedLocale, messages });+ if (current()) i18n.loadAndActivate({ locale: resolvedLocale, messages });};export const changeLocale = (value: string | null) => {diff --git a/apps/web/src/libs/root-context.test.ts b/apps/web/src/libs/root-context.test.tsindex 6ac113200..c1bd2c3fc 100644--- a/apps/web/src/libs/root-context.test.ts+++ b/apps/web/src/libs/root-context.test.ts@@ -13,6 +13,7 @@ const getSessionMock = vi.hoisted(() => vi.fn());const flagsGetMock = vi.hoisted(() => vi.fn().mockResolvedValue({ disableSignups: false, disableEmailAuth: false }));const localeMock = vi.hoisted(() => vi.fn().mockReturnValue("en-US"));+const explicitLocaleMock = vi.hoisted(() => vi.fn().mockReturnValue(true));const loadLocaleMock = vi.hoisted(() => vi.fn().mockResolvedValue(undefined));const updateProfileMock = vi.hoisted(() => vi.fn().mockResolvedValue({ status: true }));@@ -23,6 +24,7 @@ vi.mock("./auth/session", () => ({vi.mock("./locale", () => ({getLocale: localeMock,+ hasLocalePreference: explicitLocaleMock,loadLocale: loadLocaleMock,}));@@ -53,6 +55,7 @@ describe("loadRootContext", () => {registerAccountReset(() => undefined);loadLocaleMock.mockResolvedValue(undefined);localeMock.mockReturnValue("en-US");+ explicitLocaleMock.mockReturnValue(true);updateProfileMock.mockClear();});@@ -70,6 +73,25 @@ describe("loadRootContext", () => {expect(context.session).toEqual(mockSession);});+ it("resolves account language before catalog loading without writing an inferred preference", async () => {+ const cache = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ getSessionMock.mockResolvedValueOnce({ user: { id: "german", locale: "de-DE" }, session: { id: "german" } });+ explicitLocaleMock.mockReturnValue(false);+ localeMock.mockImplementationOnce((saved) => saved);+ const result = await loadRootContext(cache);+ expect(result.locale).toBe("de-DE");+ expect(loadLocaleMock).toHaveBeenLastCalledWith("de-DE", expect.any(Function));+ expect(updateProfileMock).not.toHaveBeenCalled();+ });++ it("does not save a browser hint over a missing account language", async () => {+ const cache = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ getSessionMock.mockResolvedValueOnce({ user: { id: "unconfigured", locale: null }, session: { id: "missing" } });+ explicitLocaleMock.mockReturnValue(false);+ await loadRootContext(cache);+ expect(updateProfileMock).not.toHaveBeenCalled();+ });+it("retains cached session when getSession encounters a transient error on refresh", async () => {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },diff --git a/apps/web/src/libs/root-context.ts b/apps/web/src/libs/root-context.tsindex b63356e56..ff89dcfa9 100644--- a/apps/web/src/libs/root-context.ts+++ b/apps/web/src/libs/root-context.ts@@ -2,14 +2,14 @@ import type { AuthSession } from "@reactive-resume/auth/types";import type { QueryClient } from "@tanstack/react-query";import { setAccountScope } from "./auth/account-scope";import { getSession } from "./auth/session";-import { getLocale, loadLocale } from "./locale";+import { getLocale, hasLocalePreference, loadLocale } from "./locale";import { client } from "./orpc/client";import { getTheme } from "./theme";export const sessionQueryKey = ["auth", "session"] as const;-// The account's language follows the interface it was last used in, so its emails (password reset, email change)-// arrive in that language. A different account, session or interface language needs its own check.+// Explicit interface choices update account emails; unconfigured browsers restore the account language instead.+// A different account, session or interface language needs its own check.let accountLocaleCheck: { userId: string; sessionId: string; locale: string } | null = null;const flagsQueryKey = ["flags"] as const;// Each root load is numbered. A load that finishes after a newer one must not certify its older session: a hover@@ -28,7 +28,7 @@ type RootLoadOptions = {export async function loadRootContext(queryClient: QueryClient, options: RootLoadOptions = {}) {const load = options.commit === false ? rootLoadSequence : ++rootLoadSequence;const theme = getTheme();- const locale = getLocale();+ const explicitLocale = hasLocalePreference() ? getLocale() : undefined;const sessionPromise = queryClient.query({@@ -48,8 +48,17 @@ export async function loadRootContext(queryClient: QueryClient, options: RootLoaconst [session, flags] = await Promise.all([sessionPromise,queryClient.query({ queryKey: flagsQueryKey, queryFn: () => client.flags.get(), staleTime: 5 * 60_000 }),- loadLocale(locale),]);+ const locale = explicitLocale ?? getLocale(session?.user.isAnonymous ? undefined : session?.user.locale);+ await loadLocale(locale, () => {+ const current = queryClient.getQueryData<AuthSession | null>(sessionQueryKey);+ return (+ load === rootLoadSequence &&+ options.commit !== false &&+ current?.user.id === session?.user.id &&+ current?.session.id === session?.session.id+ );+ });// A preload only prepares a future navigation; a stale completion has already been overtaken. Neither may adopt// an account scope, because the page on screen still belongs to the session it was rendered for.const current = queryClient.getQueryData<AuthSession | null>(sessionQueryKey);@@ -59,6 +68,7 @@ export async function loadRootContext(queryClient: QueryClient, options: RootLoaif (committed &&session &&+ hasLocalePreference() &&!session.user.isAnonymous &¤t?.user.id === session.user.id &¤t.session.id === session.session.id &&diff --git a/docs/guides/changing-appearance-and-language.mdx b/docs/guides/changing-appearance-and-language.mdxindex 07c5bdb13..80e907774 100644--- a/docs/guides/changing-appearance-and-language.mdx+++ b/docs/guides/changing-appearance-and-language.mdx@@ -44,7 +44,19 @@ The change applies at once. Reactive Resume remembers it in this browser for a yOn your first visit, the website follows your browser's preferred languages. It uses a supported regional variant when an exact match is unavailable, or English if none matches. This automatic choice isn't saved: a language in the page address (`?locale=`) or a choice already saved in this browser takes priority. Automatic selection needs JavaScript; homepage language links also work without it.-The Android and iPhone apps follow your device's preferred languages until you choose a language in Preferences.+After sign-in on a browser or device without a language choice, Reactive Resume restores your account's saved language.+If the account has none, it follows the browser or device. Automatic choices don't replace your account language or become a local override.++The Android and iPhone apps also restore your account language on an unconfigured device. Choosing **System** in Preferences+explicitly follows that device instead. A switch between left-to-right and right-to-left languages shows a restart notice;+the language changes immediately, and restarting applies the layout direction.++<Frame caption="Account language restored in a fresh browser">+ <img+ src="/images/guides/changing-appearance-and-language/account-language-restored.png"+ alt="Fictional Maya Chen account in German Preferences, with Deutsch selected after opening a fresh English-language browser"+ />+</Frame><Steps><Step title="Open Preferences">diff --git a/docs/images/guides/changing-appearance-and-language/account-language-restored.png b/docs/images/guides/changing-appearance-and-language/account-language-restored.pngnew file mode 100644index 000000000..206c77152Binary files /dev/null and b/docs/images/guides/changing-appearance-and-language/account-language-restored.png differdiff --git a/tests/e2e/specs/account-language.spec.ts b/tests/e2e/specs/account-language.spec.tsnew file mode 100644index 000000000..c6ff21d51--- /dev/null+++ b/tests/e2e/specs/account-language.spec.ts@@ -0,0 +1,56 @@+import { expect, test } from "../fixtures/test";++for (const width of [390, 1440]) {+ test(`restores account language on a fresh browser while explicit choices win at ${width}px`, async ({+ authPage,+ browser,+ baseURL,+ }, testInfo) => {+ expect(+ (+ await authPage.request.patch("/api/openapi/auth/profile", { data: { name: "Maya Chen", locale: "de-DE" } })+ ).status(),+ ).toBe(200);+ const state = await authPage.context().storageState();+ const context = await browser.newContext({+ baseURL,+ locale: "en-US",+ viewport: { width, height: 900 },+ storageState: { cookies: state.cookies.filter((cookie) => cookie.name !== "locale"), origins: [] },+ });+ try {+ const page = await context.newPage();+ const writes: string[] = [];+ page.on("request", (request) => {+ if (request.url().includes("/auth/updateProfile")) writes.push(request.url());+ });+ await page.goto("/dashboard/settings/preferences");+ await expect(page.getByRole("heading", { level: 1 })).toBeVisible();+ await expect(page.locator("html")).toHaveAttribute("lang", "de-DE");+ expect((await (await page.request.get("/api/openapi/auth/profile")).json()).locale).toBe("de-DE");+ expect((await context.cookies()).some((cookie) => cookie.name === "locale")).toBe(false);+ expect(writes).toEqual([]);+ await page.reload();+ await expect(page.locator("html")).toHaveAttribute("lang", "de-DE");+ await page.screenshot({ path: testInfo.outputPath("restored-language.png"), animations: "disabled" });++ await context.addCookies([{ name: "locale", value: "ar-SA", url: baseURL ?? "http://localhost:3000" }]);+ await Promise.all([+ page.waitForResponse((response) => response.url().includes("/auth/updateProfile") && response.status() === 200),+ page.goto("/dashboard/settings/preferences"),+ ]);+ await expect(page.locator("html")).toHaveAttribute("lang", "ar-SA");+ expect((await (await page.request.get("/api/openapi/auth/profile")).json()).locale).toBe("ar-SA");++ await Promise.all([+ page.waitForResponse((response) => response.url().includes("/auth/updateProfile") && response.status() === 200),+ page.goto("/dashboard/settings/preferences?locale=en-US"),+ ]);+ await expect(page.locator("html")).toHaveAttribute("lang", "en-US");+ expect((await (await page.request.get("/api/openapi/auth/profile")).json()).locale).toBe("en-US");+ expect((await context.cookies()).find((cookie) => cookie.name === "locale")?.value).toBe("en-US");+ } finally {+ await context.close();+ }+ });+}diff --git a/tests/e2e/specs/first-visit-language.spec.ts b/tests/e2e/specs/first-visit-language.spec.tsindex 07a79773b..c41e89f04 100644--- a/tests/e2e/specs/first-visit-language.spec.ts+++ b/tests/e2e/specs/first-visit-language.spec.ts@@ -22,7 +22,10 @@ test("explicit language wins and the saved choice survives navigation", async ({await expect(page.locator("html")).toHaveAttribute("lang", "fr-FR");await page.goto("/?locale=ja-JP&campaign=explicit");await expect(page.locator("html")).toHaveAttribute("lang", "ja-JP");- expect((await context.cookies()).find((cookie) => cookie.name === "locale")?.value).toBe("ja-JP");+ // Prerendered HTML already has this language; persistence waits for the app to start.+ await expect+ .poll(async () => (await context.cookies()).find((cookie) => cookie.name === "locale")?.value)+ .toBe("ja-JP");await page.goto("/auth/login");await expect(page.locator("html")).toHaveAttribute("lang", "ja-JP");});