Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

perf(desktop): load only the shown language, and give the window's rail its own page

milind-soni7dff420df16a
diff --git a/docs/verification/cloud-rail.md b/docs/verification/cloud-rail.md
index a64658f840..6e9d8daefb 100644
--- a/docs/verification/cloud-rail.md
+++ b/docs/verification/cloud-rail.md
@@ -9,12 +9,13 @@ rail, and the window looks as before.
The rail is the window's own chrome, not a page's: this app's page `/rail` in a
view of its own at the left edge (electron/chrome-rail.mjs), beside whichever
place's page the window shows, at every width and on every place, whatever that
-server runs. The page beside it moves over by the rail's width (the app's
-preload, at any zoom). The rail's sheets cover the window while open. Its
-circles are small and named on hover; the place on screen wears a ring. Beside
-the rail the sidebar's switcher and the profile menu's Switch to… step aside.
-The person can hide the rail; the page then has the whole window, and those two
-come back.
+server runs. `/rail` is a small page of its own (`rail.html`, `src/rail.tsx`):
+the rail, its sheets, the skin and the person's language, not the app. The
+page beside it moves over by the rail's width (the app's preload, at any zoom).
+The rail's sheets cover the window while open. Its circles are small and named
+on hover; the place on screen wears a ring. Beside the rail the sidebar's
+switcher and the profile menu's Switch to… step aside. The person can hide the
+rail; the page then has the whole window, and those two come back.
Nothing here needs a real MausBot Cloud account, a payment or the Electron app.
## Contract
diff --git a/rail.html b/rail.html
new file mode 100644
index 0000000000..20eef0b177
--- /dev/null
+++ b/rail.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>OpenMausBot</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/src/rail.tsx"></script>
+ </body>
+</html>
diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjs
index ea56ff2d10..8dfe548a7f 100644
--- a/scripts/ci-scope.mjs
+++ b/scripts/ci-scope.mjs
@@ -85,7 +85,7 @@ const AREAS = [
[/^(?:src|public)\/|^[^/]+-preview\.html$/, "web"],
[/^(?:server|shared|enterprise|companion|evals|skills|deploy|cloudflare\/composio-broker)\/|^(?:Dockerfile|\.dockerignore|compose\.yaml)$/, "server"],
[/^electron\/(?:cua|cua-failure|cua-connection|capabilities|screen-status|shared-cua-connection|shared-computer-access|lent-screen-tools|lent-screen-failures|paced-typing)\.[cm]js$/, "windows-computer-control"],
- [/^(?:electron|build)\/|^(?:electron-builder\.yml|index\.html)$/, "desktop"],
+ [/^(?:electron|build)\/|^(?:electron-builder\.yml|index\.html|rail\.html)$/, "desktop"],
[/^cloudflare\/control-plane\//, "control-plane"],
];
diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.ts
index 36d17c4419..59cfba1342 100644
--- a/scripts/ci-scope.test.ts
+++ b/scripts/ci-scope.test.ts
@@ -129,7 +129,7 @@ describe("CI path scope", () => {
expect(selectCiScope([file]).checks).toContain("windows-cua");
});
- it.each([["electron/main.mjs"], ["build/icon.icns"], ["electron-builder.yml"], ["index.html"]])("runs the server's checks for the desktop's %j", (file) => {
+ it.each([["electron/main.mjs"], ["build/icon.icns"], ["electron-builder.yml"], ["index.html"], ["rail.html"]])("runs the server's checks for the desktop's %j", (file) => {
expect(selectCiScope([file])).toEqual({ areas: ["desktop"], checks: checks("server") });
});
diff --git a/server/static-files.test.ts b/server/static-files.test.ts
new file mode 100644
index 0000000000..f35904c794
--- /dev/null
+++ b/server/static-files.test.ts
@@ -0,0 +1,38 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import type { ServerResponse } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, describe, expect, it } from "vitest";
+
+import { serveStatic } from "./static-files.ts";
+
+const dir = mkdtempSync(join(tmpdir(), "omb-static-"));
+writeFileSync(join(dir, "index.html"), "app");
+writeFileSync(join(dir, "rail.html"), "rail");
+mkdirSync(join(dir, "assets"));
+writeFileSync(join(dir, "assets", "rail-1a2b.js"), "js");
+afterAll(() => rmSync(dir, { recursive: true, force: true }));
+
+function get(path: string, staticDir: string = dir) {
+ const answer: { status?: number; headers: Record<string, string>; body?: string } = { headers: {} };
+ const res = {
+ writeHead(status: number, headers: Record<string, string>) { answer.status = status; answer.headers = headers; return res; },
+ end(data: Buffer) { answer.body = String(data); },
+ } as unknown as ServerResponse;
+ return { served: serveStatic(res, path, staticDir), ...answer };
+}
+
+describe("serveStatic", () => {
+ it("answers the window's rail with its own small page, never cached", () => {
+ const rail = get("/rail");
+ expect(rail.body).toBe("rail");
+ expect(rail.headers).toMatchObject({ "content-type": "text/html", "cache-control": "no-cache", "x-frame-options": "DENY" });
+ });
+
+ it("answers the app's paths with the app, and keeps hashed assets for good", () => {
+ expect(get("/").body).toBe("app");
+ expect(get("/settings").body).toBe("app");
+ expect(get("/rail/more").body).toBe("app");
+ expect(get("/assets/rail-1a2b.js").headers["cache-control"]).toBe("public, max-age=31536000, immutable");
+ });
+});
diff --git a/server/static-files.ts b/server/static-files.ts
index d3c5cde397..14df0cbd2a 100644
--- a/server/static-files.ts
+++ b/server/static-files.ts
@@ -19,10 +19,13 @@ const MIME: Record<string, string> = {
/** Never framed (a hidden frame could act on a pair or sign-in page unseen), and no Referer. */
const PAGE_HEADERS = { "content-security-policy": "frame-ancestors 'none'", "x-frame-options": "DENY", "referrer-policy": "no-referrer" } as const;
+/** Pages with an entry of their own: the app, and the desktop window's rail of places. */
+const PAGES: Record<string, string> = { "/": "/index.html", "/rail": "/rail.html" };
+
/** Public by design: the same bundle anyone can download, with no secrets, and /pair must load before a session exists. */
export function serveStatic(res: ServerResponse, path: string, staticDir: string | null): boolean {
if (!staticDir) return false;
- const safe = path === "/" ? "/index.html" : path.replace(/\.\./g, "");
+ const safe = PAGES[path] ?? path.replace(/\.\./g, "");
const file = join(staticDir, safe);
try {
const data = readFileSync(file);
diff --git a/src/App.tsx b/src/App.tsx
index f1699dffaf..f6ddd92f49 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -54,9 +54,9 @@ import { EmptyChatShell } from "@/components/onboarding/EmptyChatShell";
import { cloudFirstRun, cloudWelcomeVisible, useCloudWelcome } from "@/lib/cloud-welcome";
import { engineReady } from "@/components/EngineLibrary";
import { CommandPalette } from "@/components/CommandPalette";
-import { setLocale, t } from "@/lib/i18n";
+import { t } from "@/lib/i18n";
import { shouldOpenKeyboardShortcuts } from "@/lib/keyboard-shortcuts";
-import { effectiveLanguage, useLanguageChoice } from "@/lib/language-preference";
+import { effectiveLanguage, useLanguageChoice, usePageLanguage } from "@/lib/language-preference";
import { botUnreadCount, showBrowserUnread } from "@/lib/bot-unread";
import { phonePairingSettingsAction, takePhonePairingRequest } from "@/lib/phone-pairing"; import { takeConnectRequest } from "@/lib/connect-link";
import { useExternalChatLinks } from "@/hooks/use-external-chat-links";
@@ -130,12 +130,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
useExternalChatLinks(state, dispatch);
usePresence(state, dispatch);
const [drawerOpen, setDrawerOpen] = useState(false);
- const language = effectiveLanguage(useLanguageChoice(), state.config?.language);
- const [, setLocaleEpoch] = useState(0);
- useEffect(() => {
- setLocale(language || globalThis.navigator?.language);
- setLocaleEpoch((epoch) => epoch + 1);
- }, [language]);
+ usePageLanguage(effectiveLanguage(useLanguageChoice(), state.config?.language));
const [paletteOpen, setPaletteOpen] = useState(false);
const [localVmWorkspaceBotId, setLocalVmWorkspaceBotId] = useState<string | null>(null);
const menuButtonRef = useRef<HTMLButtonElement>(null);
diff --git a/src/cancel-plan-preview.tsx b/src/cancel-plan-preview.tsx
index 3c74de90c6..360af4c6b6 100644
--- a/src/cancel-plan-preview.tsx
+++ b/src/cancel-plan-preview.tsx
@@ -5,7 +5,7 @@ import { createRoot } from "react-dom/client";
import type { CloudAccountBridge, CloudAccountState, CloudPlanBridge, CloudPlanSnapshot, CloudRenewalResult } from "../electron/cloud-account.mjs";
import type { CloudRenewal } from "../electron/cloud-list.mjs";
import { CloudAccountSettings, CloudPlanOnCloud } from "@/components/CloudAccountSettings";
-import { setLocale } from "@/lib/i18n";
+import { loadLocale } from "@/lib/i18n";
import { SKIN_IDS, type SkinId } from "@/lib/skins";
import "./styles.css";
@@ -39,7 +39,6 @@ const plan = { state: async (): Promise<CloudPlanSnapshot> => ({ status: "paid",
function Preview() {
const skin = (SKIN_IDS as readonly string[]).includes(params.get("skin") ?? "") ? params.get("skin") as SkinId : "midnight";
document.documentElement.dataset.skin = skin;
- setLocale(params.get("lang") ?? "en");
const cloudPage = params.get("view") === "cloud";
return <div className="flex min-h-screen justify-center bg-app p-6 text-ink sm:p-10">
<div className="flex w-full max-w-[680px] flex-col gap-4">
@@ -50,4 +49,5 @@ function Preview() {
}
window.ogb = { ...window.ogb, cloudAccount: account } as typeof window.ogb;
+await loadLocale(params.get("lang") ?? "en");
createRoot(document.getElementById("root")!).render(<StrictMode><Preview /></StrictMode>);
diff --git a/src/cloud-buy-preview.tsx b/src/cloud-buy-preview.tsx
index 2cbcac71e0..36e630491e 100644
--- a/src/cloud-buy-preview.tsx
+++ b/src/cloud-buy-preview.tsx
@@ -12,7 +12,7 @@ import { CloudAddPanel, CloudAddSheet, type CloudAddActions, type CloudAddUi } f
import { WhatsNewPopup } from "@/components/whats-new/WhatsNewPopup";
import { ChooseScreen } from "@/components/cloud-buy/ChooseScreen";
import type { CloudAddView } from "@/lib/cloud-plan";
-import { setLocale } from "@/lib/i18n";
+import { loadLocale } from "@/lib/i18n";
import { SKIN_IDS, type SkinId } from "@/lib/skins";
import { whatsNewView } from "@/lib/whats-new";
import "./styles.css";
@@ -78,7 +78,6 @@ function Preview() {
const skin = (SKIN_IDS as readonly string[]).includes(params.get("skin") ?? "") ? params.get("skin") as SkinId : "midnight";
document.documentElement.dataset.skin = skin;
if (params.get("reduced") === "1") document.documentElement.dataset.reducedMotion = "true";
- setLocale(params.get("lang") ?? "en");
const state = params.get("state") ?? "choose";
const asked = POPUPS[state], popup = asked ? whatsNewView(asked.account, asked.offer) : null;
if (popup && typeof popup === "object") {
@@ -102,4 +101,5 @@ function Preview() {
</div>;
}
+await loadLocale(new URLSearchParams(location.search).get("lang") ?? "en");
createRoot(document.getElementById("root")!).render(<StrictMode><Preview /></StrictMode>);
diff --git a/src/components/ChromeRail.tsx b/src/components/ChromeRail.tsx
index 1eb463fd34..9374e87b76 100644
--- a/src/components/ChromeRail.tsx
+++ b/src/components/ChromeRail.tsx
@@ -1,6 +1,5 @@
-import { useEffect, useState } from "react";
-import { setLocale } from "@/lib/i18n";
-import { effectiveLanguage, useLanguageChoice } from "@/lib/language-preference";
+import { useEffect } from "react";
+import { effectiveLanguage, useLanguageChoice, usePageLanguage } from "@/lib/language-preference";
import { wearSkin } from "@/lib/skins";
import { DesktopCapabilitiesProvider } from "./DesktopCapabilities";
import { PlacesRail } from "./PlacesRail";
@@ -9,9 +8,7 @@ import { PlacesRail } from "./PlacesRail";
* beside whichever place's page the window shows, in the skin and language of the app. Its sheets cover the window
* while open (main widens the view for them). */
export function ChromeRail() {
- const language = effectiveLanguage(useLanguageChoice(), undefined);
- const [, setEpoch] = useState(0);
- useEffect(() => { setLocale(language || globalThis.navigator?.language); setEpoch((epoch) => epoch + 1); }, [language]);
+ usePageLanguage(effectiveLanguage(useLanguageChoice(), undefined));
// The page beside the rail chose its skin: the rail wears the same one.
useEffect(() => window.ogb?.rail?.onSkin?.(wearSkin), []);
return <DesktopCapabilitiesProvider><div data-chrome-rail className="h-full"><PlacesRail chrome /></div></DesktopCapabilitiesProvider>;
diff --git a/src/components/PlacesRail.tsx b/src/components/PlacesRail.tsx
index 36e3e52831..881710f7b3 100644
--- a/src/components/PlacesRail.tsx
+++ b/src/components/PlacesRail.tsx
@@ -12,7 +12,7 @@ import { track } from "@/lib/analytics";
import { cn } from "@/lib/cn";
import { cloudColor, cloudColorFill } from "@/lib/cloud-look";
import { activeLocale, t } from "@/lib/i18n";
-import { localizedRelativeTime } from "@/lib/memory";
+import { localizedRelativeTime } from "@/lib/relative-time";
import { useAdvancedMode } from "@/lib/interface-mode";
import { useBesideFramed } from "@/lib/chrome-rail";
import { makeHome, placeInitials, recolorPlace, removePlace, usePlaces, type RailPlace } from "@/lib/places";
diff --git a/src/components/bot-settings/MemorySection.tsx b/src/components/bot-settings/MemorySection.tsx
index 143cdc04df..8f05cba036 100644
--- a/src/components/bot-settings/MemorySection.tsx
+++ b/src/components/bot-settings/MemorySection.tsx
@@ -10,7 +10,6 @@ import {
fetchMemoryJournal,
fetchMemoryOverview,
formatBytes,
- localizedRelativeTime,
journalSource,
journalSourceKey,
fileLabel,
@@ -30,6 +29,7 @@ import {
type LendingReview,
markMemoryReviewed,
} from "@/lib/memory";
+import { localizedRelativeTime } from "@/lib/relative-time";
import { shortPath } from "@/lib/short-path";
import { activeLocale, t } from "@/lib/i18n";
import { roomMemoryCaptureEnabled } from "@/lib/feature-flags";
diff --git a/src/components/lazy-screens.test.ts b/src/components/lazy-screens.test.ts
index 6890b2ffd1..18dbd2d0e9 100644
--- a/src/components/lazy-screens.test.ts
+++ b/src/components/lazy-screens.test.ts
@@ -208,18 +208,19 @@ describe("launch bundle", () => {
: specifier.startsWith(".") ? join(dirname(from), specifier) : null;
if (!base) return null;
for (const candidate of [base, `${base}.tsx`, `${base}.ts`, join(base, "index.tsx"), join(base, "index.ts")]) {
- if (/\.tsx?$/.test(candidate) && existsSync(candidate)) return candidate;
+ if (/\.(tsx?|json)$/.test(candidate) && existsSync(candidate)) return candidate;
}
return null;
};
const staticImports = /(?:^|\n)\s*(?:import|export)\s+(?!type\s)(?:[^"'`;]*?\sfrom\s+)?["']([^"']+)["']/g;
- const launchModules = () => {
+ const launchModules = (entry = "main.tsx") => {
const seen = new Set<string>();
- const queue = [join(srcRoot, "main.tsx")];
+ const queue = [join(srcRoot, entry)];
while (queue.length) {
const file = queue.pop()!;
if (seen.has(file)) continue;
seen.add(file);
+ if (file.endsWith(".json")) continue;
for (const [, specifier] of readFileSync(file, "utf8").matchAll(staticImports)) {
const target = resolve(file, specifier!);
if (target) queue.push(target);
@@ -240,4 +241,16 @@ describe("launch bundle", () => {
].map((name) => `components/${name}.tsx`);
expect(deferred.filter((file) => reached.has(file))).toEqual([]);
});
+
+ it("carries English and no other language: the one a person chose loads before the first render", () => {
+ expect([...launchModules()].filter((file) => file.startsWith("locales/")).sort()).toEqual(["locales/en.json", "locales/index.ts"]);
+ });
+
+ it("gives the window's rail a page of its own that leaves the app out", () => {
+ const rail = launchModules("rail.tsx");
+ expect(rail.has("components/PlacesRail.tsx")).toBe(true);
+ expect(rail.has("components/PlaceAddSheet.tsx")).toBe(true);
+ expect(["App.tsx", "state/store.tsx", "components/Sidebar.tsx", "components/ChatView.tsx"].filter((file) => rail.has(file))).toEqual([]);
+ expect([...rail].filter((file) => file.startsWith("locales/")).sort()).toEqual(["locales/en.json", "locales/index.ts"]);
+ });
});
diff --git a/src/lib/i18n.test.ts b/src/lib/i18n.test.ts
index c5f878abd5..a0dd818f1d 100644
--- a/src/lib/i18n.test.ts
+++ b/src/lib/i18n.test.ts
@@ -169,6 +169,53 @@ describe("tFromServer", () => {
});
});
+describe("loading a language", () => {
+ afterEach(() => {
+ vi.doUnmock("@/locales");
+ vi.resetModules();
+ });
+
+ it("starts with English alone and shows another language only once its pack is here", async () => {
+ vi.resetModules();
+ const page = await import("./i18n");
+ const packs = await import("@/locales");
+ expect(Object.keys(packs.locales)).toEqual(["en"]);
+ expect(page.setLocale("de")).toBe("en");
+ expect(await page.loadLocale("de-AT")).toBe("de");
+ expect(page.t("engines.local")).toBe("Lokal");
+ expect(Object.keys(packs.locales)).toEqual(["en", "de"]);
+ expect(await page.loadLocale("pt")).toBe("pt");
+ expect(packs.locales["pt-br"]).toBe(packs.locales.pt);
+ expect(page.setLocale("de")).toBe("de");
+ });
+
+ it("shows the language asked for last, whichever pack arrives first", async () => {
+ vi.resetModules();
+ const page = await import("./i18n");
+ await Promise.all([page.loadLocale("ja"), page.loadLocale("fr"), page.loadLocale("de")]);
+ expect(page.activeLocale()).toBe("de");
+ const later = page.loadLocale("ko");
+ page.setLocale("en");
+ await later;
+ expect(page.activeLocale()).toBe("en");
+ });
+
+ it("falls back to English when a pack can't be loaded, and tries again next time", async () => {
+ vi.resetModules();
+ let offline = true;
+ vi.doMock("@/locales", async (original) => {
+ const real = await original<typeof import("@/locales")>();
+ return { ...real, loadLocalePack: (tag: string) => offline ? Promise.reject(new Error("offline")) : real.loadLocalePack(tag) };
+ });
+ const page = await import("./i18n");
+ expect(await page.loadLocale("fr")).toBe("en");
+ expect(page.t("rail.thisComputer")).toBe("This computer");
+ offline = false;
+ expect(await page.loadLocale("fr")).toBe("fr");
+ expect(page.t("rail.thisComputer")).toBe("Cet ordinateur");
+ });
+});
+
describe("page language", () => {
afterEach(() => {
setLocale("en");
@@ -205,13 +252,18 @@ describe("page language", () => {
expect(root.lang).toBe("en");
});
- it("tags the page from the system language the moment the module loads", async () => {
+ it("tags the page once the language's pack has loaded, keeping the one it shows until then", async () => {
const root = { lang: "en", dir: "" };
vi.stubGlobal("document", { documentElement: root });
- vi.stubGlobal("navigator", { language: "ja-JP" });
vi.resetModules();
- await import("./i18n");
+ const page = await import("./i18n");
+ await page.loadLocale("de");
+ const loading = page.loadLocale("ja-JP");
+ expect(root.lang).toBe("de");
+ expect(page.t("engines.local")).toBe("Lokal");
+ expect(await loading).toBe("ja");
expect(root).toEqual({ lang: "ja", dir: "ltr" });
+ expect(page.t("engines.local")).toBe(locales.ja!["engines.local"]);
});
it("still switches language where there is no page (tests, workers)", () => {
diff --git a/src/lib/i18n.ts b/src/lib/i18n.ts
index 8a14479082..3d764b86b6 100644
--- a/src/lib/i18n.ts
+++ b/src/lib/i18n.ts
@@ -1,5 +1,5 @@
import { productName } from "@/lib/brand";
-import { en, localeChoices, locales, type LocaleKey, type LocalePack } from "@/locales";
+import { en, loadLocalePack, localeChoices, localePacks, locales, type LocaleKey, type LocalePack } from "@/locales";
export function resolveLocale(tag: string | undefined, available: ReadonlySet<string>): string {
if (!tag) return "en";
@@ -15,8 +15,26 @@ export function resolveLocale(tag: string | undefined, available: ReadonlySet<st
const RTL_LANGUAGES = new Set(["ar", "fa", "he", "ur"]);
+/** Every tag a pack is shown for, loaded or not. */
+export function knownLocales(): Set<string> {
+ return new Set([...Object.keys(localePacks), ...Object.keys(locales)]);
+}
+
+/** Shows `tag`'s language when its pack is loaded (loadLocale), English otherwise; returns the locale that took effect. */
export function setLocale(tag: string | undefined): string {
- const resolved = resolveLocale(tag, new Set(Object.keys(locales)));
+ switches += 1;
+ return show(resolveLocale(tag, new Set(Object.keys(locales))));
+}
+
+/** Loads `tag`'s pack and shows it, unless another language was asked for meanwhile; until then the page keeps the
+ * language it shows. Resolves to the locale shown. */
+export async function loadLocale(tag: string | undefined): Promise<string> {
+ const asked = ++switches;
+ await loadLocalePack(resolveLocale(tag, knownLocales())).catch(() => undefined);
+ return asked === switches ? show(resolveLocale(tag, new Set(Object.keys(locales)))) : active;
+}
+
+function show(resolved: string): string {
activePack = locales[resolved] ?? en;
active = resolved;
// Screen readers choose pronunciation from <html lang>, and index.html ships "en".
@@ -29,8 +47,8 @@ export function setLocale(tag: string | undefined): string {
}
export function documentLanguage(code: string): string {
- const pack = locales[code];
- const shown = localeChoices.find((choice) => locales[choice.code] === pack)?.code ?? code;
+ const pack = localePacks[code];
+ const shown = (pack && localeChoices.find((choice) => localePacks[choice.code] === pack)?.code) || code;
return shown
.split("-")
.map((part, index) =>
@@ -48,7 +66,7 @@ export function activeLocale(): string {
let active = "en";
let activePack: LocalePack = en;
-setLocale(globalThis.navigator?.language);
+let switches = 0;
export function tFromServer(key: string | undefined, fallback: string | undefined): string | undefined {
return key && Object.hasOwn(en, key) ? t(key as LocaleKey) : fallback;
diff --git a/src/lib/language-preference.ts b/src/lib/language-preference.ts
index 344920e24e..0abb28e377 100644
--- a/src/lib/language-preference.ts
+++ b/src/lib/language-preference.ts
@@ -1,4 +1,5 @@
-import { useSyncExternalStore } from "react";
+import { useEffect, useState, useSyncExternalStore } from "react";
+import { loadLocale } from "@/lib/i18n";
export const LANGUAGE_KEY = "omb-language";
@@ -99,3 +100,16 @@ export function setLanguageChoice(language: string): void {
export function useLanguageChoice(): string | null {
return useSyncExternalStore(subscribe, languageChoice, () => null);
}
+
+/** The person's own language, loaded before a page first draws, so they never see another one first. */
+export function loadPageLanguage(): Promise<string> {
+ return loadLocale(effectiveLanguage(languageChoice(), undefined) || globalThis.navigator?.language);
+}
+
+/** Shows `language` (the system's when empty) once its pack has loaded, and draws the caller again then. */
+export function usePageLanguage(language: string): void {
+ const [, setShown] = useState(0);
+ useEffect(() => {
+ void loadLocale(language || globalThis.navigator?.language).then(() => setShown((shown) => shown + 1));
+ }, [language]);
+}
diff --git a/src/lib/memory.ts b/src/lib/memory.ts
index 947559f5e1..62de660d76 100644
--- a/src/lib/memory.ts
+++ b/src/lib/memory.ts
@@ -181,19 +181,6 @@ export function relativeTime(at: number, now = Date.now()): string {
return new Date(at).toLocaleDateString([], { month: "short", day: "numeric" });
}
-export function localizedRelativeTime(at: number, locale: string, now = Date.now()): string {
- const seconds = Math.max(0, Math.round((now - at) / 1000));
- const formatter = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
- if (seconds < 45) return formatter.format(0, "second");
- const minutes = Math.round(seconds / 60);
- if (minutes < 60) return formatter.format(-minutes, "minute");
- const hours = Math.round(minutes / 60);
- if (hours < 24) return formatter.format(-hours, "hour");
- const days = Math.round(hours / 24);
- if (days < 7) return formatter.format(-days, "day");
- return new Date(at).toLocaleDateString(locale, { month: "short", day: "numeric" });
-}
-
export type CapacityLevel = "ok" | "near" | "over";
export interface CapacityStatus {
diff --git a/src/lib/presence-client.ts b/src/lib/presence-client.ts
index c6dd73b20a..1d692ce1c4 100644
--- a/src/lib/presence-client.ts
+++ b/src/lib/presence-client.ts
@@ -1,12 +1,11 @@
-import { resolveLocale } from "@/lib/i18n";
+import { knownLocales, resolveLocale } from "@/lib/i18n";
import { effectiveLanguage, languageChoice } from "@/lib/language-preference";
-import { locales } from "@/locales";
export const PRESENCE_MIN_INTERVAL_MS = 60_000;
/** The pack the app shows, worked out as App does rather than read from i18n, which a first ping can reach before App applies it. */
export function shownLanguage(serverDefault: string | undefined, choice: string | null = languageChoice()): string {
- return resolveLocale(effectiveLanguage(choice, serverDefault) || globalThis.navigator?.language, new Set(Object.keys(locales)));
+ return resolveLocale(effectiveLanguage(choice, serverDefault) || globalThis.navigator?.language, knownLocales());
}
/** The language lets the brief the server writes match the app; the open chat lets the server get it ready to answer. */
diff --git a/src/lib/relative-time.ts b/src/lib/relative-time.ts
new file mode 100644
index 0000000000..f7ddd001fa
--- /dev/null
+++ b/src/lib/relative-time.ts
@@ -0,0 +1,12 @@
+export function localizedRelativeTime(at: number, locale: string, now = Date.now()): string {
+ const seconds = Math.max(0, Math.round((now - at) / 1000));
+ const formatter = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
+ if (seconds < 45) return formatter.format(0, "second");
+ const minutes = Math.round(seconds / 60);
+ if (minutes < 60) return formatter.format(-minutes, "minute");
+ const hours = Math.round(minutes / 60);
+ if (hours < 24) return formatter.format(-hours, "hour");
+ const days = Math.round(hours / 24);
+ if (days < 7) return formatter.format(-days, "day");
+ return new Date(at).toLocaleDateString(locale, { month: "short", day: "numeric" });
+}
diff --git a/src/lib/send-key.test.ts b/src/lib/send-key.test.ts
index e86d9447a2..29dab518a6 100644
--- a/src/lib/send-key.test.ts
+++ b/src/lib/send-key.test.ts
@@ -128,7 +128,7 @@ describe("the local send key choice", () => {
expect(preference.defaultSendKey("ja-jp")).toBe("mod-enter");
for (const locale of ["en", "zh", "ko", "jam"]) expect(preference.defaultSendKey(locale)).toBe("enter");
try {
- i18n.setLocale("ja-JP");
+ await i18n.loadLocale("ja-JP");
expect(preference.useSendKey()).toBe("mod-enter");
expect(hook.serverSnapshot!()).toBe("mod-enter");
expect(preference.parseSendKey("bogus")).toBe("mod-enter");
diff --git a/src/locales/index.ts b/src/locales/index.ts
index a948519447..948ac67945 100644
--- a/src/locales/index.ts
+++ b/src/locales/index.ts
@@ -1,47 +1,64 @@
import en from "./en.json";
-import de from "./de.json";
-import es from "./es.json";
-import fr from "./fr.json";
-import hi from "./hi.json";
-import ja from "./ja.json";
-import ptBr from "./pt-br.json";
-import zh from "./zh.json";
-import zhTw from "./zh-tw.json";
-import uk from "./uk.json";
-import vi from "./vi.json";
-import tr from "./tr.json";
-import pl from "./pl.json";
-import ru from "./ru.json";
-import it from "./it.json";
-import ko from "./ko.json";
export { en };
export type LocaleKey = keyof typeof en;
export type LocalePack = Partial<Record<LocaleKey, string>>;
-export const locales: Record<string, LocalePack> = {
- en,
- de,
- es,
- fr,
- hi,
- ja,
- pt: ptBr,
- "pt-br": ptBr,
- zh,
- "zh-hant": zhTw,
- "zh-hk": zhTw,
- "zh-mo": zhTw,
- "zh-tw": zhTw,
- uk,
- vi,
- tr,
- pl,
- ru,
- it,
- ko,
+const packLoaders = {
+ de: () => import("./de.json"),
+ es: () => import("./es.json"),
+ fr: () => import("./fr.json"),
+ hi: () => import("./hi.json"),
+ ja: () => import("./ja.json"),
+ "pt-br": () => import("./pt-br.json"),
+ zh: () => import("./zh.json"),
+ "zh-tw": () => import("./zh-tw.json"),
+ uk: () => import("./uk.json"),
+ vi: () => import("./vi.json"),
+ tr: () => import("./tr.json"),
+ pl: () => import("./pl.json"),
+ ru: () => import("./ru.json"),
+ it: () => import("./it.json"),
+ ko: () => import("./ko.json"),
+} satisfies Record<string, () => Promise<{ default: LocalePack }>>;
+
+export type PackName = "en" | keyof typeof packLoaders;
+
+/** Every language tag the app answers to, and the pack it shows. */
+export const localePacks: Readonly<Record<string, PackName>> = {
+ en: "en",
+ de: "de",
+ es: "es",
+ fr: "fr",
+ hi: "hi",
+ ja: "ja",
+ pt: "pt-br",
+ "pt-br": "pt-br",
+ zh: "zh",
+ "zh-hant": "zh-tw",
+ "zh-hk": "zh-tw",
+ "zh-mo": "zh-tw",
+ "zh-tw": "zh-tw",
+ uk: "uk",
+ vi: "vi",
+ tr: "tr",
+ pl: "pl",
+ ru: "ru",
+ it: "it",
+ ko: "ko",
};
+/** The packs this page has loaded, under every tag that shows them: English, and each one loadLocalePack fetched. */
+export const locales: Record<string, LocalePack> = { en };
+
+export async function loadLocalePack(tag: string): Promise<LocalePack | undefined> {
+ const name = localePacks[tag];
+ if (locales[tag] || !name || name === "en") return locales[tag];
+ const pack: LocalePack = (await packLoaders[name]()).default;
+ for (const [alias, shown] of Object.entries(localePacks)) if (shown === name) locales[alias] ??= pack;
+ return pack;
+}
+
export const localeChoices: ReadonlyArray<{ code: string; label: string }> = [
{ code: "en", label: "English" },
{ code: "de", label: "Deutsch" },
diff --git a/src/main.tsx b/src/main.tsx
index 2621c72859..d2621c27d8 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -5,6 +5,7 @@ import {
BROWSER_SIGN_IN_FAILED, previewBrowserSignIn, readSessionState, SERVICE_TRUST_REASON, takeBrowserSignInFromLocation, takePairingCodeFromLocation, takeInvitedEmailFromLocation,
} from "./lib/session";
import { bootstrapBrand } from "./lib/brand";
+import { loadPageLanguage } from "./lib/language-preference";
import { applySkinChoice, readSkinChoice } from "./lib/skins";
import { applyChatWidth, readChatWidth } from "./lib/chat-width";
import { applyFont, readFont } from "./lib/fonts";
@@ -24,12 +25,6 @@ applyChatWidth(readChatWidth());
async function chooseRoot(): Promise<React.ReactNode> {
const home = window.ogb?.home;
if (location.pathname === "/home" && home) return <HomeScreen bridge={home} manage={window.ogb?.cloudPlan?.manage} />;
- // The window's own rail of places (electron/chrome-rail.mjs): see-through but for the rail and its open sheets.
- if (location.pathname === "/rail" && window.ogb?.rail?.expand) {
- document.documentElement.style.background = document.body.style.background = "transparent";
- const { ChromeRail } = await import("./components/ChromeRail");
- return <ChromeRail />;
- }
if (location.pathname === "/pair") {
const signIn = takeBrowserSignInFromLocation();
if (signIn) {
@@ -52,6 +47,6 @@ async function chooseRoot(): Promise<React.ReactNode> {
return <App />;
}
-void Promise.all([bootstrapBrand(), chooseRoot()]).then(([, root]) => {
+void Promise.all([bootstrapBrand(), chooseRoot(), loadPageLanguage()]).then(([, root]) => {
createRoot(document.getElementById("root")!).render(<StrictMode>{root}</StrictMode>);
});
diff --git a/src/one-home-preview.tsx b/src/one-home-preview.tsx
index 9132df5790..756fc1e82c 100644
--- a/src/one-home-preview.tsx
+++ b/src/one-home-preview.tsx
@@ -8,7 +8,7 @@ import type { RailState } from "../electron/cloud-rail.mjs";
import { PlacesRail } from "@/components/PlacesRail";
import { SidebarFooter } from "@/components/SidebarFooter";
import { TwoPlacesCard } from "@/components/TwoPlacesCard";
-import { setLocale } from "@/lib/i18n";
+import { loadLocale } from "@/lib/i18n";
import { applySkinChoice, SKIN_IDS, type SkinId } from "@/lib/skins";
import { initialState, StoreContext, type AppState } from "@/state/store";
import "./styles.css";
@@ -17,7 +17,7 @@ const params = new URLSearchParams(location.search);
const stateName = params.get("state") ?? "menu";
const skin = params.get("skin") ?? "midnight";
applySkinChoice(SKIN_IDS.includes(skin as SkinId) ? (skin as SkinId) : "midnight");
-setLocale(params.get("lang") ?? "en");
+await loadLocale(params.get("lang") ?? "en");
const rail: RailState = { places: [
{ id: "local", name: "This computer", color: null, kind: "computer", opens: true, active: true, paint: { swatch: null } },
diff --git a/src/question-cards-preview.tsx b/src/question-cards-preview.tsx
index c731dd5a47..619fd0b28d 100644
--- a/src/question-cards-preview.tsx
+++ b/src/question-cards-preview.tsx
@@ -6,7 +6,7 @@ import { createRoot } from "react-dom/client";
import type { InboxRow, InboxView } from "../shared/inbox";
import { ChatView } from "@/components/ChatView";
import { InboxPanel } from "@/components/inbox/InboxPanel";
-import { setLocale } from "@/lib/i18n";
+import { loadLocale } from "@/lib/i18n";
import { setAdvancedMode } from "@/lib/interface-mode";
import { applySkinChoice, SKIN_IDS, type SkinId } from "@/lib/skins";
import { openInbox, setInboxView } from "@/state/inbox";
@@ -20,7 +20,7 @@ const surface = params.get("surface") ?? "chat";
const skin = params.get("skin") ?? "midnight";
setAdvancedMode(params.get("mode") === "advanced");
applySkinChoice(SKIN_IDS.includes(skin as SkinId) ? (skin as SkinId) : "midnight");
-setLocale(params.get("lang") ?? "en");
+await loadLocale(params.get("lang") ?? "en");
const AT = Date.now() - 12 * 60_000;
const CLEO = { email: "[email protected]", name: "Cleo", role: "owner" };
diff --git a/src/rail.tsx b/src/rail.tsx
new file mode 100644
index 0000000000..d655eab622
--- /dev/null
+++ b/src/rail.tsx
@@ -0,0 +1,23 @@
+import { StrictMode } from "react";
+import { createRoot } from "react-dom/client";
+import { ChromeRail } from "./components/ChromeRail";
+import { bootstrapBrand } from "./lib/brand";
+import { applyFont, readFont } from "./lib/fonts";
+import { settleAdvancedModeDefault } from "./lib/interface-mode";
+import { loadPageLanguage } from "./lib/language-preference";
+import { applySkinChoice, readSkinChoice } from "./lib/skins";
+import "./styles.css";
+
+// The window's own rail of places (electron/chrome-rail.mjs): see-through but for the rail and its open sheets. Only
+// the desktop's preload gives this app's page a rail; anywhere else this address is the app.
+if (window.ogb?.rail?.expand) {
+ settleAdvancedModeDefault();
+ applySkinChoice(readSkinChoice());
+ applyFont(readFont());
+ document.documentElement.style.background = document.body.style.background = "transparent";
+ void Promise.all([bootstrapBrand(), loadPageLanguage()]).then(() => {
+ createRoot(document.getElementById("root")!).render(<StrictMode><ChromeRail /></StrictMode>);
+ });
+} else {
+ location.replace(`/${location.search}${location.hash}`);
+}
diff --git a/src/room-card-preview.tsx b/src/room-card-preview.tsx
index 3ef214b116..877146e0a3 100644
--- a/src/room-card-preview.tsx
+++ b/src/room-card-preview.tsx
@@ -8,7 +8,7 @@ import { InitialsAvatar } from "@/components/Avatar";
import { ConfirmDialogCard } from "@/components/ConfirmDialog";
import { CloudRoomCardView } from "@/components/CloudRoomCard";
import { cloudPlanLabel } from "@/lib/cloud-plan";
-import { setLocale, t } from "@/lib/i18n";
+import { loadLocale, t } from "@/lib/i18n";
import { roomCardView } from "@/lib/room-card";
import { SKIN_IDS, type SkinId } from "@/lib/skins";
import { upgradeConfirmBody } from "@/lib/usage-meter";
@@ -89,11 +89,11 @@ function Preview() {
const params = new URLSearchParams(location.search);
const skin = (SKIN_IDS as readonly string[]).includes(params.get("skin") ?? "") ? params.get("skin") as SkinId : "midnight";
document.documentElement.dataset.skin = skin;
- setLocale(params.get("lang") ?? "en");
const state = params.get("state") ?? "memory", layout = params.get("layout") ?? "desktop";
return <div className="h-screen overflow-hidden">
{state === "confirm" ? <Confirm layout={layout} /> : layout === "phone" ? <Phone state={state} /> : <Desktop state={state} />}
</div>;
}
+await loadLocale(new URLSearchParams(location.search).get("lang") ?? "en");
createRoot(document.getElementById("root")!).render(<StrictMode><Preview /></StrictMode>);
diff --git a/src/testing/all-locales.ts b/src/testing/all-locales.ts
new file mode 100644
index 0000000000..a45433ad98
--- /dev/null
+++ b/src/testing/all-locales.ts
@@ -0,0 +1,18 @@
+// The app loads a language's pack before it shows it (loadLocale); tests switch languages synchronously, so every
+// pack is here, read the first time a test asks for it.
+import { readFileSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { localePacks, locales, type LocalePack } from "../locales/index.ts";
+
+const folder = join(dirname(fileURLToPath(import.meta.url)), "..", "locales");
+const read = new Map<string, LocalePack>();
+const pack = (name: string): LocalePack => {
+ let found = read.get(name);
+ if (!found) read.set(name, found = JSON.parse(readFileSync(join(folder, `${name}.json`), "utf8")) as LocalePack);
+ return found;
+};
+for (const [tag, name] of Object.entries(localePacks)) {
+ if (!(tag in locales)) Object.defineProperty(locales, tag, { configurable: true, enumerable: true, get: () => pack(name) });
+}
diff --git a/src/usage-meter-preview.tsx b/src/usage-meter-preview.tsx
index 4a8f4e28e0..ba53b16d4a 100644
--- a/src/usage-meter-preview.tsx
+++ b/src/usage-meter-preview.tsx
@@ -9,7 +9,7 @@ import { ConfirmDialogCard } from "@/components/ConfirmDialog";
import { CloudUsageCardView, CloudUsageSettingsView } from "@/components/CloudUsageMeter";
import { Card } from "@/components/SettingsPrimitives";
import { cloudPlanLabel } from "@/lib/cloud-plan";
-import { setLocale, t } from "@/lib/i18n";
+import { loadLocale, t } from "@/lib/i18n";
import { SKIN_IDS, type SkinId } from "@/lib/skins";
import { upgradeConfirmBody, usageCardView } from "@/lib/usage-meter";
import "./styles.css";
@@ -90,7 +90,6 @@ function Preview() {
const params = new URLSearchParams(location.search);
const skin = (SKIN_IDS as readonly string[]).includes(params.get("skin") ?? "") ? params.get("skin") as SkinId : "midnight";
document.documentElement.dataset.skin = skin;
- setLocale(params.get("lang") ?? "en");
const usage = USAGE[params.get("state") ?? "near"] ?? USAGE.near!;
const view = params.get("view") ?? "sidebar";
return <div className="h-screen overflow-hidden">
@@ -98,4 +97,5 @@ function Preview() {
</div>;
}
+await loadLocale(new URLSearchParams(location.search).get("lang") ?? "en");
createRoot(document.getElementById("root")!).render(<StrictMode><Preview /></StrictMode>);
diff --git a/vite.config.ts b/vite.config.ts
index d1b4d2da3a..fcf2f6ce78 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -1,5 +1,6 @@
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
+import type { Connect, Plugin } from "vite";
import { configDefaults, defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
import tailwindcss from "@tailwindcss/vite";
@@ -14,6 +15,21 @@ const { version } = JSON.parse(
) as { version: string };
const root = fileURLToPath(new URL(".", import.meta.url));
+const page = (file: string) => fileURLToPath(new URL(file, import.meta.url));
+
+/** The window's rail of places loads /rail: rail.html, its own small page, in development as from the server. */
+function railPage(): Plugin {
+ const rewrite: Connect.NextHandleFunction = (req, _res, next) => {
+ if (req.url === "/rail" || req.url?.startsWith("/rail?")) req.url = `/rail.html${req.url.slice("/rail".length)}`;
+ next();
+ };
+ return {
+ name: "rail-page",
+ configureServer: (server) => void server.middlewares.use(rewrite),
+ configurePreviewServer: (server) => void server.middlewares.use(rewrite),
+ };
+}
+
const include = [
"evals/**/*.test.ts",
"server/**/*.test.ts",
@@ -28,7 +44,10 @@ const include = [
];
export default defineConfig({
- plugins: [react(), tailwindcss()],
+ plugins: [react(), tailwindcss(), railPage()],
+ build: {
+ rollupOptions: { input: { index: page("./index.html"), rail: page("./rail.html") } },
+ },
define: {
__APP_VERSION__: JSON.stringify(version),
},
@@ -37,7 +56,7 @@ export default defineConfig({
include,
// OMB_VITEST_E2E=host (CI's Windows and macOS shards) leaves the e2e files that run on Linux only.
exclude: [...configDefaults.exclude, ...(hostE2eOnly() ? portableE2eFiles(root, include) : [])],
- setupFiles: ["server/testing/setup.ts"],
+ setupFiles: ["server/testing/setup.ts", "src/testing/all-locales.ts"],
// the suite spawns fake provider CLIs and a real harness server;
// parallel files introduce load-sensitive flakes for no win
fileParallelism: false,