fix(webui): keep every concurrently loaded channel locale registered

loadChannelLocale() captured the per-channel translation map before
awaiting the locale loader and re-registered it afterwards. Because
initializeI18n() loads the fallback and initial locales concurrently,
two calls per channel each created their own Map and the one resolving
last replaced the other's registration, silently dropping one locale
from every channel for any user whose stored locale is not en.

Create and register the map synchronously, before any await, so
concurrent loads append to a single shared Map.

Add a regression test that loads two locales concurrently against a
fresh registry instance.
This commit is contained in:
Yao authored and chengyongru committed 2026-09-04 13:46:42 +08:00
1 parent 3d40ed8f76
commit 8fb7bc34ec
2 files changed
+31 -3

No files matched your search

+7 -2
View File
@@ -73,7 +73,13 @@ async function loadChannelLocale(
channel: string,
locale: SupportedLocale,
): Promise<ChannelMessages> {
const translations = translationsByChannel.get(channel) ?? new Map();
// Get-or-create the shared per-channel map synchronously so concurrent locale
// loads append to one Map instead of replacing each other's registration.
let translations = translationsByChannel.get(channel);
if (!translations) {
translations = new Map();
translationsByChannel.set(channel, translations);
}
const loaded = translations.get(locale);
if (loaded) return loaded;
@@ -87,6 +93,5 @@ async function loadChannelLocale(
throw new Error(`Channel '${channel}' locale '${locale}' has no default export`);
}
translations.set(locale, messages);
translationsByChannel.set(channel, translations);
return messages;
}
@@ -1,7 +1,7 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { channelFieldMessageKey } from "@/channel-plugins/i18n";
import { registeredChannelLocales } from "@/channel-plugins/locale-registry";
@@ -113,3 +113,26 @@ describe("channel locale registry", () => {
expect(i18nEntry).not.toContain("channel-plugins/registry");
});
});
describe("channel locale registry concurrency", () => {
it("registers every locale loaded concurrently for the same channel", async () => {
// A fresh module instance starts with an empty registry, which is the state
// startup reaches when the stored locale differs from the fallback locale.
vi.resetModules();
const registry = await import("@/channel-plugins/locale-registry");
await Promise.all([
registry.channelLocaleResources("en"),
registry.channelLocaleResources("zh-CN"),
]);
const registrations = registry.registeredChannelLocales();
expect([...registrations.keys()].sort()).toEqual(expectedChannels);
for (const [channel, locales] of registrations) {
expect([...locales.keys()].sort(), `${channel} concurrent locales`).toEqual([
"en",
"zh-CN",
]);
}
});
});