Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat(web): add interface languages and a Language setting

Kilyn8c41eb607a4b
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 0cb0eaa0..bd937903 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -74,6 +74,10 @@ build:assets` to check the initial JS budget.
accounts for) when unloading models cannot free enough, and says a model
cannot fit only when it needs more than the pool's total. A Computer's detail
on the Computers page links here and reads no model state itself.
+- `src/i18n`: the interface languages (English and Simplified Chinese).
+ `messages.ts` is the React-free core, `language.ts` holds the language on
+ screen and the stored choice, `use-translation.tsx` is the React side, and
+ `locales/` holds one catalog per translated language plus its glossary.
- `src/test`: unit-test support, including the in-process TeamHub test server.
- `e2e`: Playwright product workflows; every spec runs on the real TeamHub and
Document Runtime stack (`make check-e2e-room-document`).
@@ -236,3 +240,37 @@ build:assets` to check the initial JS budget.
React Doctor catches this and it renders fine in unit tests, so assert the outcome
(the wrapper carries the positioning, the clamped node carries no `block`) in a test
and confirm that test fails when the utility is put back on the same element.
+- Interface text on a translated surface comes from a message, not a literal.
+ English is the source and the fallback: a string with no translation shows
+ its English text.
+ - Add a string: declare it in the feature's `*.messages.ts` with
+ `defineMessages("<namespace>", { name: "English text" })`, show it with
+ `const t = useT()` and `t(messages.name)`, and add the same
+ `<namespace>.<name>` to `src/i18n/locales/zh-CN.json` following
+ `src/i18n/locales/zh-CN.glossary.md`. `src/i18n/catalog.test.ts` fails when
+ a key, a `{placeholder}`, a `<tag>` or a plural form is missing from a
+ catalog, or when a catalog keeps a key the source no longer has.
+ - Values go in `{name}` placeholders (`t(m.space, { name })`); never join
+ translated fragments into a sentence, because word order differs. A count
+ is a plural message, `{ one: "{count} file", other: "{count} files" }`,
+ called with `count`; a catalog lists the plural forms of its own language.
+ An element inside a sentence is a `<name>…</name>` span rendered with
+ `RichMessage`, which keeps user-supplied text as text.
+ - Outside React (a toast, an error built in a helper) call `translate()`
+ when the text is shown, never at module load: a module-level string keeps
+ the language it was created in after the Human switches.
+ - Dates and numbers inside translated text take `formatLocale(language)`.
+ `lib/date-format.ts` stays on `APP_LOCALE` for surfaces that are still
+ English, so one screen does not mix an English sentence with a Chinese
+ date.
+ - Names and text that come from TeamHub or from people (Agent names, message
+ previews, server error messages) are data and are shown as they are.
+ - Add a language: add it to `LANGUAGES` and `catalogLoaders` in
+ `src/i18n/language.ts` and add `src/i18n/locales/<tag>.json`. Catalogs
+ load on demand, so English users download none.
+ - The choice is stored on the device (`localStorage["linger.language"]`);
+ an absent value means no explicit choice, which is English today. Tests
+ start in English: `src/test/setup.ts` resets the language after each test,
+ and a test of translated text reads the expected string from the catalog
+ instead of writing Chinese, which the repository gate allows only under
+ `src/i18n/locales/`.
diff --git a/apps/web/src/app/router.tsx b/apps/web/src/app/router.tsx
index c5f3b06a..1c4c223f 100644
--- a/apps/web/src/app/router.tsx
+++ b/apps/web/src/app/router.tsx
@@ -46,6 +46,8 @@ import {
type TeamHubClient,
} from "@/features/teamhub/teamhub-client";
import type { TeamHubRuntime } from "@/features/teamhub/teamhub-runtime";
+import { commonMessages } from "@/i18n/common.messages";
+import { useT } from "@/i18n/use-translation";
import {
tenantWorkItemTargetQueryOptions,
tenantWorkItemsDashboardQueryOptions,
@@ -756,6 +758,14 @@ function createSettingsRoute(): RouteObject {
}),
path: "models",
},
+ {
+ lazy: async () => ({
+ Component: (
+ await import("@/features/settings/language-settings-page")
+ ).LanguageSettingsPage,
+ }),
+ path: "language",
+ },
{ loader: openModels, path: "local-models" },
{ loader: openProfile, path: "administration" },
],
@@ -771,14 +781,15 @@ function createSettingsRoute(): RouteObject {
}
export function InitialAppLoading() {
+ const t = useT();
return (
<main
aria-busy="true"
- aria-label="Loading TeamHub"
+ aria-label={t(commonMessages.loadingApp)}
className="flex min-h-dvh items-center justify-center gap-2 bg-app-canvas text-sm text-app-muted"
>
<Spinner />
- Loading Room...
+ {t(commonMessages.loadingRoom)}
</main>
);
}
diff --git a/apps/web/src/components/ui/modal-dialog.tsx b/apps/web/src/components/ui/modal-dialog.tsx
index d8e9fe64..009f0e87 100644
--- a/apps/web/src/components/ui/modal-dialog.tsx
+++ b/apps/web/src/components/ui/modal-dialog.tsx
@@ -8,6 +8,8 @@ import {
} from "react";
import { Icon } from "@/components/ui/icon";
+import { commonMessages } from "@/i18n/common.messages";
+import { useT } from "@/i18n/use-translation";
export type DialogSize = "sm" | "md" | "lg" | "xl";
@@ -60,6 +62,7 @@ export function ModalDialog({
/** Rendering a title opts the dialog into the shared header/body/footer chrome. */
title?: ReactNode;
}) {
+ const t = useT();
const dialogRef = useRef<HTMLDialogElement>(null);
const closeFromBackdrop = useEffectEvent(() => onClose());
const headingId = useId();
@@ -135,7 +138,7 @@ export function ModalDialog({
) : null}
</div>
<button
- aria-label="Close"
+ aria-label={t(commonMessages.close)}
className="app-dialog-close"
ref={closeButtonRef}
onClick={onClose}
diff --git a/apps/web/src/features/settings/language-settings-page.test.tsx b/apps/web/src/features/settings/language-settings-page.test.tsx
new file mode 100644
index 00000000..67d458a9
--- /dev/null
+++ b/apps/web/src/features/settings/language-settings-page.test.tsx
@@ -0,0 +1,110 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { fireEvent, render, screen, within } from "@testing-library/react";
+import { createMemoryRouter, RouterProvider } from "react-router";
+import { describe, expect, it } from "vitest";
+
+import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";
+import {
+ LANGUAGE_STORAGE_KEY,
+ LANGUAGES,
+ restoreLanguage,
+} from "@/i18n/language";
+import zhCN from "@/i18n/locales/zh-CN.json";
+import { createTestTeamHubRuntime } from "@/test/teamhub-test-runtime";
+
+import { LanguageSettingsPage } from "./language-settings-page";
+import { SettingsLayout } from "./settings-page";
+
+const chinese = zhCN.settings;
+const chineseName = LANGUAGES.find(({ tag }) => tag === "zh-CN")!.name;
+
+describe("Language settings", () => {
+ it("offers each language under its own name, with English chosen", async () => {
+ renderLanguageSettings();
+ const select = await screen.findByRole("combobox", {
+ name: "Interface language",
+ });
+ expect(select).toHaveValue("en");
+ expect(select).toHaveTextContent("English");
+ fireEvent.click(select);
+ const options = await screen.findAllByRole("option");
+ expect(options.map((option) => option.textContent)).toEqual(
+ LANGUAGES.map(({ name }) => name),
+ );
+ expect(options[1]!.querySelector("[lang]")).toHaveAttribute(
+ "lang",
+ "zh-CN",
+ );
+ expect(localStorage.getItem(LANGUAGE_STORAGE_KEY)).toBeNull();
+ });
+
+ it("switches the page and the Settings navigation without a reload", async () => {
+ renderLanguageSettings();
+ await chooseLanguage("Interface language", chineseName);
+
+ expect(
+ await screen.findByRole("heading", { level: 1, name: chinese.language }),
+ ).toBeVisible();
+ const sections = screen.getByRole("navigation", { name: chinese.sections });
+ expect(
+ within(sections).getByRole("link", { name: chinese.profile }),
+ ).toBeVisible();
+ expect(
+ screen.getByRole("combobox", { name: chinese.interfaceLanguage }),
+ ).toHaveAccessibleDescription(chinese.interfaceLanguageHint);
+ expect(screen.queryByText("Interface language")).not.toBeInTheDocument();
+ expect(document.documentElement).toHaveAttribute("lang", "zh-CN");
+ expect(localStorage.getItem(LANGUAGE_STORAGE_KEY)).toBe("zh-CN");
+
+ await chooseLanguage(chinese.interfaceLanguage, "English");
+ expect(
+ await screen.findByRole("heading", { level: 1, name: "Language" }),
+ ).toBeVisible();
+ expect(document.documentElement).toHaveAttribute("lang", "en");
+ expect(localStorage.getItem(LANGUAGE_STORAGE_KEY)).toBe("en");
+ });
+
+ it("opens in the language chosen on an earlier visit", async () => {
+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "zh-CN");
+ await restoreLanguage();
+ renderLanguageSettings();
+ expect(
+ await screen.findByRole("combobox", { name: chinese.interfaceLanguage }),
+ ).toHaveValue("zh-CN");
+ expect(
+ screen.getByRole("heading", { level: 1, name: chinese.language }),
+ ).toBeVisible();
+ });
+});
+
+async function chooseLanguage(label: string, name: string) {
+ fireEvent.click(await screen.findByRole("combobox", { name: label }));
+ fireEvent.click(await screen.findByRole("option", { name }));
+}
+
+function renderLanguageSettings() {
+ render(
+ <QueryClientProvider
+ client={
+ new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ }
+ >
+ <TeamHubRuntimeProvider runtime={createTestTeamHubRuntime()}>
+ <RouterProvider
+ router={createMemoryRouter(
+ [
+ {
+ children: [
+ { element: <LanguageSettingsPage />, path: "language" },
+ ],
+ element: <SettingsLayout />,
+ path: "/t/:tenantId/settings",
+ },
+ ],
+ { initialEntries: ["/t/tenant-northstar/settings/language"] },
+ )}
+ />
+ </TeamHubRuntimeProvider>
+ </QueryClientProvider>,
+ );
+}
diff --git a/apps/web/src/features/settings/language-settings-page.tsx b/apps/web/src/features/settings/language-settings-page.tsx
new file mode 100644
index 00000000..7b636a54
--- /dev/null
+++ b/apps/web/src/features/settings/language-settings-page.tsx
@@ -0,0 +1,68 @@
+import { useState } from "react";
+
+import { Select, SelectItem } from "@/components/ui/select";
+import { isLanguage, LANGUAGES, setLanguage } from "@/i18n/language";
+import { useTranslation } from "@/i18n/use-translation";
+
+import { SettingsPageHeading } from "./settings-page-heading";
+import { settingsMessages } from "./settings.messages";
+
+export function LanguageSettingsPage() {
+ const { language, t } = useTranslation();
+ const [failed, setFailed] = useState(false);
+ const [switching, setSwitching] = useState(false);
+
+ function choose(value: string) {
+ if (!isLanguage(value) || value === language) return;
+ setFailed(false);
+ setSwitching(true);
+ setLanguage(value)
+ .catch(() => setFailed(true))
+ .finally(() => setSwitching(false));
+ }
+
+ return (
+ <div className="mx-auto flex w-full max-w-(--app-settings-width) flex-col gap-8 pb-4">
+ <SettingsPageHeading
+ description={t(settingsMessages.languageDescription)}
+ title={t(settingsMessages.language)}
+ />
+
+ <section className="rounded-2xl border border-border bg-background p-6">
+ <div className="flex flex-col justify-center gap-3 sm:flex-row sm:items-center sm:justify-between">
+ <div className="min-w-0">
+ <p className="text-sm text-foreground" id="interface-language">
+ {t(settingsMessages.interfaceLanguage)}
+ </p>
+ <p
+ className="text-sm text-muted-foreground"
+ id="interface-language-hint"
+ >
+ {t(settingsMessages.interfaceLanguageHint)}
+ </p>
+ </div>
+ {/* Each language is named in itself, so it can be found from any other. */}
+ <Select
+ aria-describedby="interface-language-hint"
+ aria-label={t(settingsMessages.interfaceLanguage)}
+ className="w-full shrink-0 sm:w-44"
+ disabled={switching}
+ onValueChange={choose}
+ value={language}
+ >
+ {LANGUAGES.map(({ name, tag }) => (
+ <SelectItem key={tag} value={tag}>
+ <span lang={tag}>{name}</span>
+ </SelectItem>
+ ))}
+ </Select>
+ </div>
+ {failed ? (
+ <p className="mt-3 text-sm text-app-danger" role="alert">
+ {t(settingsMessages.languageUnavailable)}
+ </p>
+ ) : null}
+ </section>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/settings/settings-page.tsx b/apps/web/src/features/settings/settings-page.tsx
index 093df87f..e058cc2f 100644
--- a/apps/web/src/features/settings/settings-page.tsx
+++ b/apps/web/src/features/settings/settings-page.tsx
@@ -1,51 +1,69 @@
import {
AiChipIcon,
Key01Icon,
+ LanguageSkillIcon,
LaptopIcon,
UserIcon,
} from "@hugeicons/core-free-icons";
import { Icon } from "@/components/ui/icon";
-import { Suspense, type ReactNode } from "react";
+import { Suspense, useEffect, useRef, type ReactNode } from "react";
import { NavLink, Outlet, useLocation } from "react-router";
import { Skeleton } from "@/components/ui/skeleton";
+import { useT } from "@/i18n/use-translation";
+
+import { settingsMessages } from "./settings.messages";
/** Settings is a page in the Space shell: its own sections beside the rail. */
export function SettingsLayout() {
const { pathname } = useLocation();
+ const t = useT();
+ const sections = useRef<HTMLElement>(null);
+ // In a narrow window the sections scroll sideways; the open one stays in view.
+ useEffect(() => {
+ sections.current
+ ?.querySelector('[aria-current="page"]')
+ ?.scrollIntoView({ block: "nearest", inline: "nearest" });
+ }, [pathname]);
return (
<div className="flex min-h-0 flex-1 flex-col md:flex-row">
<aside
- aria-label="Settings navigation"
+ aria-label={t(settingsMessages.navigation)}
className="flex shrink-0 flex-col border-b border-border px-3 py-4 md:w-[228px] md:border-r md:border-b-0"
>
<div className="flex items-center pt-0.5 pb-3.5">
- <h1 className="text-lg">Settings</h1>
+ <h1 className="text-lg">{t(settingsMessages.title)}</h1>
</div>
<nav
- aria-label="Settings sections"
+ aria-label={t(settingsMessages.sections)}
className="workspace-scrollbar flex min-h-0 flex-1 gap-0.5 overflow-x-auto md:flex-col md:overflow-x-visible md:overflow-y-auto"
+ ref={sections}
>
<SettingsLink
icon={<Icon icon={UserIcon} size={14} />}
- label="Profile"
+ label={t(settingsMessages.profile)}
to="account"
/>
<SettingsLink
icon={<Icon icon={Key01Icon} size={14} />}
- label="Security"
+ label={t(settingsMessages.security)}
to="security"
/>
<SettingsLink
icon={<Icon icon={LaptopIcon} size={14} />}
- label="Computers"
+ label={t(settingsMessages.computers)}
to="computers"
/>
<SettingsLink
icon={<Icon icon={AiChipIcon} size={14} />}
- label="Models"
+ label={t(settingsMessages.models)}
to="models"
/>
+ <SettingsLink
+ icon={<Icon icon={LanguageSkillIcon} size={14} />}
+ label={t(settingsMessages.language)}
+ to="language"
+ />
</nav>
</aside>
<div className="workspace-content-viewport workspace-scrollbar flex min-h-0 min-w-0 flex-1 flex-col overflow-y-auto px-6 py-6 [scrollbar-gutter:stable] md:px-8">
@@ -64,7 +82,12 @@ export function SettingsLayout() {
}
function SettingsSectionLoading({ computers }: { computers: boolean }) {
- const label = computers ? "Loading Computers" : "Loading content";
+ const t = useT();
+ const label = t(
+ computers
+ ? settingsMessages.loadingComputers
+ : settingsMessages.loadingContent,
+ );
return (
<div
aria-busy="true"
diff --git a/apps/web/src/features/settings/settings-pages.test.tsx b/apps/web/src/features/settings/settings-pages.test.tsx
index 984a786e..14d37d31 100644
--- a/apps/web/src/features/settings/settings-pages.test.tsx
+++ b/apps/web/src/features/settings/settings-pages.test.tsx
@@ -169,7 +169,7 @@ describe("Settings surfaces", () => {
within(settingsNav)
.getAllByRole("link")
.map((link) => link.textContent?.replace(/\s+/g, " ").trim()),
- ).toEqual(["Profile", "Security", "Computers", "Models"]);
+ ).toEqual(["Profile", "Security", "Computers", "Models", "Language"]);
expect(
screen.queryByRole("button", { name: "Log out" }),
).not.toBeInTheDocument();
diff --git a/apps/web/src/features/settings/settings.messages.ts b/apps/web/src/features/settings/settings.messages.ts
new file mode 100644
index 00000000..da50005e
--- /dev/null
+++ b/apps/web/src/features/settings/settings.messages.ts
@@ -0,0 +1,20 @@
+import { defineMessages } from "@/i18n/messages";
+
+export const settingsMessages = defineMessages("settings", {
+ navigation: "Settings navigation",
+ title: "Settings",
+ sections: "Settings sections",
+ profile: "Profile",
+ security: "Security",
+ computers: "Computers",
+ models: "Models",
+ language: "Language",
+ loadingComputers: "Loading Computers",
+ loadingContent: "Loading content",
+ languageDescription: "Choose the language Linger is shown in.",
+ interfaceLanguage: "Interface language",
+ interfaceLanguageHint:
+ "Saved on this device. Text written by Agents and other people stays as they wrote it.",
+ languageUnavailable:
+ "That language could not be loaded. Check your connection and try again.",
+});
diff --git a/apps/web/src/i18n/catalog.test.ts b/apps/web/src/i18n/catalog.test.ts
new file mode 100644
index 00000000..531b44c0
--- /dev/null
+++ b/apps/web/src/i18n/catalog.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, it } from "vitest";
+
+import { LANGUAGES, SOURCE_LANGUAGE } from "./language";
+import zhCN from "./locales/zh-CN.json";
+import type { Catalog, Message, MessageSource } from "./messages";
+
+// Every namespace of the client, found by file name so that a new
+// `*.messages.ts` is checked without being listed here.
+const modules = import.meta.glob<Record<string, Record<string, Message>>>(
+ "../**/*.messages.ts",
+ { eager: true },
+);
+
+const source = new Map<string, MessageSource>();
+for (const exports of Object.values(modules)) {
+ for (const messages of Object.values(exports)) {
+ for (const message of Object.values(messages)) {
+ if (source.has(message.id)) {
+ throw new Error(`Two messages are named ${message.id}`);
+ }
+ source.set(message.id, message.source);
+ }
+ }
+}
+
+const catalogs: Record<string, Catalog> = { "zh-CN": zhCN };
+
+/**
+ * English messages a catalog may still lack, as `namespace.name`. A message
+ * listed here shows in English until it is translated; keep the list empty
+ * unless a translation is knowingly postponed.
+ */
+const untranslated: Record<string, readonly string[]> = { "zh-CN": [] };
+
+function forms(text: MessageSource): string[] {
+ return typeof text === "string" ? [text] : Object.values(text);
+}
+
+function names(text: MessageSource, pattern: RegExp): string[] {
+ return [
+ ...new Set(
+ forms(text).flatMap((form) =>
+ [...form.matchAll(pattern)].map((match) => match[1]!),
+ ),
+ ),
+ ].sort();
+}
+
+const placeholder = /\{(\w+)\}/gu;
+const openingTag = /<(\w+)>/gu;
+const span = /<(\w+)>.*?<\/\1>/gsu;
+
+describe("message catalogs", () => {
+ it("finds the message modules of the client", () => {
+ expect(source.size).toBeGreaterThan(0);
+ for (const id of source.keys()) {
+ // The catalog is addressed as namespace, then name.
+ expect(id.split(".")).toHaveLength(2);
+ }
+ });
+
+ it("has a catalog for every language except the source", () => {
+ expect(Object.keys(catalogs).sort()).toEqual(
+ LANGUAGES.map((language) => language.tag)
+ .filter((tag) => tag !== SOURCE_LANGUAGE)
+ .sort(),
+ );
+ });
+
+ describe.each(Object.entries(catalogs))("%s", (language, catalog) => {
+ const translated = new Map<string, MessageSource>(
+ Object.entries(catalog).flatMap(([namespace, messages]) =>
+ Object.entries(messages).map(
+ ([name, text]) => [`${namespace}.${name}`, text] as const,
+ ),
+ ),
+ );
+
+ it("translates every English message", () => {
+ const missing = [...source.keys()].filter((id) => !translated.has(id));
+ expect(missing.sort()).toEqual([...untranslated[language]!].sort());
+ });
+
+ it("has no translation without an English message", () => {
+ expect([...translated.keys()].filter((id) => !source.has(id))).toEqual(
+ [],
+ );
+ });
+
+ it("keeps the placeholders and tags of each message", () => {
+ const different = [...translated]
+ .filter(([id]) => source.has(id))
+ .filter(([id, text]) => {
+ const english = source.get(id)!;
+ return (
+ names(text, placeholder).join() !==
+ names(english, placeholder).join() ||
+ names(text, openingTag).join() !==
+ names(english, openingTag).join() ||
+ // Every tag of a translation is closed, so none shows as text.
+ forms(text).some(
+ (form) =>
+ (form.match(openingTag) ?? []).length !==
+ (form.match(span) ?? []).length,
+ )
+ );
+ })
+ .map(([id]) => id);
+ expect(different).toEqual([]);
+ });
+
+ it("gives plural messages the forms the language uses", () => {
+ const categories = [
+ ...new Intl.PluralRules(language).resolvedOptions().pluralCategories,
+ ].sort();
+ const wrong = [...translated]
+ .filter(([id]) => source.has(id))
+ .filter(([id, text]) => {
+ const plural = typeof source.get(id) !== "string";
+ if (typeof text === "string") return plural;
+ return (
+ !plural || Object.keys(text).sort().join() !== categories.join()
+ );
+ })
+ .map(([id]) => id);
+ expect(wrong).toEqual([]);
+ });
+ });
+});
diff --git a/apps/web/src/i18n/common.messages.ts b/apps/web/src/i18n/common.messages.ts
new file mode 100644
index 00000000..6028805c
--- /dev/null
+++ b/apps/web/src/i18n/common.messages.ts
@@ -0,0 +1,11 @@
+import { defineMessages } from "./messages";
+
+/** Text shown before any feature loads, and words every feature shares. */
+export const commonMessages = defineMessages("common", {
+ close: "Close",
+ loadingApp: "Loading TeamHub",
+ loadingRoom: "Loading Room...",
+ unavailableTitle: "Web client unavailable",
+ unavailableBody: "The application could not finish loading.",
+ tryAgain: "Try again",
+});
diff --git a/apps/web/src/i18n/language.test.ts b/apps/web/src/i18n/language.test.ts
new file mode 100644
index 00000000..9a7be5a5
--- /dev/null
+++ b/apps/web/src/i18n/language.test.ts
@@ -0,0 +1,104 @@
+// @vitest-environment jsdom
+import { describe, expect, it, vi } from "vitest";
+
+import { settingsMessages } from "@/features/settings/settings.messages";
+
+import {
+ LANGUAGE_STORAGE_KEY,
+ formatLocale,
+ getLanguage,
+ getTranslation,
+ restoreLanguage,
+ setLanguage,
+ subscribeToLanguage,
+ translate,
+} from "./language";
+import zhCN from "./locales/zh-CN.json";
+
+describe("interface language", () => {
+ it("starts in English with nothing stored", async () => {
+ await restoreLanguage();
+ expect(getLanguage()).toBe("en");
+ expect(translate(settingsMessages.title)).toBe("Settings");
+ expect(localStorage.getItem(LANGUAGE_STORAGE_KEY)).toBeNull();
+ });
+
+ it("switches at once, remembers the choice and marks the document", async () => {
+ const changed = vi.fn();
+ const unsubscribe = subscribeToLanguage(changed);
+ const english = getTranslation();
+ await setLanguage("zh-CN");
+ unsubscribe();
+ expect(changed).toHaveBeenCalledTimes(1);
+ expect(getTranslation()).not.toBe(english);
+ expect(getLanguage()).toBe("zh-CN");
+ expect(translate(settingsMessages.title)).toBe(zhCN.settings.title);
+ expect(localStorage.getItem(LANGUAGE_STORAGE_KEY)).toBe("zh-CN");
+ expect(document.documentElement.lang).toBe("zh-CN");
+
+ await setLanguage("en");
+ expect(translate(settingsMessages.title)).toBe("Settings");
+ expect(localStorage.getItem(LANGUAGE_STORAGE_KEY)).toBe("en");
+ expect(document.documentElement.lang).toBe("en");
+ });
+
+ it("restores the remembered language before the app renders", async () => {
+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "zh-CN");
+ await restoreLanguage();
+ expect(getLanguage()).toBe("zh-CN");
+ expect(document.documentElement.lang).toBe("zh-CN");
+ });
+
+ it("ignores a stored value it does not know and leaves it in place", async () => {
+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "system");
+ await restoreLanguage();
+ expect(getLanguage()).toBe("en");
+ expect(localStorage.getItem(LANGUAGE_STORAGE_KEY)).toBe("system");
+ });
+
+ it("follows a choice made in another tab", async () => {
+ await restoreLanguage();
+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "zh-CN");
+ window.dispatchEvent(
+ new StorageEvent("storage", { key: LANGUAGE_STORAGE_KEY }),
+ );
+ await vi.waitFor(() => expect(getLanguage()).toBe("zh-CN"));
+ });
+
+ it("keeps the newest choice when two switches overlap", async () => {
+ const first = setLanguage("zh-CN");
+ const second = setLanguage("en");
+ await Promise.all([first, second]);
+ expect(getLanguage()).toBe("en");
+ });
+
+ it("keeps another tab's newer choice over a switch still loading", async () => {
+ await restoreLanguage();
+ const mine = setLanguage("zh-CN");
+ // Another tab chooses English while the Chinese catalog is loading.
+ localStorage.setItem(LANGUAGE_STORAGE_KEY, "en");
+ window.dispatchEvent(
+ new StorageEvent("storage", { key: LANGUAGE_STORAGE_KEY }),
+ );
+ await mine;
+ await vi.waitFor(() => expect(getLanguage()).toBe("en"));
+ expect(localStorage.getItem(LANGUAGE_STORAGE_KEY)).toBe("en");
+ expect(document.documentElement.lang).toBe("en");
+ });
+
+ it("still switches when the choice cannot be saved", async () => {
+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new DOMException("denied", "SecurityError");
+ });
+ await setLanguage("zh-CN");
+ expect(getLanguage()).toBe("zh-CN");
+ expect(localStorage).toHaveLength(0);
+ });
+
+ it("names the Intl locale of the language on screen", async () => {
+ expect(formatLocale()).toBe("en-US");
+ await setLanguage("zh-CN");
+ expect(formatLocale()).toBe("zh-CN");
+ expect(formatLocale("en")).toBe("en-US");
+ });
+});
diff --git a/apps/web/src/i18n/language.ts b/apps/web/src/i18n/language.ts
new file mode 100644
index 00000000..bb9ae3f0
--- /dev/null
+++ b/apps/web/src/i18n/language.ts
@@ -0,0 +1,160 @@
+import { loadHanFont } from "@/app/han-font";
+
+import {
+ formatMessage,
+ type Catalog,
+ type Message,
+ type MessageArguments,
+} from "./messages";
+
+/**
+ * The languages the interface is offered in, each named in its own language.
+ * English is the source every message is written in and the fallback.
+ */
+export const LANGUAGES = [
+ { tag: "en", name: "English" },
+ { tag: "zh-CN", name: "\u7b80\u4f53\u4e2d\u6587" },
+] as const;
+
+export type Language = (typeof LANGUAGES)[number]["tag"];
+
+export const SOURCE_LANGUAGE = "en" satisfies Language;
+
+/**
+ * The choice is kept per browser, not per account: the sign-in page and the
+ * desktop shell show text before any account is known. No stored value means
+ * the user has not chosen, so a default other than English can be introduced
+ * later without rewriting what is stored.
+ */
+export const LANGUAGE_STORAGE_KEY = "linger.language";
+
+const catalogLoaders: Record<
+ Exclude<Language, typeof SOURCE_LANGUAGE>,
+ () => Promise<Catalog>
+> = {
+ "zh-CN": async () => (await import("./locales/zh-CN.json")).default,
+};
+
+/** Formats one message in the language of the snapshot it belongs to. */
+export type Translate = <M extends Message>(
+ message: M,
+ ...values: MessageArguments<M["source"]>
+) => string;
+
+/** The language on screen and the lookup for it; replaced as one on a switch. */
+export interface Translation {
+ readonly language: Language;
+ /** The loaded translations; English needs none. */
+ readonly catalog: Catalog | undefined;
+ readonly t: Translate;
+}
+
+function createTranslation(
+ language: Language,
+ catalog: Catalog | undefined,
+): Translation {
+ return {
+ language,
+ catalog,
+ t: (message, ...values) =>
+ formatMessage(message, language, catalog, values[0]),
+ };
+}
+
+let translation = createTranslation(SOURCE_LANGUAGE, undefined);
+// A newer choice wins when two catalogs are still loading.
+let latestRequest = 0;
+const listeners = new Set<() => void>();
+
+export function isLanguage(value: unknown): value is Language {
+ return LANGUAGES.some((language) => language.tag === value);
+}
+
+export function getTranslation(): Translation {
+ return translation;
+}
+
+export function getLanguage(): Language {
+ return translation.language;
+}
+
+export function subscribeToLanguage(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+/** Formats a message outside React, in the language on screen right now. */
+export const translate: Translate = (message, ...values) =>
+ translation.t(message, ...values);
+
+/** The `Intl` locale for dates, numbers and lists in the language on screen. */
+export function formatLocale(language: Language = translation.language) {
+ // English keeps the US conventions the client has always used.
+ return language === "en" ? "en-US" : language;
+}
+
+function storedLanguage(): Language | undefined {
+ try {
+ const stored = localStorage.getItem(LANGUAGE_STORAGE_KEY);
+ return isLanguage(stored) ? stored : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
+/** Shows `language`; false when a newer choice took over while it loaded. */
+async function showLanguage(language: Language): Promise<boolean> {
+ const request = ++latestRequest;
+ const catalog =
+ language === SOURCE_LANGUAGE ? undefined : await catalogLoaders[language]();
+ if (request !== latestRequest) return false;
+ translation = createTranslation(language, catalog);
+ if (typeof document !== "undefined") {
+ document.documentElement.lang = language;
+ loadHanFont([language, ...navigator.languages]);
+ }
+ for (const listener of listeners) listener();
+ return true;
+}
+
+/**
+ * Switches the interface to `language` and remembers the choice. Rejects, with
+ * the previous language still on screen, when the catalog cannot be loaded.
+ * A newer choice made while the catalog loads, here or in another tab, wins:
+ * this one is then neither shown nor remembered.
+ */
+export async function setLanguage(language: Language) {
+ if (!(await showLanguage(language))) return;
+ try {
+ localStorage.setItem(LANGUAGE_STORAGE_KEY, language);
+ } catch {
+ // The switch still holds for this session without saved preferences.
+ }
+}
+
+let followingOtherTabs = false;
+
+/**
+ * Shows the remembered language before the first paint. A catalog that cannot
+ * be loaded leaves the interface in English instead of blocking the start.
+ */
+export async function restoreLanguage() {
+ if (typeof window !== "undefined" && !followingOtherTabs) {
+ followingOtherTabs = true;
+ // Another tab of this browser changed the language: follow it.
+ window.addEventListener("storage", (event) => {
+ if (event.key !== LANGUAGE_STORAGE_KEY) return;
+ void showLanguage(storedLanguage() ?? SOURCE_LANGUAGE).catch(() => {});
+ });
+ }
+ const language = storedLanguage();
+ if (!language || language === translation.language) return;
+ await showLanguage(language).catch(() => {});
+}
+
+/** Puts the interface back to English between tests. */
+export function resetLanguageForTest() {
+ latestRequest += 1;
+ translation = createTranslation(SOURCE_LANGUAGE, undefined);
+ for (const listener of listeners) listener();
+}
diff --git a/apps/web/src/i18n/locales/zh-CN.glossary.md b/apps/web/src/i18n/locales/zh-CN.glossary.md
new file mode 100644
index 00000000..9a6c1f8c
--- /dev/null
+++ b/apps/web/src/i18n/locales/zh-CN.glossary.md
@@ -0,0 +1,62 @@
+# Simplified Chinese (zh-CN) Glossary
+
+The terms and style `zh-CN.json` follows. Check a new translation against this
+file, and add a term here the first time it needs a decision.
+
+## Stay in English
+
+Product names and the concepts people see in commands, logs and documentation
+keep their English form, so the interface matches what a Human types and reads
+elsewhere.
+
+| Term | Note |
+| ------------------------------------ | --------------------------------------------------- |
+| Linger, TeamHub | Product names. |
+| Agent, Room, Runtime, Skill, Routine | Product concepts. |
+| Another Me, Wiki | Feature names. |
+| CLI, PowerShell, npm, Node.js | Tools. |
+| Claude Code, Codex, Pi, Antigravity | App names. |
+| Local Computer | Only when it names the background program. |
+| Reconnect This Computer | A desktop menu item, quoted until it is translated. |
+
+## Translated
+
+| English | Chinese | Note |
+| -------------------------- | -------- | ------------------------------------------------- |
+| Computer | 电脑 | The machine an Agent runs on. |
+| Local Computer (a machine) | 本地电脑 | The field or the machine, not the program. |
+| Model | 模型 | |
+| Task | 任务 | |
+| Messages | 消息 | |
+| Chat | 对话 | |
+| Library | 资料库 | |
+| Connectors | 连接器 | |
+| Settings | 设置 | |
+| Profile | 个人资料 | |
+| Security | 安全 | |
+| Language | 语言 | |
+| Space | 空间 | |
+| Meetings | 会议 | |
+| Pocket Notes | 随手记 | Proposed; the product owner has not confirmed it. |
+| Create (a menu entry) | 新建 | Opens a choice of what to create. |
+| Create (a confirm button) | 创建 | Carries the action out. |
+| Pin | 置顶 | |
+| Log out | 退出登录 | |
+| Thinking effort | 思考强度 | |
+| Token | 令牌 | |
+| Workspace | 工作区 | |
+| Server | 服务器 | |
+
+## Style
+
+- Put one space between Chinese and Latin letters or digits: `连接 Agent`,
+ `3 条未读消息`.
+- Use full-width punctuation in sentences (`,` `。` `:` `?`) and `…` for an
+ ellipsis.
+- Labels, buttons, menu entries and tooltips have no closing period. Full
+ sentences do.
+- Address the Human as `你`, not `您`.
+- Prefer the short everyday word a native app would use over a literal
+ rendering of the English.
+- Keep every `{placeholder}` and `<tag>` of the English source; move them to
+ where the Chinese sentence needs them.
diff --git a/apps/web/src/i18n/locales/zh-CN.json b/apps/web/src/i18n/locales/zh-CN.json
new file mode 100644
index 00000000..f1a64b51
--- /dev/null
+++ b/apps/web/src/i18n/locales/zh-CN.json
@@ -0,0 +1,26 @@
+{
+ "common": {
+ "close": "关闭",
+ "loadingApp": "正在加载 TeamHub",
+ "loadingRoom": "正在加载 Room…",
+ "unavailableTitle": "Web 客户端暂不可用",
+ "unavailableBody": "应用未能完成加载。",
+ "tryAgain": "重试"
+ },
+ "settings": {
+ "navigation": "设置导航",
+ "title": "设置",
+ "sections": "设置分区",
+ "profile": "个人资料",
+ "security": "安全",
+ "computers": "电脑",
+ "models": "模型",
+ "language": "语言",
+ "loadingComputers": "正在加载电脑",
+ "loadingContent": "正在加载内容",
+ "languageDescription": "选择 Linger 界面使用的语言。",
+ "interfaceLanguage": "界面语言",
+ "interfaceLanguageHint": "仅保存在这台设备上。Agent 和其他人写的内容保持原样,不会被翻译。",
+ "languageUnavailable": "无法加载这种语言,请检查网络后重试。"
+ }
+}
diff --git a/apps/web/src/i18n/messages.test.ts b/apps/web/src/i18n/messages.test.ts
new file mode 100644
index 00000000..1a61345c
--- /dev/null
+++ b/apps/web/src/i18n/messages.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from "vitest";
+
+import {
+ defineMessages,
+ formatMessage,
+ formatMessageParts,
+ type Catalog,
+} from "./messages";
+
+const messages = defineMessages("sample", {
+ greeting: "Hello, {name}",
+ plain: "Settings",
+ unread: { one: "{count} unread message", other: "{count} unread messages" },
+ help: "Read <link>the guide for {name}</link> first.",
+});
+
+const translated: Catalog = {
+ sample: {
+ greeting: "Bonjour, {name}",
+ unread: {
+ one: "{count} message non lu",
+ other: "{count} messages non lus",
+ },
+ help: "Lisez d'abord <link>le guide de {name}</link>.",
+ },
+};
+
+describe("message formatting", () => {
+ it("names each message by its namespace and key", () => {
+ expect(messages.greeting).toEqual({
+ id: "sample.greeting",
+ source: "Hello, {name}",
+ });
+ });
+
+ it("fills placeholders in the English source and in a translation", () => {
+ expect(
+ formatMessage(messages.greeting, "en", undefined, { name: "Ada" }),
+ ).toBe("Hello, Ada");
+ expect(
+ formatMessage(messages.greeting, "fr", translated, { name: "Ada" }),
+ ).toBe("Bonjour, Ada");
+ });
+
+ it("shows the English source for a message the catalog does not have", () => {
+ expect(formatMessage(messages.plain, "fr", translated)).toBe("Settings");
+ expect(formatMessage(messages.plain, "fr", {})).toBe("Settings");
+ });
+
+ it("selects the plural form of the language the text is in", () => {
+ const unread = (
+ language: string,
+ catalog: Catalog | undefined,
+ count: number,
+ ) => formatMessage(messages.unread, language, catalog, { count });
+ expect(unread("en", undefined, 1)).toBe("1 unread message");
+ expect(unread("en", undefined, 2)).toBe("2 unread messages");
+ // French counts zero as singular; the form follows the translation.
+ expect(unread("fr", translated, 0)).toBe("0 message non lu");
+ // A language with one form only supplies `other`.
+ expect(
+ unread("zh-CN", { sample: { unread: { other: "{count} unread" } } }, 1),
+ ).toBe("1 unread");
+ // An untranslated plural falls back to English text and English rules.
+ expect(unread("zh-CN", {}, 1)).toBe("1 unread message");
+ });
+
+ it("writes numbers the way the language of the text groups digits", () => {
+ expect(
+ formatMessage(messages.unread, "en", undefined, { count: 12345 }),
+ ).toBe("12,345 unread messages");
+ expect(
+ formatMessage(
+ messages.unread,
+ "de",
+ { sample: { unread: { other: "{count} ungelesen" } } },
+ { count: 12345 },
+ ),
+ ).toBe("12.345 ungelesen");
+ // A string value is never reformatted.
+ expect(
+ formatMessage(messages.greeting, "en", undefined, { name: "12345" }),
+ ).toBe("Hello, 12345");
+ });
+
+ it("cuts a message at its tags, wherever the translation puts them", () => {
+ expect(
+ formatMessageParts(messages.help, "en", undefined, { name: "Ada" }),
+ ).toEqual([
+ { text: "Read " },
+ { tag: "link", text: "the guide for Ada" },
+ { text: " first." },
+ ]);
+ expect(
+ formatMessageParts(messages.help, "fr", translated, { name: "Ada" }),
+ ).toEqual([
+ { text: "Lisez d'abord " },
+ { tag: "link", text: "le guide de Ada" },
+ { text: "." },
+ ]);
+ });
+
+ it("keeps a value that looks like a tag as plain text", () => {
+ expect(
+ formatMessageParts(messages.greeting, "en", undefined, {
+ name: "<link>Ada</link>",
+ }),
+ ).toEqual([{ text: "Hello, <link>Ada</link>" }]);
+ });
+});
diff --git a/apps/web/src/i18n/messages.ts b/apps/web/src/i18n/messages.ts
new file mode 100644
index 00000000..f610b778
--- /dev/null
+++ b/apps/web/src/i18n/messages.ts
@@ -0,0 +1,190 @@
+/**
+ * Message catalogs without React or the DOM: the English source declared
+ * beside the code that shows it, and the lookup that picks a translation,
+ * a plural form and the placeholder values.
+ */
+
+/** Plural forms by `Intl.PluralRules` category; `other` is the fallback. */
+export interface PluralForms {
+ readonly zero?: string;
+ readonly one?: string;
+ readonly two?: string;
+ readonly few?: string;
+ readonly many?: string;
+ readonly other: string;
+}
+
+export type MessageSource = string | PluralForms;
+
+/** One string of the interface: its catalog key and its English source. */
+export interface Message<S extends MessageSource = MessageSource> {
+ readonly id: string;
+ readonly source: S;
+}
+
+/** A language's translations, by namespace and then by message name. */
+export type Catalog = Readonly<
+ Record<string, Readonly<Record<string, MessageSource>>>
+>;
+
+type SourceText<S extends MessageSource> = S extends string
+ ? S
+ : S[keyof S] & string;
+
+type PlaceholderNames<Text extends string> =
+ Text extends `${string}{${infer Name}}${infer Rest}`
+ ? Name | PlaceholderNames<Rest>
+ : never;
+
+type TagNames<Text extends string> =
+ Text extends `${string}<${infer Name}>${infer Rest}`
+ ? (Name extends `/${string}` ? never : Name) | TagNames<Rest>
+ : never;
+
+/** The `{name}` values a message needs; a plural message also needs `count`. */
+export type MessageValues<S extends MessageSource> = {
+ readonly [Name in PlaceholderNames<SourceText<S>>]: string | number;
+} & (S extends string ? unknown : { readonly count: number });
+
+/** The `<name>…</name>` spans of a message. */
+export type MessageTags<S extends MessageSource> = TagNames<SourceText<S>>;
+
+export type MessageArguments<S extends MessageSource> = [
+ keyof MessageValues<S>,
+] extends [never]
+ ? []
+ : [values: MessageValues<S>];
+
+/**
+ * Declares the English source of one namespace. Each feature keeps its own
+ * namespace beside its components, so English text ships in that feature's
+ * chunk and a key that does not exist fails the typecheck.
+ */
+export function defineMessages<
+ const Source extends Readonly<Record<string, MessageSource>>,
+>(
+ namespace: string,
+ source: Source,
+): { readonly [Name in keyof Source]: Message<Source[Name]> } {
+ return Object.fromEntries(
+ Object.entries(source).map(([name, text]) => [
+ name,
+ { id: `${namespace}.${name}`, source: text },
+ ]),
+ ) as { readonly [Name in keyof Source]: Message<Source[Name]> };
+}
+
+/** A piece of a formatted message: plain text, or the text inside a tag. */
+export interface MessagePart {
+ readonly tag?: string;
+ readonly text: string;
+}
+
+interface LanguageRules {
+ readonly numbers: Intl.NumberFormat;
+ readonly plurals: Intl.PluralRules;
+}
+
+const languageRules = new Map<string, LanguageRules>();
+
+function rulesFor(language: string) {
+ let rules = languageRules.get(language);
+ if (!rules) {
+ rules = {
+ numbers: new Intl.NumberFormat(language),
+ plurals: new Intl.PluralRules(language),
+ };
+ languageRules.set(language, rules);
+ }
+ return rules;
+}
+
+function resolve(
+ message: Message,
+ language: string,
+ catalog: Catalog | undefined,
+): { language: string; text: MessageSource } {
+ const separator = message.id.indexOf(".");
+ const translated =
+ catalog?.[message.id.slice(0, separator)]?.[
+ message.id.slice(separator + 1)
+ ];
+ // A string the catalog does not have yet shows its English source.
+ return translated === undefined
+ ? { language: "en", text: message.source }
+ : { language, text: translated };
+}
+
+interface ResolvedText {
+ readonly rules: LanguageRules;
+ readonly text: string;
+}
+
+function selectText(
+ message: Message,
+ language: string,
+ catalog: Catalog | undefined,
+ values: Readonly<Record<string, string | number>>,
+): ResolvedText {
+ const resolved = resolve(message, language, catalog);
+ const rules = rulesFor(resolved.language);
+ const text =
+ typeof resolved.text === "string"
+ ? resolved.text
+ : (resolved.text[rules.plurals.select(Number(values.count))] ??
+ resolved.text.other);
+ return { rules, text };
+}
+
+function interpolate(
+ { rules, text }: ResolvedText,
+ values: Readonly<Record<string, string | number>>,
+) {
+ return text.replace(/\{(\w+)\}/gu, (placeholder, name: string) => {
+ const value = values[name];
+ if (value === undefined) return placeholder;
+ return typeof value === "number" ? rules.numbers.format(value) : value;
+ });
+}
+
+/**
+ * The message in `language`, falling back to English, with the plural form
+ * `count` selects and every `{name}` replaced by its value. A number is
+ * written the way the language groups digits; pass a string to keep digits
+ * as they are, as for a year or an identifier.
+ */
+export function formatMessage(
+ message: Message,
+ language: string,
+ catalog: Catalog | undefined,
+ values: Readonly<Record<string, string | number>> = {},
+): string {
+ return interpolate(selectText(message, language, catalog, values), values);
+}
+
+/**
+ * The formatted message cut at its `<name>…</name>` spans, so a caller can
+ * wrap each span in an element. Tags do not nest. The spans come from the
+ * message alone: a value that happens to contain a tag stays plain text.
+ */
+export function formatMessageParts(
+ message: Message,
+ language: string,
+ catalog: Catalog | undefined,
+ values: Readonly<Record<string, string | number>> = {},
+): MessagePart[] {
+ const { rules, text } = selectText(message, language, catalog, values);
+ const parts: MessagePart[] = [];
+ const add = (part: string, tag?: string) => {
+ if (part)
+ parts.push({ tag, text: interpolate({ rules, text: part }, values) });
+ };
+ let end = 0;
+ for (const match of text.matchAll(/<(\w+)>(.*?)<\/\1>/gsu)) {
+ add(text.slice(end, match.index));
+ add(match[2]!, match[1]);
+ end = match.index + match[0].length;
+ }
+ add(text.slice(end));
+ return parts;
+}
diff --git a/apps/web/src/i18n/use-translation.test.tsx b/apps/web/src/i18n/use-translation.test.tsx
new file mode 100644
index 00000000..d7f5b1b8
--- /dev/null
+++ b/apps/web/src/i18n/use-translation.test.tsx
@@ -0,0 +1,24 @@
+import { act, render, screen } from "@testing-library/react";
+import { describe, expect, it } from "vitest";
+
+import { settingsMessages } from "@/features/settings/settings.messages";
+
+import { setLanguage } from "./language";
+import zhCN from "./locales/zh-CN.json";
+import { useT } from "./use-translation";
+
+function Title() {
+ const t = useT();
+ return <h1>{t(settingsMessages.title)}</h1>;
+}
+
+describe("translated components", () => {
+ it("render again in the new language when it changes", async () => {
+ render(<Title />);
+ expect(screen.getByRole("heading")).toHaveTextContent("Settings");
+ await act(() => setLanguage("zh-CN"));
+ expect(screen.getByRole("heading")).toHaveTextContent(zhCN.settings.title);
+ await act(() => setLanguage("en"));
+ expect(screen.getByRole("heading")).toHaveTextContent("Settings");
+ });
+});
diff --git a/apps/web/src/i18n/use-translation.tsx b/apps/web/src/i18n/use-translation.tsx
new file mode 100644
index 00000000..d7b04cda
--- /dev/null
+++ b/apps/web/src/i18n/use-translation.tsx
@@ -0,0 +1,58 @@
+import { Fragment, useSyncExternalStore, type ReactNode } from "react";
+
+import {
+ getTranslation,
+ subscribeToLanguage,
+ type Translation,
+} from "./language";
+import {
+ formatMessageParts,
+ type Message,
+ type MessageSource,
+ type MessageTags,
+ type MessageValues,
+} from "./messages";
+
+/** The language on screen; the component renders again when it changes. */
+export function useTranslation(): Translation {
+ return useSyncExternalStore(
+ subscribeToLanguage,
+ getTranslation,
+ getTranslation,
+ );
+}
+
+/** `t(message, values)` for the language on screen. */
+export function useT() {
+ return useTranslation().t;
+}
+
+type RichMessageProps<S extends MessageSource> = {
+ message: Message<S>;
+ /** Wraps the text of each `<name>…</name>` span of the message. */
+ tags: Readonly<Record<MessageTags<S>, (text: string) => ReactNode>>;
+} & ([keyof MessageValues<S>] extends [never]
+ ? { values?: undefined }
+ : { values: MessageValues<S> });
+
+/**
+ * A message with elements inside the sentence, such as a link or a product
+ * name in bold. The translation decides where each span sits.
+ */
+export function RichMessage<S extends MessageSource>({
+ message,
+ tags,
+ values,
+}: RichMessageProps<S>) {
+ const { catalog, language } = useTranslation();
+ const render: Readonly<
+ Record<string, ((text: string) => ReactNode) | undefined>
+ > = tags;
+ return formatMessageParts(message, language, catalog, values).map(
+ (part, index) => (
+ <Fragment key={index}>
+ {part.tag ? (render[part.tag]?.(part.text) ?? part.text) : part.text}
+ </Fragment>
+ ),
+ );
+}
diff --git a/apps/web/src/lib/date-format.ts b/apps/web/src/lib/date-format.ts
index 547b723e..fe6ffc40 100644
--- a/apps/web/src/lib/date-format.ts
+++ b/apps/web/src/lib/date-format.ts
@@ -1,9 +1,14 @@
export const APP_LOCALE = "en-US";
+/**
+ * Text that is translated passes the locale of the language on screen
+ * (`formatLocale()` of `@/i18n/language`); everything else stays in English.
+ */
export function dateTimeFormat(
options?: Intl.DateTimeFormatOptions,
+ locale: string = APP_LOCALE,
): Intl.DateTimeFormat {
- return new Intl.DateTimeFormat(APP_LOCALE, options);
+ return new Intl.DateTimeFormat(locale, options);
}
export function formatDateTime(
@@ -12,8 +17,9 @@ export function formatDateTime(
dateStyle: "medium",
timeStyle: "short",
},
+ locale?: string,
): string {
- return dateTimeFormat(options).format(new Date(value));
+ return dateTimeFormat(options, locale).format(new Date(value));
}
/** `YYYY-MM-DD` of the instant in the browser's time zone. Memory, Pocket Notes
diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx
index fec4737a..e4dc7059 100644
--- a/apps/web/src/main.tsx
+++ b/apps/web/src/main.tsx
@@ -20,6 +20,9 @@ import { DesktopConnectorReturn } from "@/features/apps/desktop-connector-return
import { createBrowserTeamHubRuntime } from "@/features/teamhub/browser-teamhub-runtime";
import { teamHubData } from "@/features/teamhub/teamhub-api";
import { TeamHubRuntimeProvider } from "@/features/teamhub/teamhub-runtime";
+import { commonMessages } from "@/i18n/common.messages";
+import { restoreLanguage } from "@/i18n/language";
+import { useT } from "@/i18n/use-translation";
installVitePreloadRecovery({ buildId: import.meta.url });
markDesktopShell();
@@ -32,37 +35,47 @@ if (!rootElement) {
}
const root = createRoot(rootElement);
-root.render(
- <StrictMode>
- <InitialAppLoading />
- </StrictMode>,
-);
-
-void startBrowserApp().catch(() => {
+// The remembered language is loaded before the first paint, so its reader
+// never sees the interface flash by in English. English loads nothing.
+void restoreLanguage().then(() => {
root.render(
<StrictMode>
- <main
- className="flex min-h-dvh items-center justify-center bg-app-canvas px-6 text-center text-app-ink"
- role="alert"
- >
- <div>
- <h1 className="text-lg">Web client unavailable</h1>
- <p className="mt-2 text-sm text-app-muted">
- The application could not finish loading.
- </p>
- <button
- className="mt-5 min-h-10 bg-app-action px-3 text-[14px] font-medium text-app-action-foreground hover:bg-app-action-hover [border-radius:var(--app-button-radius-large)]"
- onClick={() => globalThis.location.reload()}
- type="button"
- >
- Try again
- </button>
- </div>
- </main>
+ <InitialAppLoading />
</StrictMode>,
);
+ startBrowserApp().catch(() => {
+ root.render(
+ <StrictMode>
+ <AppUnavailable />
+ </StrictMode>,
+ );
+ });
});
+function AppUnavailable() {
+ const t = useT();
+ return (
+ <main
+ className="flex min-h-dvh items-center justify-center bg-app-canvas px-6 text-center text-app-ink"
+ role="alert"
+ >
+ <div>
+ <h1 className="text-lg">{t(commonMessages.unavailableTitle)}</h1>
+ <p className="mt-2 text-sm text-app-muted">
+ {t(commonMessages.unavailableBody)}
+ </p>
+ <button
+ className="mt-5 min-h-10 bg-app-action px-3 text-[14px] font-medium text-app-action-foreground hover:bg-app-action-hover [border-radius:var(--app-button-radius-large)]"
+ onClick={() => globalThis.location.reload()}
+ type="button"
+ >
+ {t(commonMessages.tryAgain)}
+ </button>
+ </div>
+ </main>
+ );
+}
+
async function startBrowserApp() {
const queryClient = createAppQueryClient();
const runtime = createBrowserTeamHubRuntime();
diff --git a/apps/web/src/test/setup.ts b/apps/web/src/test/setup.ts
index db7e3d0e..dcebccbe 100644
--- a/apps/web/src/test/setup.ts
+++ b/apps/web/src/test/setup.ts
@@ -2,6 +2,7 @@ import { focusManager, onlineManager } from "@tanstack/react-query";
import { afterEach, vi } from "vitest";
import { resetComposerAttachmentDraftsForTest } from "@/features/rooms/chat/composer-attachment-drafts";
+import { resetLanguageForTest } from "@/i18n/language";
import { setRoomDiagnosticsEnabledForTest } from "@/lib/room-diagnostics";
import { restoreGlobalProperties } from "@/test/global-properties";
import { assertNoUnhandledTestRoutes } from "@/test/teamhub-test-server";
@@ -185,6 +186,8 @@ afterEach(() => {
onlineManager.setOnline(true);
resetDocumentGlobals();
resetComposerAttachmentDraftsForTest();
+ // The language on screen is module state the files of a worker share.
+ resetLanguageForTest();
resetRoomTimelineReadingPositions?.();
// Timers first: a later assertion that throws must not leave a leaked fake
// timer on the window the next file shares.