Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: optimize startup with on-demand language catalogs (#8623)

oobaboogaeb869b856cb5
diff --git a/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts b/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts
index 8416f35b13a..4d0761bea88 100644
--- a/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts
+++ b/studio/frontend/src/features/profile/hooks/use-personalization-sync.ts
@@ -19,6 +19,7 @@ import {
} from "@/features/settings";
import {
DEFAULT_LOCALE_PREFERENCE,
+ LOCALE_INITIALIZATION_TIMEOUT_MS,
type LocalePreference,
getLocalePreference,
isLocalePreference,
@@ -230,6 +231,7 @@ export function usePersonalizationSync(enabled: boolean): void {
return;
}
let cancelled = false;
+ const localeHydrationController = new AbortController();
void (async () => {
try {
const remote = await loadPersonalization();
@@ -295,8 +297,36 @@ export function usePersonalizationSync(enabled: boolean): void {
) {
useAppearanceCustomStore.getState().replaceAll(nextCustomization);
}
- if (nextLanguage !== latestLanguageRef.current)
- setLocale(nextLanguage);
+ if (nextLanguage !== latestLanguageRef.current) {
+ const localeResult = await setLocale(nextLanguage, {
+ signal: localeHydrationController.signal,
+ // A catalog that will not load must not decide whether the rest of
+ // personalization syncs. Adopting the preference and rendering
+ // English keeps the local preference equal to the server's, so the
+ // baseline below is honest and the debounced push cannot overwrite
+ // the remote language with a stale local one.
+ adoptOnFailure: true,
+ // And a catalog request that is accepted but never completes
+ // must not hold hydration, and with it every save for the rest
+ // of the session, open forever. Same bound as startup.
+ timeoutMs: LOCALE_INITIALIZATION_TIMEOUT_MS,
+ });
+ if (cancelled) return;
+ // "superseded" means a newer request took over, so this language is
+ // no longer the one in effect and must not be recorded as the
+ // synchronized baseline: the newer request may itself have failed,
+ // leaving the local preference on neither value. Hydration still has
+ // to finish, or every later save stays paused for the session; an
+ // empty baseline makes the next push send whatever is in effect.
+ if (localeResult === "cancelled") return;
+ if (localeResult === "superseded") {
+ if (authGenerationRef.current === generation) {
+ lastSavedRef.current = "";
+ setHydratedGeneration(generation);
+ }
+ return;
+ }
+ }
// lastSaved records what the server actually has (server-side defaults
// for legacy fields) so the debounced push re-uploads preserved local
// values.
@@ -360,6 +390,7 @@ export function usePersonalizationSync(enabled: boolean): void {
})();
return () => {
cancelled = true;
+ localeHydrationController.abort();
};
}, [enabled]);
diff --git a/studio/frontend/src/features/settings/components/language-select.tsx b/studio/frontend/src/features/settings/components/language-select.tsx
index 1f388d6f2c1..fbf892f793c 100644
--- a/studio/frontend/src/features/settings/components/language-select.tsx
+++ b/studio/frontend/src/features/settings/components/language-select.tsx
@@ -8,32 +8,56 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
+import { Spinner } from "@/components/ui/spinner";
import {
AUTO_LOCALE,
LOCALES,
isLocalePreference,
setLocale,
- useT,
+ useLocale,
+ useLocaleCatalogFailed,
useLocalePreference,
+ usePendingLocalePreference,
+ useT,
} from "@/i18n";
export function LanguageSelect() {
const t = useT();
+ const locale = useLocale();
const preference = useLocalePreference();
+ const pendingPreference = usePendingLocalePreference();
+ const catalogFailed = useLocaleCatalogFailed();
+ // Name no entry at all whenever the preference's own catalog failed and a
+ // fallback was adopted. A controlled Select never fires onValueChange for the
+ // value it already holds, so whichever entry it names is the one entry the
+ // user cannot pick, and after a failure both of them are needed: the failed
+ // preference is the retry, and the fallback in effect is how English becomes
+ // a real preference instead of something the app is doing temporarily. The
+ // empty string is Radix's "no selection", so every entry stays pickable and
+ // the trigger shows the language actually in effect as the placeholder.
+ // Whether the catalog failed has to come from the store rather than a
+ // `preference !== locale` comparison, because a failed `auto` still reads as
+ // `auto`, and its fallback locale is indistinguishable from a successful
+ // detection that landed on the same language.
+ const fallbackLabel = catalogFailed ? LOCALES[locale].nativeLabel : "";
return (
<Select
- value={preference}
+ value={pendingPreference ?? (catalogFailed ? "" : preference)}
onValueChange={(value) => {
if (isLocalePreference(value)) setLocale(value);
}}
>
<SelectTrigger
aria-label={t("settings.appearance.language.label")}
- className="w-40"
+ aria-busy={pendingPreference !== null}
+ // The placeholder is a real language here, not an empty menu, so it
+ // keeps the normal trigger colour rather than the muted one.
+ className="w-40 data-[placeholder]:text-foreground"
size="sm"
>
- <SelectValue />
+ <SelectValue placeholder={fallbackLabel} />
+ {pendingPreference !== null ? <Spinner className="size-3.5" /> : null}
</SelectTrigger>
<SelectContent
style={{
diff --git a/studio/frontend/src/i18n/index.ts b/studio/frontend/src/i18n/index.ts
index ee58314a163..ae79c39e263 100644
--- a/studio/frontend/src/i18n/index.ts
+++ b/studio/frontend/src/i18n/index.ts
@@ -4,24 +4,34 @@
import { useCallback } from "react";
import { useLocale } from "./locale-store";
import { translate } from "./messages";
-import type { InterpolationValues } from "./types";
import type { TranslationKey } from "./messages";
+import type { InterpolationValues } from "./types";
export {
AUTO_LOCALE,
DEFAULT_LOCALE,
DEFAULT_LOCALE_PREFERENCE,
LOCALE_STORAGE_KEY,
+ LOCALE_INITIALIZATION_TIMEOUT_MS,
+ LOCALE_SELECTION_TIMEOUT_MS,
getLocale,
+ getLocaleCatalogFailed,
getLocalePreference,
+ getPendingLocalePreference,
initializeLocale,
isLocalePreference,
setLocale,
subscribeLocale,
useLocale,
+ useLocaleCatalogFailed,
useLocalePreference,
+ usePendingLocalePreference,
+} from "./locale-store";
+export type {
+ LocaleChangeResult,
+ LocalePreference,
+ SetLocaleOptions,
} from "./locale-store";
-export type { LocalePreference } from "./locale-store";
export {
LOCALES,
isSupportedLocale,
diff --git a/studio/frontend/src/i18n/locale-store.ts b/studio/frontend/src/i18n/locale-store.ts
index 106ec49ec18..0609a797fa9 100644
--- a/studio/frontend/src/i18n/locale-store.ts
+++ b/studio/frontend/src/i18n/locale-store.ts
@@ -2,21 +2,88 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useSyncExternalStore } from "react";
-import { isSupportedLocale, LOCALES, type Locale } from "./messages";
+import {
+ LOCALES,
+ type Locale,
+ forgetLocaleLoad,
+ isSupportedLocale,
+ loadLocaleMessages,
+} from "./messages";
export const DEFAULT_LOCALE: Locale = "en";
export const AUTO_LOCALE = "auto";
export const LOCALE_STORAGE_KEY = "unsloth_locale";
+export const LOCALE_INITIALIZATION_TIMEOUT_MS = 2_000;
+/**
+ * The bound a locale change gets when its caller names none.
+ *
+ * Startup and hydration pass their own, but the language menu, a storage event
+ * and a `languagechange` refresh do not, and a request that is accepted and
+ * then never completes rejects nothing: the pending marker would stay set for
+ * the session, leaving the menu spinning on a language it will never reach and
+ * handing every later pick of it the same dead promise, with reloading the app
+ * the only way out. Longer than startup's, because this one is a deliberate
+ * download rather than a render everything else is waiting on, and a late
+ * catalog still commits over the fallback.
+ */
+export const LOCALE_SELECTION_TIMEOUT_MS = 10_000;
export type LocalePreference = Locale | typeof AUTO_LOCALE;
+export type LocaleChangeResult =
+ | "applied"
+ | "superseded"
+ | "failed"
+ | "cancelled";
+
+export type SetLocaleOptions = {
+ loadMessages?: (locale: Locale) => Promise<void> | undefined;
+ signal?: AbortSignal;
+ /**
+ * Adopt the preference even when its catalog never loads, rendering English.
+ *
+ * For a user picking a language this would be wrong: the choice failed, so it
+ * must not be persisted. Hydration is the opposite case. The preference it is
+ * applying is already the stored truth on the server, so refusing to adopt it
+ * leaves the local preference disagreeing with the server, and the next
+ * outbound save would push the stale local value back over it.
+ */
+ adoptOnFailure?: boolean;
+ /**
+ * Stop waiting on the catalog after this many ms and settle as a failure.
+ *
+ * A request that is accepted but never completes (a stalled CDN, proxy or
+ * service worker) rejects nothing, so without a bound the returned promise
+ * stays pending for the session and everything awaiting it waits with it.
+ * `initializeLocale` bounds startup for the same reason. A late arrival still
+ * commits, so a slow catalog is upgraded to rather than lost. Defaults to
+ * LOCALE_SELECTION_TIMEOUT_MS: every path here is bounded, including the
+ * language menu, which names none of its own.
+ */
+ timeoutMs?: number;
+};
+
export const DEFAULT_LOCALE_PREFERENCE: LocalePreference = AUTO_LOCALE;
const subscribers = new Set<() => void>();
let currentPreference: LocalePreference = DEFAULT_LOCALE_PREFERENCE;
let currentLocale: Locale = DEFAULT_LOCALE;
+let pendingPreference: LocalePreference | null = null;
+let pendingPreferenceShouldPersist = false;
let areListenersActive = false;
+/**
+ * The catalog the current preference resolves to failed, so currentLocale is a
+ * fallback rather than that preference's own language.
+ *
+ * Comparing the preference to the locale cannot stand in for this: `auto`
+ * resolves through the browser, so a failed auto reads as `auto` with English
+ * in effect, which is also what a successful auto looks like to an English
+ * browser. The UI needs the difference, because a controlled Select never fires
+ * onValueChange for the value it already shows: naming a preference whose
+ * catalog failed is what makes it the one preference the user cannot re-pick.
+ */
+let currentCatalogFailed = false;
export function isLocalePreference(value: unknown): value is LocalePreference {
return value === AUTO_LOCALE || isSupportedLocale(value);
@@ -71,7 +138,9 @@ function normalizePreference(value: unknown): LocalePreference {
// Return a value re-derived from our own locale table rather than the raw
// input, so only known language codes are ever persisted.
const locales = Object.keys(LOCALES) as Locale[];
- return locales.find((locale) => locale === value) ?? DEFAULT_LOCALE_PREFERENCE;
+ return (
+ locales.find((locale) => locale === value) ?? DEFAULT_LOCALE_PREFERENCE
+ );
}
function resolvePreference(preference: LocalePreference): Locale {
@@ -105,13 +174,166 @@ function notifySubscribers(): void {
for (const subscriber of subscribers) subscriber();
}
-function applyPreference(preference: LocalePreference): void {
- const locale = resolvePreference(preference);
- if (preference === currentPreference && locale === currentLocale) return;
+let preferenceRevision = 0;
+
+function commitPreference(
+ preference: LocalePreference,
+ locale: Locale,
+ revision: number,
+ persist: boolean,
+): LocaleChangeResult {
+ if (revision !== preferenceRevision) return "superseded";
+ if (persist) writeStoredPreference(preference);
+ const didChange =
+ preference !== currentPreference ||
+ locale !== currentLocale ||
+ pendingPreference !== null ||
+ currentCatalogFailed;
currentPreference = preference;
currentLocale = locale;
+ pendingPreference = null;
+ pendingPreferenceShouldPersist = false;
+ // This preference's catalog is loaded, so a retry has nothing left to fix.
+ currentCatalogFailed = false;
syncDocumentLang(locale);
+ if (didChange) notifySubscribers();
+ return "applied";
+}
+
+function commitFallbackLocale(
+ preference: LocalePreference,
+ revision: number,
+): void {
+ if (revision !== preferenceRevision) return;
+ const didChange =
+ preference !== currentPreference ||
+ currentLocale !== DEFAULT_LOCALE ||
+ pendingPreference !== null ||
+ !currentCatalogFailed;
+ currentPreference = preference;
+ currentLocale = DEFAULT_LOCALE;
+ pendingPreference = null;
+ pendingPreferenceShouldPersist = false;
+ // Adopted, but on the fallback catalog rather than this preference's own.
+ currentCatalogFailed = true;
+ syncDocumentLang(currentLocale);
+ if (didChange) notifySubscribers();
+}
+
+type LocaleCatalogLoader = (locale: Locale) => Promise<void> | undefined;
+
+function failPreference(
+ revision: number,
+ preference: LocalePreference,
+ locale: Locale,
+): void {
+ if (revision !== preferenceRevision || pendingPreference === null) return;
+ pendingPreference = null;
+ pendingPreferenceShouldPersist = false;
+ // A rejected pick leaves the standing preference untouched, so it is still
+ // serving its own catalog and stays re-pickable; the flag must not move.
+ // A refresh of the preference already in effect is the other case: a
+ // `languagechange` re-resolving `auto` onto a language whose catalog fails
+ // leaves that preference pointing at a locale the app is not showing, which
+ // is exactly the state the retry path needs to see.
+ if (preference === currentPreference && locale !== currentLocale) {
+ currentCatalogFailed = true;
+ }
+ notifySubscribers();
+}
+
+function cancelPreference(revision: number): void {
+ if (revision !== preferenceRevision) return;
+ preferenceRevision += 1;
+ if (pendingPreference === null) return;
+ pendingPreference = null;
+ pendingPreferenceShouldPersist = false;
+ notifySubscribers();
+}
+
+function applyPreference(
+ preference: LocalePreference,
+ persist = false,
+ loadMessages: LocaleCatalogLoader = loadLocaleMessages,
+ signal?: AbortSignal,
+ adoptOnFailure = false,
+ timeoutMs: number = LOCALE_SELECTION_TIMEOUT_MS,
+): LocaleChangeResult | Promise<LocaleChangeResult> {
+ if (signal?.aborted) return "cancelled";
+ const previousPending = pendingPreference;
+ const previousPendingPersist = pendingPreferenceShouldPersist;
+ const revision = ++preferenceRevision;
+ const locale = resolvePreference(preference);
+ let pending: Promise<void> | undefined;
+ try {
+ pending = loadMessages(locale);
+ } catch {
+ if (adoptOnFailure) {
+ commitFallbackLocale(preference, revision);
+ return "failed";
+ }
+ // This request never became the pending one, so failing it must not clear
+ // the marker an earlier request that is still in flight is relying on.
+ pendingPreference = previousPending;
+ pendingPreferenceShouldPersist = previousPendingPersist;
+ return "failed";
+ }
+ if (!pending) {
+ return commitPreference(preference, locale, revision, persist);
+ }
+ pendingPreference = preference;
+ pendingPreferenceShouldPersist = persist;
notifySubscribers();
+ const cancel = () => cancelPreference(revision);
+ signal?.addEventListener("abort", cancel, { once: true });
+ if (signal?.aborted) cancel();
+ const settled = pending.then<LocaleChangeResult, LocaleChangeResult>(
+ () => {
+ if (signal?.aborted) return "cancelled";
+ return commitPreference(preference, locale, revision, persist);
+ },
+ () => {
+ if (signal?.aborted) return "cancelled";
+ if (revision !== preferenceRevision) return "superseded";
+ if (adoptOnFailure) {
+ commitFallbackLocale(preference, revision);
+ } else {
+ failPreference(revision, preference, locale);
+ }
+ return "failed";
+ },
+ );
+ const bounded = new Promise<LocaleChangeResult>((resolve) => {
+ const timeout = globalThis.setTimeout(
+ () => {
+ // Settle the way a rejection would. The load itself is left alone,
+ // so if it does arrive it still commits over this. Its place in the
+ // in-flight map is not: a load that never settles never clears its own
+ // entry, so leaving it there would hand every later pick of this
+ // language the same dead promise and time out again without ever
+ // asking for the catalog a second time.
+ forgetLocaleLoad(locale, pending);
+ if (signal?.aborted) {
+ resolve("cancelled");
+ } else if (revision !== preferenceRevision) {
+ resolve("superseded");
+ } else {
+ if (adoptOnFailure) {
+ commitFallbackLocale(preference, revision);
+ } else {
+ failPreference(revision, preference, locale);
+ }
+ resolve("failed");
+ }
+ },
+ Math.max(0, timeoutMs),
+ );
+ void settled.then((outcome) => {
+ globalThis.clearTimeout(timeout);
+ resolve(outcome);
+ });
+ });
+ return bounded.finally(() => signal?.removeEventListener("abort", cancel));
}
function isLocaleStorageEvent(event: StorageEvent): boolean {
@@ -133,17 +355,28 @@ function handleStorageEvent(event: StorageEvent): void {
event.key === null
? DEFAULT_LOCALE_PREFERENCE
: normalizePreference(event.newValue);
- applyPreference(nextPreference);
+ // Adopted on failure, like hydration and for the same reason: this value is
+ // already the stored truth, written by the tab that made the choice, so a
+ // catalog that will not load here must not leave this tab holding the
+ // preference the user replaced. It would disagree with storage until the next
+ // reload, and the next personalization save would push that stale language
+ // back over the choice. Nothing is written back: storage is where this came
+ // from, and a catalog that failed is not recorded as a choice that worked.
+ void applyPreference(
+ nextPreference,
+ false,
+ loadLocaleMessages,
+ undefined,
+ true,
+ );
}
function handleLanguageChange(): void {
- // Only auto mode tracks the browser language.
- if (currentPreference !== AUTO_LOCALE) return;
- const locale = detectLocale();
- if (locale === currentLocale) return;
- currentLocale = locale;
- syncDocumentLang(locale);
- notifySubscribers();
+ // A pending choice is the effective preference. Browser changes may refresh
+ // a pending auto request, but must not supersede an explicit user choice.
+ const effectivePreference = pendingPreference ?? currentPreference;
+ if (effectivePreference !== AUTO_LOCALE) return;
+ void applyPreference(effectivePreference, pendingPreferenceShouldPersist);
}
function startListeners(): void {
@@ -176,6 +409,22 @@ function getServerPreferenceSnapshot(): LocalePreference {
return DEFAULT_LOCALE_PREFERENCE;
}
+function getPendingPreferenceSnapshot(): LocalePreference | null {
+ return pendingPreference;
+}
+
+function getServerPendingPreferenceSnapshot(): null {
+ return null;
+}
+
+function getCatalogFailedSnapshot(): boolean {
+ return currentCatalogFailed;
+}
+
+function getServerCatalogFailedSnapshot(): false {
+ return false;
+}
+
export function subscribeLocale(listener: () => void): () => void {
const shouldStartListeners = subscribers.size === 0;
subscribers.add(listener);
@@ -187,13 +436,68 @@ export function subscribeLocale(listener: () => void): () => void {
};
}
-export function initializeLocale(): Locale {
+export function initializeLocale({
+ loadMessages = loadLocaleMessages,
+ timeoutMs = LOCALE_INITIALIZATION_TIMEOUT_MS,
+}: {
+ loadMessages?: LocaleCatalogLoader;
+ timeoutMs?: number;
+} = {}): Locale | Promise<Locale> {
const preference = readStoredPreference();
- currentPreference = preference;
- currentLocale = resolvePreference(preference);
- syncDocumentLang(currentLocale);
+ const locale = resolvePreference(preference);
+ const revision = ++preferenceRevision;
+ let pending: Promise<void> | undefined;
+ try {
+ pending = loadMessages(locale);
+ } catch {
+ commitFallbackLocale(preference, revision);
+ return currentLocale;
+ }
+ if (!pending) {
+ commitPreference(preference, locale, revision, false);
+ return currentLocale;
+ }
+
+ pendingPreference = preference;
+ pendingPreferenceShouldPersist = false;
notifySubscribers();
- return currentLocale;
+
+ return new Promise((resolve) => {
+ let didResolve = false;
+ const finish = () => {
+ if (didResolve) return;
+ didResolve = true;
+ resolve(currentLocale);
+ };
+ const timeout = globalThis.setTimeout(
+ () => {
+ // Same as the selection path: the load itself is left running, so a
+ // late catalog still commits over the fallback, but its place in the
+ // in-flight map goes. A load that never settles never clears its own
+ // entry, and the saved language is exactly the one the user reaches for
+ // next once English appears, so keeping it would hand that pick this
+ // same dead promise and spend the whole selection bound on it without
+ // ever asking for the catalog again.
+ forgetLocaleLoad(locale, pending);
+ commitFallbackLocale(preference, revision);
+ finish();
+ },
+ Math.max(0, timeoutMs),
+ );
+
+ pending.then(
+ () => {
+ globalThis.clearTimeout(timeout);
+ commitPreference(preference, locale, revision, false);
+ finish();
+ },
+ () => {
+ globalThis.clearTimeout(timeout);
+ commitFallbackLocale(preference, revision);
+ finish();
+ },
+ );
+ });
}
export function getLocale(): Locale {
@@ -204,14 +508,36 @@ export function getLocalePreference(): LocalePreference {
return currentPreference;
}
-export function setLocale(preference: LocalePreference): void {
- const requestedPreference = normalizePreference(preference);
- writeStoredPreference(requestedPreference);
+export function getPendingLocalePreference(): LocalePreference | null {
+ return pendingPreference;
+}
- currentPreference = requestedPreference;
- currentLocale = resolvePreference(requestedPreference);
- syncDocumentLang(currentLocale);
- notifySubscribers();
+export function getLocaleCatalogFailed(): boolean {
+ return currentCatalogFailed;
+}
+
+export function setLocale(
+ preference: LocalePreference,
+ {
+ loadMessages = loadLocaleMessages,
+ signal,
+ adoptOnFailure = false,
+ timeoutMs,
+ }: SetLocaleOptions = {},
+): LocaleChangeResult | Promise<LocaleChangeResult> {
+ const requestedPreference = normalizePreference(preference);
+ // persist stays true on both paths: a successful change is still written, and
+ // the adopt-on-failure path routes through commitFallbackLocale, which never
+ // writes storage, so a preference whose catalog failed is adopted for this
+ // session without being recorded as a choice that worked.
+ return applyPreference(
+ requestedPreference,
+ true,
+ loadMessages,
+ signal,
+ adoptOnFailure,
+ timeoutMs,
+ );
}
export function useLocale(): Locale {
@@ -229,3 +555,19 @@ export function useLocalePreference(): LocalePreference {
getServerPreferenceSnapshot,
);
}
+
+export function usePendingLocalePreference(): LocalePreference | null {
+ return useSyncExternalStore(
+ subscribeLocale,
+ getPendingPreferenceSnapshot,
+ getServerPendingPreferenceSnapshot,
+ );
+}
+
+export function useLocaleCatalogFailed(): boolean {
+ return useSyncExternalStore(
+ subscribeLocale,
+ getCatalogFailedSnapshot,
+ getServerCatalogFailedSnapshot,
+ );
+}
diff --git a/studio/frontend/src/i18n/messages.ts b/studio/frontend/src/i18n/messages.ts
index f33cdf418de..4bb2aa85727 100644
--- a/studio/frontend/src/i18n/messages.ts
+++ b/studio/frontend/src/i18n/messages.ts
@@ -3,18 +3,7 @@
import { getLocale } from "./locale-store";
import { en } from "./locales/en";
-import { zhCN } from "./locales/zh-CN";
-import { ptBR } from "./locales/pt-br";
-import { ja } from "./locales/ja";
-import { es } from "./locales/es";
-import { hi } from "./locales/hi";
-import { ar } from "./locales/ar";
-import { fr } from "./locales/fr";
-import { ru } from "./locales/ru";
-import { de } from "./locales/de";
-import { ko } from "./locales/ko";
-import { it } from "./locales/it";
-import type { InterpolationValues, MessageKey } from "./types";
+import type { InterpolationValues, MessageKey, MessageTree } from "./types";
export const LOCALES = {
en: { label: "English", nativeLabel: "English" },
@@ -34,20 +23,145 @@ export const LOCALES = {
export type Locale = keyof typeof LOCALES;
export type TranslationKey = MessageKey<typeof en>;
-export const messages = {
+const loadedMessages: Partial<Record<Locale, MessageTree>> = {
en,
- "zh-CN": zhCN,
- ja,
- ko,
- es,
- "pt-BR": ptBR,
- fr,
- de,
- it,
- ru,
- hi,
- ar,
-} as const;
+};
+export const messages = loadedMessages as typeof loadedMessages & {
+ en: typeof en;
+};
+
+type LazyLocale = Exclude<Locale, "en">;
+
+const localeLoaders: Record<LazyLocale, () => Promise<unknown>> = {
+ "zh-CN": () => import("./locales/zh-CN"),
+ ja: () => import("./locales/ja"),
+ ko: () => import("./locales/ko"),
+ es: () => import("./locales/es"),
+ "pt-BR": () => import("./locales/pt-br"),
+ fr: () => import("./locales/fr"),
+ de: () => import("./locales/de"),
+ it: () => import("./locales/it"),
+ ru: () => import("./locales/ru"),
+ hi: () => import("./locales/hi"),
+ ar: () => import("./locales/ar"),
+};
+
+/** A catalog exports its own tag with the separator dropped: zh-CN -> zhCN. */
+function readCatalog(module: unknown, locale: LazyLocale): MessageTree {
+ const name = locale.replace("-", "");
+ const catalog = (module as Record<string, unknown> | null)?.[name];
+ if (catalog === undefined) {
+ throw new Error(`Locale catalog "${locale}" has no "${name}" export.`);
+ }
+ return catalog as MessageTree;
+}
+
+export const CATALOG_RETRY_PARAM = "catalogRetry";
+
+const CHUNK_URL_PATTERN = /\bhttps?:\/\/[^\s"'`)]+/;
+
+let catalogRetryCount = 0;
+
+/**
+ * The URL to re-request a failed catalog from, or null when none can be read.
+ *
+ * Chrome, Edge and Firefox before 155 keep a failed module in the module map
+ * keyed by URL, so re-running the same import resolves to the stored failure
+ * without touching the network: dropping our own promise is not enough to make
+ * a retry a retry. A one-off query gives the request its own module map key and
+ * its own HTTP cache key, while the hashed filename it is appended to is
+ * unchanged, so the first load of every catalog keeps its normal long-lived
+ * caching and nothing about it moves until something has actually failed.
+ *
+ * The URL comes out of the browser's own message ("Failed to fetch dynamically
+ * imported module: <url>"), which is the only place the built chunk's URL is
+ * exposed to us; Safari reports no URL there, and it is also the one engine
+ * that already re-requests on its own.
+ */
+export function catalogRetryUrl(
+ error: unknown,
+ previousUrl: string | null = null,
+): string | null {
+ const message = error instanceof Error ? error.message : String(error ?? "");
+ const found = message.match(CHUNK_URL_PATTERN)?.[0] ?? previousUrl;
+ if (found === null) return null;
+ let url: URL;
+ try {
+ url = new URL(found);
+ } catch {
+ return null;
+ }
+ // A preload failure names the stylesheet, not the module that wanted it.
+ if (url.pathname.endsWith(".css")) return null;
+ catalogRetryCount += 1;
+ url.searchParams.set(CATALOG_RETRY_PARAM, String(catalogRetryCount));
+ return url.href;
+}
+
+export type CatalogImporter = (
+ locale: LazyLocale,
+ retryUrl: string | null,
+) => Promise<unknown>;
+
+function importCatalog(
+ locale: LazyLocale,
+ retryUrl: string | null,
+): Promise<unknown> {
+ if (retryUrl === null) return localeLoaders[locale]();
+ return import(/* @vite-ignore */ retryUrl);
+}
+
+const localeLoads = new Map<Locale, Promise<void>>();
+const catalogRetryUrls = new Map<Locale, string>();
+
+export function loadLocaleMessages(
+ locale: Locale,
+ importer: CatalogImporter = importCatalog,
+): Promise<void> | undefined {
+ if (loadedMessages[locale] !== undefined) return undefined;
+ const pending = localeLoads.get(locale);
+ if (pending) return pending;
+
+ if (locale === "en") return undefined;
+ const retryUrl = catalogRetryUrls.get(locale) ?? null;
+ const load = importer(locale, retryUrl)
+ .then(
+ (module) => {
+ loadedMessages[locale] = readCatalog(module, locale);
+ catalogRetryUrls.delete(locale);
+ },
+ (error: unknown) => {
+ const nextUrl = catalogRetryUrl(error, retryUrl);
+ if (nextUrl === null) catalogRetryUrls.delete(locale);
+ else catalogRetryUrls.set(locale, nextUrl);
+ throw error;
+ },
+ )
+ .finally(() => {
+ // Only if it is still ours: a load evicted by its caller's timeout may
+ // already have been replaced by the retry it made room for.
+ if (localeLoads.get(locale) === load) localeLoads.delete(locale);
+ });
+ localeLoads.set(locale, load);
+ return load;
+}
+
+/**
+ * Stop deduplicating onto a catalog load, so the next request starts its own.
+ *
+ * A load that never settles never reaches the `.finally()` above, so its entry
+ * would hand every later pick of that language the same permanently pending
+ * promise and the choice could not be retried without reloading the app.
+ * Whoever bounded the wait evicts the load it gave up on; the promise itself is
+ * left running, so a late arrival still populates the catalog.
+ *
+ * `load` identifies the attempt being forgotten, so a newer one for the same
+ * locale is never evicted by an older caller's timeout.
+ */
+export function forgetLocaleLoad(locale: Locale, load?: Promise<void>): void {
+ if (load !== undefined && localeLoads.get(locale) !== load) return;
+ localeLoads.delete(locale);
+}
const PLACEHOLDER_PATTERN = /\{([a-zA-Z0-9_]+)\}/g;
diff --git a/studio/frontend/src/main.tsx b/studio/frontend/src/main.tsx
index e5f494464cd..359212c2aee 100644
--- a/studio/frontend/src/main.tsx
+++ b/studio/frontend/src/main.tsx
@@ -35,8 +35,7 @@ const rootElement = document.getElementById("root");
if (!rootElement) {
throw new Error("Root element not found");
}
-
-initializeLocale();
+const root = createRoot(rootElement);
if (isTauri) {
document.documentElement.classList.add("tauri");
@@ -52,10 +51,19 @@ if (uaLower.includes("linux") && !uaLower.includes("android")) {
// Keep right-edge controls clear of overlay scrollbars.
watchOverlayScrollbarGutter(window);
-createRoot(rootElement).render(
- <StrictMode>
- <App />
- </StrictMode>,
-);
+function renderApp(): void {
+ root.render(
+ <StrictMode>
+ <App />
+ </StrictMode>,
+ );
+}
+
+const localeInitialization = initializeLocale();
+if (typeof localeInitialization !== "string") {
+ localeInitialization.then(renderApp);
+} else {
+ renderApp();
+}
fetchDeviceType().catch(() => undefined);
diff --git a/studio/frontend/tests/helpers/module-stubs.ts b/studio/frontend/tests/helpers/module-stubs.ts
new file mode 100644
index 00000000000..a09dee7ebce
--- /dev/null
+++ b/studio/frontend/tests/helpers/module-stubs.ts
@@ -0,0 +1,56 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Kept out of kit.ts on purpose, like tsx-ast.ts: only the few tests that drive a
+// component or a hook directly should pay for loading the TypeScript compiler.
+
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+
+import ts from "typescript";
+
+/** A JSX element as the stub runtime below records it. */
+export type StubElement = {
+ type: unknown;
+ props: Record<string, unknown>;
+};
+
+/**
+ * Runs one shipped src module with every import replaced by a stub, so a test can
+ * call the real source with dependencies it controls. Bare node cannot import a
+ * .tsx file at all, and a hook needs a React whose renders the test drives.
+ */
+export function loadWithStubs<T>(
+ moduleUrl: URL,
+ stubs: Record<string, unknown>,
+): T {
+ const path = fileURLToPath(moduleUrl);
+ const { outputText } = ts.transpileModule(readFileSync(path, "utf8"), {
+ fileName: path,
+ compilerOptions: {
+ target: ts.ScriptTarget.ES2022,
+ module: ts.ModuleKind.CommonJS,
+ jsx: ts.JsxEmit.ReactJSX,
+ },
+ });
+ const loaded = { exports: {} as T };
+ const requireStub = (specifier: string): unknown => {
+ if (specifier in stubs) return stubs[specifier];
+ throw new Error(`no stub for import "${specifier}" in ${path}`);
+ };
+ new Function("require", "module", "exports", outputText)(
+ requireStub,
+ loaded,
+ loaded.exports,
+ );
+ return loaded.exports;
+}
+
+/** A react/jsx-runtime that builds plain records instead of React elements. */
+export function stubJsxRuntime(): Record<string, unknown> {
+ const jsx = (type: unknown, props: Record<string, unknown>): StubElement => ({
+ type,
+ props,
+ });
+ return { jsx, jsxs: jsx, Fragment: Symbol.for("Fragment") };
+}
diff --git a/studio/frontend/tests/lazy-locale-loading.test.ts b/studio/frontend/tests/lazy-locale-loading.test.ts
new file mode 100644
index 00000000000..1a304e009b6
--- /dev/null
+++ b/studio/frontend/tests/lazy-locale-loading.test.ts
@@ -0,0 +1,834 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+import assert from "node:assert/strict";
+import test, { mock } from "node:test";
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+import {
+ type StubElement,
+ loadWithStubs,
+ stubJsxRuntime,
+} from "./helpers/module-stubs.ts";
+
+registerBundlerResolver();
+const { store } = installLocalStorageFake();
+const windowListeners = new Map<string, Set<EventListener>>();
+Object.assign(globalThis.window, {
+ addEventListener(type: string, listener: EventListener) {
+ const listeners = windowListeners.get(type) ?? new Set<EventListener>();
+ listeners.add(listener);
+ windowListeners.set(type, listeners);
+ },
+ removeEventListener(type: string, listener: EventListener) {
+ windowListeners.get(type)?.delete(listener);
+ },
+});
+
+function fireWindowEvent(type: string): void {
+ for (const listener of windowListeners.get(type) ?? []) {
+ listener(new Event(type));
+ }
+}
+
+/** What another tab writing the shared preference delivers to this one. */
+function fireStorageEvent(key: string | null, newValue: string | null): void {
+ for (const listener of windowListeners.get("storage") ?? []) {
+ listener({ key, newValue, storageArea: null } as unknown as Event);
+ }
+}
+
+let documentLanguage = "";
+Object.assign(globalThis, {
+ document: {
+ documentElement: {
+ get lang() {
+ return documentLanguage;
+ },
+ set lang(value: string) {
+ documentLanguage = value;
+ },
+ },
+ },
+});
+const navigatorState = { language: "en-US", languages: ["en-US"] };
+Object.defineProperty(globalThis, "navigator", {
+ configurable: true,
+ value: navigatorState,
+});
+
+const messagesModule = await import("../src/i18n/messages.ts");
+const localeStore = await import("../src/i18n/locale-store.ts");
+
+test("only English is present before a non-English locale is requested", () => {
+ assert.deepEqual(Object.keys(messagesModule.messages), ["en"]);
+ assert.equal(messagesModule.translate("common.cancel"), "Cancel");
+});
+
+test("initialization waits for the saved locale catalog before committing it", async () => {
+ store.set(localeStore.LOCALE_STORAGE_KEY, "de");
+
+ const initialized = localeStore.initializeLocale();
+ assert.notEqual(typeof initialized, "string");
+ assert.equal(localeStore.getLocale(), "en");
+
+ assert.equal(await initialized, "de");
+ assert.equal(localeStore.getLocale(), "de");
+ assert.equal(localeStore.getLocalePreference(), "de");
+ assert.equal(documentLanguage, "de");
+ assert.equal(messagesModule.translate("common.cancel"), "Abbrechen");
+});
+
+test("concurrent requests share one catalog load", async () => {
+ const first = messagesModule.loadLocaleMessages("ko");
+ const second = messagesModule.loadLocaleMessages("ko");
+
+ assert.ok(first);
+ assert.equal(second, first);
+ await first;
+ assert.equal(messagesModule.loadLocaleMessages("ko"), undefined);
+});
+
+test("concurrent language loads keep the latest selection", async () => {
+ const first = localeStore.setLocale("fr");
+ const second = localeStore.setLocale("it");
+ await Promise.all([
+ messagesModule.loadLocaleMessages("fr"),
+ messagesModule.loadLocaleMessages("it"),
+ ]);
+
+ assert.equal(await first, "superseded");
+ assert.equal(await second, "applied");
+
+ assert.equal(localeStore.getLocale(), "it");
+ assert.equal(localeStore.getLocalePreference(), "it");
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "it");
+ assert.equal(messagesModule.translate("common.cancel"), "Annulla");
+});
+
+test("a selection is shown as pending and persisted only after loading", async () => {
+ let finishLoading!: () => void;
+ const loading = new Promise<void>((resolve) => {
+ finishLoading = resolve;
+ });
+
+ const selected = localeStore.setLocale("ja", {
+ loadMessages: () => loading,
+ });
+
+ assert.equal(localeStore.getPendingLocalePreference(), "ja");
+ assert.equal(localeStore.getLocale(), "it");
+ assert.equal(localeStore.getLocalePreference(), "it");
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "it");
+
+ finishLoading();
+ assert.equal(await selected, "applied");
+
+ assert.equal(localeStore.getPendingLocalePreference(), null);
+ assert.equal(localeStore.getLocale(), "ja");
+ assert.equal(localeStore.getLocalePreference(), "ja");
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "ja");
+});
+
+test("a failed selection keeps the active and persisted language", async () => {
+ const selected = localeStore.setLocale("ko", {
+ loadMessages: () => Promise.reject(new Error("catalog unavailable")),
+ });
+
+ assert.equal(localeStore.getPendingLocalePreference(), "ko");
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "ja");
+
+ assert.equal(await selected, "failed");
+
+ assert.equal(localeStore.getPendingLocalePreference(), null);
+ assert.equal(localeStore.getLocale(), "ja");
+ assert.equal(localeStore.getLocalePreference(), "ja");
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "ja");
+});
+
+test("cancelling a pending selection prevents a late commit", async () => {
+ const controller = new AbortController();
+ let finishLoading!: () => void;
+ const loading = new Promise<void>((resolve) => {
+ finishLoading = resolve;
+ });
+
+ const selected = localeStore.setLocale("de", {
+ loadMessages: () => loading,
+ signal: controller.signal,
+ });
+ assert.equal(localeStore.getPendingLocalePreference(), "de");
+
+ controller.abort();
+ assert.equal(localeStore.getPendingLocalePreference(), null);
+ assert.equal(localeStore.getLocale(), "ja");
+ assert.equal(localeStore.getLocalePreference(), "ja");
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "ja");
+
+ finishLoading();
+ assert.equal(await selected, "cancelled");
+ assert.equal(localeStore.getLocale(), "ja");
+ assert.equal(localeStore.getLocalePreference(), "ja");
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "ja");
+});
+
+test("a browser language change cannot supersede a pending explicit choice", async () => {
+ assert.equal(
+ localeStore.setLocale("auto", { loadMessages: () => undefined }),
+ "applied",
+ );
+ const unsubscribe = localeStore.subscribeLocale(() => undefined);
+ let finishLoading!: () => void;
+ const loading = new Promise<void>((resolve) => {
+ finishLoading = resolve;
+ });
+
+ const selected = localeStore.setLocale("de", {
+ loadMessages: () => loading,
+ });
+ navigatorState.language = "fr-FR";
+ navigatorState.languages = ["fr-FR"];
+ fireWindowEvent("languagechange");
+
+ assert.equal(localeStore.getPendingLocalePreference(), "de");
+ finishLoading();
+ assert.equal(await selected, "applied");
+ unsubscribe();
+
+ assert.equal(localeStore.getLocale(), "de");
+ assert.equal(localeStore.getLocalePreference(), "de");
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "de");
+});
+
+test("a browser language change refreshes a pending auto choice", async () => {
+ assert.equal(
+ localeStore.setLocale("it", { loadMessages: () => undefined }),
+ "applied",
+ );
+ navigatorState.language = "de-DE";
+ navigatorState.languages = ["de-DE"];
+ const unsubscribe = localeStore.subscribeLocale(() => undefined);
+ let finishLoading!: () => void;
+ const loading = new Promise<void>((resolve) => {
+ finishLoading = resolve;
+ });
+
+ const selected = localeStore.setLocale("auto", {
+ loadMessages: () => loading,
+ });
+ navigatorState.language = "en-US";
+ navigatorState.languages = ["en-US"];
+ fireWindowEvent("languagechange");
+
+ assert.equal(localeStore.getPendingLocalePreference(), null);
+ assert.equal(localeStore.getLocale(), "en");
+ assert.equal(localeStore.getLocalePreference(), "auto");
+ finishLoading();
+ assert.equal(await selected, "superseded");
+ unsubscribe();
+
+ assert.equal(localeStore.getLocale(), "en");
+ assert.equal(localeStore.getLocalePreference(), "auto");
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "auto");
+});
+
+test("a catalog timeout preserves the preference and finishes later", async () => {
+ store.set(localeStore.LOCALE_STORAGE_KEY, "de");
+ let finishLoading!: () => void;
+ const loading = new Promise<void>((resolve) => {
+ finishLoading = resolve;
+ });
+
+ const initialized = localeStore.initializeLocale({
+ loadMessages: () => loading,
+ timeoutMs: 0,
+ });
+ assert.notEqual(typeof initialized, "string");
+
+ assert.equal(await initialized, "en");
+ assert.equal(localeStore.getLocale(), "en");
+ // Personalization sync reads this preference. The temporary English render
+ // must not turn into a server-side language change.
+ assert.equal(localeStore.getLocalePreference(), "de");
+ assert.equal(localeStore.getPendingLocalePreference(), null);
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "de");
+
+ finishLoading();
+ await loading;
+ await Promise.resolve();
+
+ assert.equal(localeStore.getLocale(), "de");
+ assert.equal(localeStore.getLocalePreference(), "de");
+ assert.equal(localeStore.getPendingLocalePreference(), null);
+});
+
+test("a late initial catalog cannot replace a newer language selection", async () => {
+ store.set(localeStore.LOCALE_STORAGE_KEY, "de");
+ let finishLoading!: () => void;
+ const loading = new Promise<void>((resolve) => {
+ finishLoading = resolve;
+ });
+
+ const initialized = localeStore.initializeLocale({
+ loadMessages: () => loading,
+ timeoutMs: 0,
+ });
+ assert.notEqual(typeof initialized, "string");
+ await initialized;
+
+ await localeStore.setLocale("it", { loadMessages: () => undefined });
+ finishLoading();
+ await loading;
+ await Promise.resolve();
+
+ assert.equal(localeStore.getLocale(), "it");
+ assert.equal(localeStore.getLocalePreference(), "it");
+ assert.equal(localeStore.getPendingLocalePreference(), null);
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "it");
+});
+
+test("a failed initial catalog falls back to English", async () => {
+ store.set(localeStore.LOCALE_STORAGE_KEY, "fr");
+
+ const initialized = localeStore.initializeLocale({
+ loadMessages: () => Promise.reject(new Error("catalog unavailable")),
+ });
+ assert.notEqual(typeof initialized, "string");
+
+ assert.equal(await initialized, "en");
+ assert.equal(localeStore.getLocale(), "en");
+ assert.equal(localeStore.getLocalePreference(), "fr");
+ assert.equal(localeStore.getPendingLocalePreference(), null);
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "fr");
+});
+
+test("a synchronous initial catalog failure preserves the preference", () => {
+ store.set(localeStore.LOCALE_STORAGE_KEY, "ko");
+
+ const initialized = localeStore.initializeLocale({
+ loadMessages: () => {
+ throw new Error("catalog unavailable");
+ },
+ });
+
+ assert.equal(initialized, "en");
+ assert.equal(localeStore.getLocale(), "en");
+ assert.equal(localeStore.getLocalePreference(), "ko");
+ assert.equal(localeStore.getPendingLocalePreference(), null);
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "ko");
+});
+
+test("hydration adopts a preference whose catalog failed, rendering English", async () => {
+ await localeStore.setLocale("en");
+ store.delete(localeStore.LOCALE_STORAGE_KEY);
+
+ const result = await localeStore.setLocale("de", {
+ loadMessages: () => Promise.reject(new Error("chunk 404")),
+ adoptOnFailure: true,
+ });
+
+ // The preference hydration applies is already the server's stored truth, so
+ // refusing to adopt it would leave the local preference disagreeing with the
+ // server and the next outbound save would push the stale value back over it.
+ assert.equal(result, "failed");
+ assert.equal(localeStore.getLocalePreference(), "de");
+ assert.equal(localeStore.getLocale(), "en");
+ assert.equal(localeStore.getPendingLocalePreference(), null);
+ // Not persisted: storage records choices that worked, and writing this one
+ // would reproduce the failure on every later load with nothing to tell it
+ // apart from a deliberate pick.
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), undefined);
+});
+
+test("a user-initiated failure is not adopted", async () => {
+ await localeStore.setLocale("en");
+
+ const result = await localeStore.setLocale("ru", {
+ loadMessages: () => Promise.reject(new Error("chunk 404")),
+ });
+
+ assert.equal(result, "failed");
+ assert.notEqual(localeStore.getLocalePreference(), "ru");
+ assert.equal(localeStore.getLocale(), "en");
+});
+
+test("adopt-on-failure still persists a change that succeeded", async () => {
+ await localeStore.setLocale("en");
+
+ const result = await localeStore.setLocale("es", {
+ loadMessages: () => Promise.resolve(),
+ adoptOnFailure: true,
+ });
+
+ assert.equal(result, "applied");
+ assert.equal(localeStore.getLocalePreference(), "es");
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "es");
+});
+
+test("a synchronous loader throw leaves an in-flight request pending", async () => {
+ await localeStore.setLocale("en");
+ let finishLoading!: () => void;
+ const loading = new Promise<void>((resolve) => {
+ finishLoading = resolve;
+ });
+
+ const slow = localeStore.setLocale("fr", { loadMessages: () => loading });
+ assert.equal(localeStore.getPendingLocalePreference(), "fr");
+
+ // This request never becomes the pending one, so clearing the marker on its
+ // way out would blank the spinner the slow request is still relying on.
+ const thrown = await localeStore.setLocale("hi", {
+ loadMessages: () => {
+ throw new Error("sync boom");
+ },
+ });
+
+ assert.equal(thrown, "failed");
+ assert.equal(localeStore.getPendingLocalePreference(), "fr");
+
+ finishLoading();
+ await slow;
+});
+
+test("a cross-tab language change is adopted even when its catalog fails", async () => {
+ await localeStore.setLocale("en", { loadMessages: () => undefined });
+ const unsubscribe = localeStore.subscribeLocale(() => undefined);
+ let failLoad!: (error: Error) => void;
+ // The real in-flight map, so the store's own listener deduplicates onto this
+ // load rather than reaching the network: the handler takes no loader.
+ const load = messagesModule.loadLocaleMessages(
+ "ru",
+ () =>
+ new Promise((_, reject) => {
+ failLoad = reject;
+ }),
+ );
+ load?.catch(() => undefined);
+
+ try {
+ // The other tab picked Russian: it wrote the shared value first, and this
+ // event is only the notification that it did.
+ store.set(localeStore.LOCALE_STORAGE_KEY, "ru");
+ fireStorageEvent(localeStore.LOCALE_STORAGE_KEY, "ru");
+ failLoad(new Error("chunk 404"));
+ await load?.catch(() => undefined);
+ await new Promise((resolve) => setImmediate(resolve));
+
+ // English is all this tab can render, but the preference is the one the
+ // user chose. Keeping the replaced one would leave this tab disagreeing
+ // with storage until a reload, and the next personalization save would
+ // upload that stale language over the other tab's choice.
+ assert.equal(localeStore.getLocalePreference(), "ru");
+ assert.equal(localeStore.getLocale(), "en");
+ assert.equal(localeStore.getPendingLocalePreference(), null);
+ assert.equal(localeStore.getLocaleCatalogFailed(), true);
+ // Storage is where this came from, and nothing about it worked here.
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "ru");
+ } finally {
+ unsubscribe();
+ messagesModule.forgetLocaleLoad("ru");
+ }
+});
+
+// The real component, with only its presentation imports faked, so these assert
+// against the value the shipped Select is actually given.
+const { LanguageSelect } = loadWithStubs<{ LanguageSelect: () => StubElement }>(
+ new URL(
+ "../src/features/settings/components/language-select.tsx",
+ import.meta.url,
+ ),
+ {
+ "react/jsx-runtime": stubJsxRuntime(),
+ "@/components/ui/select": {
+ Select: "Select",
+ SelectContent: "SelectContent",
+ SelectItem: "SelectItem",
+ SelectTrigger: "SelectTrigger",
+ SelectValue: "SelectValue",
+ },
+ "@/components/ui/spinner": { Spinner: "Spinner" },
+ // The store getters are what the module's hooks return, read here without a
+ // renderer so the test drives the same locale state the other tests do.
+ "@/i18n": {
+ AUTO_LOCALE: localeStore.AUTO_LOCALE,
+ LOCALES: messagesModule.LOCALES,
+ isLocalePreference: localeStore.isLocalePreference,
+ setLocale: localeStore.setLocale,
+ useLocale: localeStore.getLocale,
+ useLocaleCatalogFailed: localeStore.getLocaleCatalogFailed,
+ useLocalePreference: localeStore.getLocalePreference,
+ usePendingLocalePreference: localeStore.getPendingLocalePreference,
+ useT: () => (key: string) => key,
+ },
+ },
+);
+
+/** The value the language menu currently shows. */
+function shownLanguage(): unknown {
+ return LanguageSelect().props.value;
+}
+
+/**
+ * Radix's controlled Select only calls onValueChange when the picked value differs
+ * from the one it holds (useControllableState: `if (value !== prop) onChange(value)`),
+ * so whatever it shows is the one language the user cannot pick.
+ */
+function canPick(value: string): boolean {
+ return shownLanguage() !== value;
+}
+
+/** The first element of this type anywhere under the rendered tree. */
+function findStub(node: unknown, type: string): StubElement | null {
+ if (Array.isArray(node)) {
+ for (const child of node) {
+ const found = findStub(child, type);
+ if (found) return found;
+ }
+ return null;
+ }
+ if (node === null || typeof node !== "object") return null;
+ const element = node as StubElement;
+ if (element.type === type) return element;
+ return findStub(element.props?.children, type);
+}
+
+/** The label the trigger shows, which is the placeholder when nothing is named. */
+function shownLabel(): unknown {
+ return findStub(LanguageSelect(), "SelectValue")?.props.placeholder;
+}
+
+test("the language menu shows the language in effect after a catalog failure", async () => {
+ await localeStore.setLocale("en", { loadMessages: () => undefined });
+
+ const result = await localeStore.setLocale("de", {
+ loadMessages: () => Promise.reject(new Error("chunk 404")),
+ adoptOnFailure: true,
+ });
+
+ assert.equal(result, "failed");
+ assert.equal(localeStore.getLocalePreference(), "de");
+ assert.equal(localeStore.getLocale(), "en");
+ // Naming the adopted-but-failed language here would make it the value the
+ // Select already holds, and picking it again would then fire nothing, so a
+ // transient chunk failure would strand the user in English for good. Naming
+ // English instead only moves that on to English, which is the one the user
+ // needs to pick to stop retrying German and keep the language they can read.
+ assert.equal(shownLanguage(), "");
+ assert.ok(canPick("de"));
+ assert.ok(canPick("en"));
+ // Still the language in effect on the trigger, only as the placeholder.
+ assert.equal(shownLabel(), "English");
+});
+
+test("accepting the fallback after a catalog failure is a real choice", async () => {
+ await localeStore.setLocale("en", { loadMessages: () => undefined });
+ store.delete(localeStore.LOCALE_STORAGE_KEY);
+
+ assert.equal(
+ await localeStore.setLocale("de", {
+ loadMessages: () => Promise.reject(new Error("chunk 404")),
+ adoptOnFailure: true,
+ }),
+ "failed",
+ );
+ assert.equal(localeStore.getLocalePreference(), "de");
+
+ // What the user does when they would rather keep English than keep waiting
+ // for a chunk that will not load: pick English. If the menu were already
+ // holding "en" this would fire nothing, leaving German as the preference
+ // their profile keeps and every session keeps failing to load.
+ assert.ok(canPick("en"));
+ assert.equal(
+ await localeStore.setLocale("en", { loadMessages: () => undefined }),
+ "applied",
+ );
+ assert.equal(localeStore.getLocalePreference(), "en");
+ assert.equal(localeStore.getLocaleCatalogFailed(), false);
+ assert.equal(store.get(localeStore.LOCALE_STORAGE_KEY), "en");
+ assert.equal(shownLanguage(), "en");
+});
+
+test("the language menu shows the preference once it is the one in effect", async () => {
+ assert.equal(
+ await localeStore.setLocale("de", {
+ loadMessages: () => Promise.resolve(),
+ }),
+ "applied",
+ );
+
+ assert.equal(localeStore.getLocale(), "de");
+ assert.equal(shownLanguage(), "de");
+});
+
+test("the language menu shows auto rather than the detected locale", () => {
+ assert.equal(
+ localeStore.setLocale("auto", { loadMessages: () => undefined }),
+ "applied",
+ );
+
+ assert.equal(localeStore.getLocalePreference(), "auto");
+ assert.equal(localeStore.getLocale(), "en");
+ assert.equal(shownLanguage(), "auto");
+});
+
+test("the language menu shows a pending choice while its catalog loads", async () => {
+ let finishLoading!: () => void;
+ const loading = new Promise<void>((resolve) => {
+ finishLoading = resolve;
+ });
+
+ const selected = localeStore.setLocale("it", { loadMessages: () => loading });
+ assert.equal(shownLanguage(), "it");
+
+ finishLoading();
+ assert.equal(await selected, "applied");
+ assert.equal(shownLanguage(), "it");
+});
+
+test("auto detection stays retryable when its detected catalog fails", async () => {
+ await localeStore.setLocale("auto", { loadMessages: () => undefined });
+
+ navigatorState.language = "de-DE";
+ navigatorState.languages = ["de-DE"];
+ try {
+ // What hydration issues: adopt the stored preference even when its catalog
+ // never arrives, so the local value does not drift from the server's.
+ const result = await localeStore.setLocale("auto", {
+ loadMessages: () => Promise.reject(new Error("chunk 404")),
+ adoptOnFailure: true,
+ });
+
+ assert.equal(result, "failed");
+ // Auto resolved to German, German never loaded, so English is in effect
+ // while the preference is still, correctly, auto.
+ assert.equal(localeStore.getLocalePreference(), "auto");
+ assert.equal(localeStore.getLocale(), "en");
+
+ // Naming auto here would make Auto-detect the value the Select already
+ // holds, so re-picking it would fire nothing and the failed detection
+ // could never be retried; naming English would do the same to pinning
+ // English, which is the other thing a user does with a failed detection.
+ assert.equal(shownLanguage(), "");
+ assert.equal(shownLabel(), "English");
+ assert.ok(canPick("auto"));
+ assert.ok(canPick("en"));
+
+ // And the retry that buys, once the chunk is reachable again.
+ assert.equal(
+ await localeStore.setLocale("auto", {
+ loadMessages: () => Promise.resolve(),
+ }),
+ "applied",
+ );
+ assert.equal(localeStore.getLocale(), "de");
+ assert.equal(shownLanguage(), "auto");
+ } finally {
+ navigatorState.language = "en-US";
+ navigatorState.languages = ["en-US"];
+ }
+});
+
+test("a refreshed auto whose new catalog fails is still retryable", async () => {
+ await localeStore.setLocale("auto", { loadMessages: () => undefined });
+ assert.equal(localeStore.getLocale(), "en");
+
+ navigatorState.language = "de-DE";
+ navigatorState.languages = ["de-DE"];
+ try {
+ // The shape handleLanguageChange issues on a browser language change:
+ // re-apply the standing auto preference, without adopting on failure.
+ const result = await localeStore.setLocale("auto", {
+ loadMessages: () => Promise.reject(new Error("chunk 404")),
+ });
+
+ assert.equal(result, "failed");
+ assert.equal(localeStore.getLocalePreference(), "auto");
+ assert.equal(localeStore.getLocale(), "en");
+ assert.equal(shownLanguage(), "");
+ assert.equal(shownLabel(), "English");
+ assert.ok(canPick("auto"));
+ assert.ok(canPick("en"));
+ } finally {
+ navigatorState.language = "en-US";
+ navigatorState.languages = ["en-US"];
+ }
+});
+
+test("a rejected pick leaves a working auto preference named", async () => {
+ assert.equal(
+ localeStore.setLocale("auto", { loadMessages: () => undefined }),
+ "applied",
+ );
+
+ // Rejected, so the standing preference never moved and auto is still serving
+ // its own catalog. The menu has to keep naming auto here, or a failed pick of
+ // an unrelated language would be enough to hide it.
+ assert.equal(
+ await localeStore.setLocale("ru", {
+ loadMessages: () => Promise.reject(new Error("chunk 404")),
+ }),
+ "failed",
+ );
+ assert.equal(localeStore.getLocalePreference(), "auto");
+ assert.equal(localeStore.getLocale(), "en");
+ assert.equal(shownLanguage(), "auto");
+});
+
+/** The result, or "pending" when the request is still holding its caller. */
+function settledWithin(request: unknown): Promise<unknown> {
+ return Promise.race([
+ request,
+ new Promise((resolve) => setTimeout(() => resolve("pending"), 200)),
+ ]);
+}
+
+test("a catalog that never settles does not hold the caller forever", async () => {
+ // Accepted, but neither completing nor rejecting: a stalled CDN, proxy or
+ // service worker. Nothing about this request will ever wake the awaiting
+ // hydration, so the store has to.
+ const outcome = await settledWithin(
+ localeStore.setLocale("hi", {
+ loadMessages: () => new Promise<void>(() => {}),
+ adoptOnFailure: true,
+ timeoutMs: 5,
+ }),
+ );
+
+ assert.equal(outcome, "failed");
+ // Adopted on the fallback catalog, exactly as a rejection would leave it.
+ assert.equal(localeStore.getLocalePreference(), "hi");
+ assert.equal(localeStore.getLocale(), "en");
+ assert.equal(localeStore.getPendingLocalePreference(), null);
+ assert.equal(localeStore.getLocaleCatalogFailed(), true);
+});
+
+test("a catalog that arrives after the timeout still commits", async () => {
+ let finishLoading!: () => void;
+ const loading = new Promise<void>((resolve) => {
+ finishLoading = resolve;
+ });
+
+ assert.equal(
+ await settledWithin(
+ localeStore.setLocale("ar", {
+ loadMessages: () => loading,
+ adoptOnFailure: true,
+ timeoutMs: 5,
+ }),
+ ),
+ "failed",
+ );
+ assert.equal(localeStore.getLocale(), "en");
+
+ finishLoading();
+ await loading;
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(localeStore.getLocale(), "ar");
+ assert.equal(localeStore.getLocalePreference(), "ar");
+ assert.equal(localeStore.getLocaleCatalogFailed(), false);
+});
+
+test("a pick that names no bound of its own is still bounded", async () => {
+ await localeStore.setLocale("en", { loadMessages: () => undefined });
+
+ // What the language menu issues: no timeoutMs, so the store's own bound is
+ // all that stands between a stalled catalog and a spinner that never stops.
+ // A stalled load also stays in the in-flight map, so re-picking that language
+ // is handed the same never-settling promise, and reloading the app is the
+ // only way out of it.
+ mock.timers.enable({ apis: ["setTimeout"] });
+ try {
+ const selected = localeStore.setLocale("ko", {
+ loadMessages: () => new Promise<void>(() => {}),
+ });
+ assert.equal(localeStore.getPendingLocalePreference(), "ko");
+
+ mock.timers.tick(localeStore.LOCALE_SELECTION_TIMEOUT_MS);
+
+ assert.equal(localeStore.getPendingLocalePreference(), null);
+ assert.equal(await selected, "failed");
+ } finally {
+ mock.timers.reset();
+ }
+
+ // A rejected pick, so the language that was working is still the one in
+ // effect and is still the one the menu names.
+ assert.equal(localeStore.getLocale(), "en");
+ assert.equal(localeStore.getLocalePreference(), "en");
+ assert.equal(localeStore.getLocaleCatalogFailed(), false);
+});
+
+test("a timed out catalog is evicted so the next pick asks for it again", async () => {
+ await localeStore.setLocale("en", { loadMessages: () => undefined });
+
+ // The real in-flight map, with an import that is accepted and then never
+ // settles: a stalled CDN, proxy or service worker.
+ let requests = 0;
+ const stalled = () => {
+ requests += 1;
+ return new Promise<unknown>(() => {});
+ };
+ const loadMessages = (
+ locale: Parameters<typeof messagesModule.loadLocaleMessages>[0],
+ ) => messagesModule.loadLocaleMessages(locale, stalled);
+
+ mock.timers.enable({ apis: ["setTimeout"] });
+ try {
+ const first = localeStore.setLocale("pt-BR", { loadMessages });
+ mock.timers.tick(localeStore.LOCALE_SELECTION_TIMEOUT_MS);
+ assert.equal(await first, "failed");
+
+ // What the user does next: pick the language again once the network is back.
+ const retry = localeStore.setLocale("pt-BR", { loadMessages });
+ mock.timers.tick(localeStore.LOCALE_SELECTION_TIMEOUT_MS);
+ assert.equal(await retry, "failed");
+ } finally {
+ mock.timers.reset();
+ messagesModule.forgetLocaleLoad("pt-BR");
+ }
+
+ assert.equal(
+ requests,
+ 2,
+ "the retry was handed the timed out load instead of requesting the catalog again",
+ );
+});
+
+test("a timed out startup catalog is evicted so the first pick asks for it again", async () => {
+ store.set(localeStore.LOCALE_STORAGE_KEY, "hi");
+
+ // The real in-flight map, with an import that is accepted and then never
+ // settles: a stalled CDN, proxy or service worker.
+ let requests = 0;
+ const stalled = () => {
+ requests += 1;
+ return new Promise<unknown>(() => {});
+ };
+ const loadMessages = (
+ locale: Parameters<typeof messagesModule.loadLocaleMessages>[0],
+ ) => messagesModule.loadLocaleMessages(locale, stalled);
+
+ mock.timers.enable({ apis: ["setTimeout"] });
+ try {
+ const initialized = localeStore.initializeLocale({ loadMessages });
+ mock.timers.tick(localeStore.LOCALE_INITIALIZATION_TIMEOUT_MS);
+ assert.equal(await initialized, "en");
+
+ // What the user does next: the saved language is on the fallback catalog,
+ // so they pick it again from the menu once the network is back.
+ const picked = localeStore.setLocale("hi", { loadMessages });
+ mock.timers.tick(localeStore.LOCALE_SELECTION_TIMEOUT_MS);
+ assert.equal(await picked, "failed");
+ } finally {
+ mock.timers.reset();
+ messagesModule.forgetLocaleLoad("hi");
+ }
+
+ assert.equal(
+ requests,
+ 2,
+ "the pick was handed the timed out startup load instead of requesting the catalog again",
+ );
+});
diff --git a/studio/frontend/tests/locale-catalog-retry.test.ts b/studio/frontend/tests/locale-catalog-retry.test.ts
new file mode 100644
index 00000000000..31b62f9a6c8
--- /dev/null
+++ b/studio/frontend/tests/locale-catalog-retry.test.ts
@@ -0,0 +1,116 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Chrome, Edge and Firefox before 155 keep a failed module in the module map
+// keyed by URL, so importing the same catalog again resolves to the stored
+// failure without a request. Dropping our own in-flight promise only makes the
+// store willing to ask again; the ask has to reach the network to be a retry.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ installLocalStorageFake,
+ registerBundlerResolver,
+} from "./helpers/kit.ts";
+
+registerBundlerResolver();
+installLocalStorageFake();
+
+const messagesModule = await import("../src/i18n/messages.ts");
+
+const CHUNK_URL = "https://studio.example/assets/de-a1b2c3.js";
+
+type ImporterCall = { locale: string; retryUrl: string | null };
+
+/** Runs a load to completion, reporting whether it failed. */
+async function attempt(load: Promise<void> | undefined): Promise<string> {
+ const [outcome] = await Promise.allSettled([load]);
+ return outcome.status;
+}
+
+function fetchFailure(url: string): TypeError {
+ return new TypeError(`Failed to fetch dynamically imported module: ${url}`);
+}
+
+test("a failed catalog is retried from a different URL", async () => {
+ const calls: ImporterCall[] = [];
+ const importer = (locale: string, retryUrl: string | null) => {
+ calls.push({ locale, retryUrl });
+ if (calls.length === 1) return Promise.reject(fetchFailure(CHUNK_URL));
+ return Promise.resolve({ de: { common: { cancel: "Abbrechen" } } });
+ };
+
+ const first = await attempt(
+ messagesModule.loadLocaleMessages("de", importer),
+ );
+ const second = await attempt(
+ messagesModule.loadLocaleMessages("de", importer),
+ );
+
+ assert.equal(calls.length, 2);
+ assert.equal(first, "rejected");
+ assert.equal(second, "fulfilled");
+ // The first load is a plain import, so the happy path keeps the normal
+ // caching of its hashed file, and only the retry carries a one-off query.
+ assert.equal(calls[0]?.retryUrl, null);
+ assert.notEqual(calls[1]?.retryUrl, null);
+ assert.notEqual(calls[1]?.retryUrl, CHUNK_URL);
+ const retried = new URL(calls[1]?.retryUrl ?? "");
+ assert.equal(retried.origin + retried.pathname, CHUNK_URL);
+ assert.match(
+ retried.searchParams.get(messagesModule.CATALOG_RETRY_PARAM) ?? "",
+ /^\d+$/,
+ );
+ assert.equal(
+ messagesModule.translate("common.cancel", undefined, "de"),
+ "Abbrechen",
+ );
+});
+
+test("a catalog that loaded is not asked for again", () => {
+ assert.equal(
+ messagesModule.loadLocaleMessages("de", () => {
+ throw new Error("should not import");
+ }),
+ undefined,
+ );
+});
+
+test("a failure with no URL in it leaves nothing to cache-bust", async () => {
+ const calls: ImporterCall[] = [];
+ const importer = (locale: string, retryUrl: string | null) => {
+ calls.push({ locale, retryUrl });
+ if (calls.length === 1) return Promise.reject(new Error("boom"));
+ return Promise.resolve({ ru: { common: { cancel: "Отмена" } } });
+ };
+
+ await attempt(messagesModule.loadLocaleMessages("ru", importer));
+ await attempt(messagesModule.loadLocaleMessages("ru", importer));
+
+ assert.deepEqual(
+ calls.map((call) => call.retryUrl),
+ [null, null],
+ );
+});
+
+test("a retry that fails again gets a fresh URL rather than the failed one", async () => {
+ const calls: ImporterCall[] = [];
+ const importer = (locale: string, retryUrl: string | null) => {
+ calls.push({ locale, retryUrl });
+ if (calls.length < 3) return Promise.reject(fetchFailure(CHUNK_URL));
+ return Promise.resolve({ it: { common: { cancel: "Annulla" } } });
+ };
+
+ await attempt(messagesModule.loadLocaleMessages("it", importer));
+ await attempt(messagesModule.loadLocaleMessages("it", importer));
+ await attempt(messagesModule.loadLocaleMessages("it", importer));
+
+ assert.equal(calls.length, 3);
+ assert.equal(calls[0]?.retryUrl, null);
+ assert.notEqual(calls[1]?.retryUrl, calls[2]?.retryUrl);
+ // One query, so a repeated failure cannot grow the URL.
+ assert.equal(
+ [...new URL(calls[2]?.retryUrl ?? "").searchParams.keys()].length,
+ 1,
+ );
+});
diff --git a/studio/frontend/tests/personalization-locale-hydration.test.ts b/studio/frontend/tests/personalization-locale-hydration.test.ts
new file mode 100644
index 00000000000..492ea53f756
--- /dev/null
+++ b/studio/frontend/tests/personalization-locale-hydration.test.ts
@@ -0,0 +1,340 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+// Hydration calls setLocale, which can come back "superseded" when a newer
+// request took the language over. The rest of personalization has still
+// hydrated by then, so the sync has to finish; leaving it unfinished pauses the
+// save gate for the whole signed-in session.
+
+import assert from "node:assert/strict";
+import test from "node:test";
+
+import { loadWithStubs } from "./helpers/module-stubs.ts";
+
+type Slot = {
+ value?: unknown;
+ deps?: readonly unknown[];
+ // Whatever the effect returned: a cleanup, or nothing.
+ cleanup?: unknown;
+ set?: boolean;
+};
+
+function runCleanup(cleanup: unknown): void {
+ if (typeof cleanup === "function") (cleanup as () => void)();
+}
+
+type Profile = {
+ displayName: string;
+ nickname: string;
+ avatarDataUrl: string | null;
+ avatarShape: "circle" | "rounded";
+ showGreetingSloth: boolean;
+};
+
+type SavedPayload = {
+ version: number;
+ profile: Profile;
+ appearance: {
+ theme: string;
+ palette: string;
+ language: string | null;
+ customization: Record<string, unknown>;
+ };
+};
+
+const HOOK_URL = new URL(
+ "../src/features/profile/hooks/use-personalization-sync.ts",
+ import.meta.url,
+);
+
+function sameDeps(a: readonly unknown[], b: readonly unknown[]): boolean {
+ return a.length === b.length && a.every((value, i) => Object.is(value, b[i]));
+}
+
+/** The four hooks the sync uses, with renders and effects the test drives. */
+function createReact() {
+ const slots: Slot[] = [];
+ const effects: (() => void)[] = [];
+ let cursor = 0;
+ let dirty = false;
+
+ const slot = (): Slot => {
+ const existing = slots[cursor];
+ if (existing) {
+ cursor += 1;
+ return existing;
+ }
+ const created: Slot = {};
+ slots[cursor] = created;
+ cursor += 1;
+ return created;
+ };
+
+ const react = {
+ useState<T>(initial: T): [T, (next: T) => void] {
+ const self = slot();
+ if (!self.set) {
+ self.value = initial;
+ self.set = true;
+ }
+ return [
+ self.value as T,
+ (next: T) => {
+ if (Object.is(next, self.value)) return;
+ self.value = next;
+ dirty = true;
+ },
+ ];
+ },
+ useRef<T>(initial: T): { current: T } {
+ const self = slot();
+ if (!self.set) {
+ self.value = { current: initial };
+ self.set = true;
+ }
+ return self.value as { current: T };
+ },
+ useCallback<T>(fn: T, deps: readonly unknown[]): T {
+ const self = slot();
+ if (!self.deps || !sameDeps(self.deps, deps)) {
+ self.value = fn;
+ self.deps = deps;
+ }
+ return self.value as T;
+ },
+ useEffect(fn: () => unknown, deps: readonly unknown[]): void {
+ const self = slot();
+ if (self.deps && sameDeps(self.deps, deps)) return;
+ self.deps = deps;
+ effects.push(() => {
+ runCleanup(self.cleanup);
+ self.cleanup = fn();
+ });
+ },
+ };
+
+ return {
+ react,
+ /** Renders until no state change is left, running effects after each pass. */
+ flush(body: () => void): void {
+ do {
+ cursor = 0;
+ dirty = false;
+ body();
+ while (effects.length) effects.shift()?.();
+ } while (dirty);
+ },
+ unmount(): void {
+ for (const self of slots) runCleanup(self.cleanup);
+ },
+ };
+}
+
+/** Timers the test releases by hand, so the debounced push is not a real wait. */
+function installWindow() {
+ const timers = new Map<number, () => void>();
+ let nextId = 1;
+ Object.assign(globalThis, {
+ window: {
+ setTimeout(fn: () => void): number {
+ const id = nextId;
+ nextId += 1;
+ timers.set(id, fn);
+ return id;
+ },
+ clearTimeout(id: number): void {
+ timers.delete(id);
+ },
+ },
+ });
+ return () => {
+ const due = [...timers.values()];
+ timers.clear();
+ for (const fn of due) fn();
+ };
+}
+
+/** Lets every pending promise callback run. */
+function settle(): Promise<void> {
+ return new Promise((resolve) => setImmediate(resolve));
+}
+
+function remotePersonalization(language: string) {
+ return {
+ version: 3,
+ profile: {
+ displayName: "",
+ nickname: "",
+ avatarDataUrl: null,
+ avatarShape: "circle" as const,
+ showGreetingSloth: true,
+ },
+ appearance: {
+ theme: "system",
+ palette: "standard",
+ language,
+ customization: {},
+ },
+ saved: true,
+ customizationSaved: true,
+ paletteSaved: true,
+ greetingSlothSaved: true,
+ };
+}
+
+function setup(localeResult: "superseded" | "cancelled" | "stalled") {
+ const runTimers = installWindow();
+ const host = createReact();
+ const saves: SavedPayload[] = [];
+ const localeCalls: unknown[] = [];
+ let profile: Profile = {
+ displayName: "",
+ nickname: "",
+ avatarDataUrl: null,
+ avatarShape: "circle",
+ showGreetingSloth: true,
+ };
+ // A newer request already took French, which is the state "superseded"
+ // reports: the hydrated language is not the one in effect.
+ let preference = "auto";
+ let releaseLocale!: () => void;
+ const localeSettled = new Promise<void>((resolve) => {
+ releaseLocale = resolve;
+ });
+
+ const profileStore = Object.assign(
+ (select: (state: Profile) => unknown) => select(profile),
+ {
+ getState: () => profile,
+ setState: (next: Partial<Profile>) => {
+ profile = { ...profile, ...next };
+ },
+ },
+ );
+
+ const { usePersonalizationSync } = loadWithStubs<{
+ usePersonalizationSync: (enabled: boolean) => void;
+ }>(HOOK_URL, {
+ react: host.react,
+ "@/features/settings": {
+ isDefaultCustomization: (value: unknown) =>
+ Object.keys(value as object).length === 0,
+ isPalette: (value: unknown) => typeof value === "string",
+ loadPersonalization: () => Promise.resolve(remotePersonalization("de")),
+ migrateShippedSidebarNavDefault: (value: unknown) => value,
+ sanitizeCustomization: (value: unknown) => value ?? {},
+ savePersonalization: (data: SavedPayload) => {
+ saves.push(data);
+ return Promise.resolve();
+ },
+ setPalette: () => undefined,
+ setTheme: () => undefined,
+ useAppearanceCustomStore: (select: (state: unknown) => unknown) =>
+ select({ customization: {} }),
+ usePalette: () => ({ palette: "standard" }),
+ useTheme: () => ({ theme: "system" }),
+ },
+ "@/i18n": {
+ DEFAULT_LOCALE_PREFERENCE: "auto",
+ LOCALE_INITIALIZATION_TIMEOUT_MS: 2_000,
+ getLocalePreference: () => preference,
+ isLocalePreference: (value: unknown) => typeof value === "string",
+ setLocale: async (value: unknown, options?: { timeoutMs?: number }) => {
+ localeCalls.push(value);
+ // A catalog request the network accepted and never completed. It
+ // rejects nothing, so the only thing that can end this wait is the
+ // caller asking the store to bound it.
+ if (localeResult === "stalled") {
+ if (typeof options?.timeoutMs !== "number") {
+ return new Promise<string>(() => {});
+ }
+ return "failed";
+ }
+ await localeSettled;
+ if (localeResult === "superseded") preference = "fr";
+ return localeResult;
+ },
+ useLocalePreference: () => preference,
+ },
+ "../stores/user-profile-store": {
+ PROFILE_TEXT_MAX_LENGTH: 200,
+ useUserProfileStore: profileStore,
+ },
+ });
+
+ return {
+ host,
+ localeCalls,
+ releaseLocale,
+ runTimers,
+ saves,
+ rename(displayName: string) {
+ profile = { ...profile, displayName };
+ },
+ render() {
+ host.flush(() => usePersonalizationSync(true));
+ },
+ };
+}
+
+test("a superseded locale hydration does not pause personalization saves", async () => {
+ const app = setup("superseded");
+
+ app.render();
+ await settle();
+ assert.deepEqual(app.localeCalls, ["de"]);
+
+ app.releaseLocale();
+ await settle();
+ app.render();
+
+ // Pre-fix the sync returned here without finishing hydration, so the save
+ // effect's generation gate never opened again and nothing the user changed
+ // for the rest of the session was written.
+ app.rename("Ada");
+ app.render();
+ app.runTimers();
+ await settle();
+
+ assert.equal(app.saves.length, 1);
+ assert.equal(app.saves[0]?.profile.displayName, "Ada");
+ // The push carries the language actually in effect, not the superseded one.
+ assert.equal(app.saves[0]?.appearance.language, "fr");
+});
+
+test("a cancelled locale hydration stays paused, because it never finished", async () => {
+ const app = setup("cancelled");
+
+ app.render();
+ await settle();
+ app.host.unmount();
+
+ app.releaseLocale();
+ await settle();
+ app.render();
+ app.rename("Ada");
+ app.render();
+ app.runTimers();
+ await settle();
+
+ assert.equal(app.saves.length, 0);
+});
+
+test("a stalled locale catalog does not pause personalization saves", async () => {
+ const app = setup("stalled");
+
+ app.render();
+ await settle();
+ assert.deepEqual(app.localeCalls, ["de"]);
+
+ // Pre-fix hydration awaited the catalog with no bound, so it never finished
+ // and nothing the user changed for the rest of the session was written.
+ app.render();
+ app.rename("Ada");
+ app.render();
+ app.runTimers();
+ await settle();
+
+ assert.equal(app.saves.length, 1);
+ assert.equal(app.saves[0]?.profile.displayName, "Ada");
+});