Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Menus, tray and dialogs read in the language the window shows
milind-soni33805179297c
diff --git a/electron/desktop-prefs.d.mts b/electron/desktop-prefs.d.mtsindex dd830dd472..7d7bbd63a8 100644--- a/electron/desktop-prefs.d.mts+++ b/electron/desktop-prefs.d.mts@@ -27,6 +27,8 @@ export interface DesktopLanguageBridge {set(language: string): Promise<boolean>;/** A pick made on another page of this desktop. */onChange(listener: (language: string) => void): () => void;+ /** The language this page shows, so menus, tray and dialogs never read in another one beside it. Older desktop apps lack it. */+ shown?(language: string): void;}export interface DesktopPrefs {seen(): string[];@@ -93,6 +95,8 @@ export declare function registerDesktopPrefs(options: {languageChanged?(language: string, sender: unknown): void;/** The pick changed: main redraws its own words in it ("" for the system's). */onLanguage?(language: string): void;+ /** A page of the window shows `language`: with nothing picked, main draws its own words in that one too. */+ onShown?(language: string, sender: unknown): void;/** The window's frame: `made()`, the frame the window was made with (null before it is); `restarts`, a change waits for* the app to start again; `changed()`, the pages hear it. */frame?: { made(): boolean | null; restarts: boolean; changed(): void } | null;diff --git a/electron/desktop-prefs.mjs b/electron/desktop-prefs.mjsindex db6e8105ac..c4ed7ad5d3 100644--- a/electron/desktop-prefs.mjs+++ b/electron/desktop-prefs.mjs@@ -151,9 +151,10 @@ export function createDesktopPrefs({ read, write }) {* another saved server open in this desktop's window, null for anything else. `cloudOffered()`: this desktop sells* MausBot Cloud, asked once its Cloud sign-in is restored. `localConfig()`: This computer's own workspace's config.json.* `languageChanged(language, sender)`: tells this desktop's other pages the language picked on one of them;- * `onLanguage(language)`: tells main, which draws its menus, tray and dialogs in it. `prefs`: the record main reads too.+ * `onLanguage(language)`: tells main, which draws its menus, tray and dialogs in it. `onShown(language, sender)`: the+ * language a page of the window shows, which main's words follow while nothing is picked. `prefs`: the record main reads too.*/-export function registerDesktopPrefs({ prefs: given, ipcMain, read, write, page, cloudOffered, cloudAccount, localConfig = () => null, languageChanged = () => {}, onLanguage = () => {}, frame = null, now = Date.now, systemName = accountFullName }) {+export function registerDesktopPrefs({ prefs: given, ipcMain, read, write, page, cloudOffered, cloudAccount, localConfig = () => null, languageChanged = () => {}, onLanguage = () => {}, onShown = () => {}, frame = null, now = Date.now, systemName = accountFullName }) {let prefs = given ?? null;const store = () => prefs ??= createDesktopPrefs({ read, write });const from = (channel, pages, handler) => (event, ...args) => {@@ -196,6 +197,9 @@ export function registerDesktopPrefs({ prefs: given, ipcMain, read, write, page,}return store().language() === language;});+ ipcMain.on("desktop-language:shown", (event, language) => {+ try { if (page(event) && isLanguage(language) && language) onShown(language, event.sender); } catch {}+ });// Every page of this desktop's window reads and sets the frame; a server's page sets it only from the person's click,// which the preload checks.const frameState = () => ({ on: store().windowFrame(), restart: Boolean(frame?.restarts) && frame.made() !== null && frame.made() !== store().windowFrame() });diff --git a/electron/desktop-prefs.node-test.mjs b/electron/desktop-prefs.node-test.mjsindex b1a9c6a4b8..66eead74b5 100644--- a/electron/desktop-prefs.node-test.mjs+++ b/electron/desktop-prefs.node-test.mjs@@ -211,19 +211,34 @@ test("main hears each new pick once, from any page of the window, to draw its meassert.deepEqual(main.told.map(([language]) => language), main.languages);});+test("a page of the window says which language it shows, and main hears it only from this desktop's window", () => {+ const shown = [];+ const listeners = new Map();+ registerDesktopPrefs({ ipcMain: { handle: () => {}, on: (channel, listener) => listeners.set(channel, listener) }, read: () => null, write: () => {},+ page: event => event.page, cloudOffered: async () => true, onShown: (language, sender) => shown.push([language, sender]) });+ const say = (page, language) => listeners.get("desktop-language:shown")({ page, sender: `${page}-page` }, language);+ say("server", "pt-br"); say("local", "en"); say(null, "de");+ for (const bad of ["", "../../etc", "x".repeat(40), 42, null, { toString: () => "en" }]) say("local", bad);+ assert.deepEqual(shown, [["pt-br", "server-page"], ["en", "local-page"]]);+ const broken = new Map();+ registerDesktopPrefs({ ipcMain: { handle: () => {}, on: (channel, listener) => broken.set(channel, listener) }, read: () => null, write: () => {},+ page: () => { throw new Error("Object has been destroyed"); }, cloudOffered: async () => true, onShown: () => { throw new Error("never"); } });+ assert.doesNotThrow(() => broken.get("desktop-language:shown")({}, "en"));+});+const PRELOAD = readFileSync(new URL("./preload.cjs", import.meta.url), "utf8").replace(/\r\n/g, "\n");function preload(origin, { activation = false, saved = null, language = null } = {}) {let bridge;- const invoked = [], synced = [], heard = new Map();+ const invoked = [], synced = [], sent = [], heard = new Map();vm.runInNewContext(PRELOAD, {process: { platform: "darwin", argv: [`--omb-local-origin=${LOCAL}`, "--omb-company-desktop=1"] },location: { origin }, navigator: { userActivation: { isActive: activation } }, TextEncoder, localStorage: { getItem: () => null },require: () => ({ webUtils: {}, contextBridge: { exposeInMainWorld: (_name, value) => { bridge = value; } },- ipcRenderer: { on(channel, handler) { heard.set(channel, handler); }, removeListener() {}, send() {},+ ipcRenderer: { on(channel, handler) { heard.set(channel, handler); }, removeListener() {}, send(...args) { sent.push(args); },sendSync: channel => { synced.push(channel); return channel === "desktop-analytics:read" ? saved : channel === "desktop-language:read" ? language : undefined; },invoke: (...args) => { invoked.push(args); return Promise.resolve(true); } } }),});- return { bridge, invoked, synced, tell: (channel, ...args) => heard.get(channel)({}, ...args) };+ return { bridge, invoked, synced, sent, tell: (channel, ...args) => heard.get(channel)({}, ...args) };}test("the preload gives every page of the window the notices and the switch's state, and only This computer's page a way to set it", async () => {@@ -260,7 +275,7 @@ test("the preload gives every page of the window the notices and the switch's sttest("the preload gives every page of the window the app language this computer keeps", async () => {for (const origin of [LOCAL, CLOUD, VPS]) {const page = preload(origin, { language: "de" });- assert.deepEqual(Object.keys(page.bridge.desktopLanguage), ["choice", "set", "onChange"], origin);+ assert.deepEqual(Object.keys(page.bridge.desktopLanguage), ["choice", "set", "onChange", "shown"], origin);const asked = () => page.synced.filter(channel => channel.startsWith("desktop-"));assert.deepEqual(asked(), [], "nothing is asked until the language is");assert.equal(page.bridge.desktopLanguage.choice(), "de", origin);@@ -279,6 +294,9 @@ test("the preload gives every page of the window the app language this computerpage.tell("desktop-language:changed", "fr");assert.deepEqual(heard, ["ja"]);assert.equal(page.bridge.desktopLanguage.choice(), "fr");+ page.bridge.desktopLanguage.shown("pt-br");+ assert.deepEqual(page.sent.filter(([channel]) => channel.startsWith("desktop-language")), [["desktop-language:shown", "pt-br"]], "the language it shows, for main's own words");+ assert.equal(page.bridge.desktopLanguage.choice(), "fr", "showing a language is not a pick");}assert.equal(preload(VPS, { language: 7 }).bridge.desktopLanguage.choice(), null);const safe = PRELOAD.match(/const REMOTE_SAFE = new Set\(\[([^\]]*)\]\)/)[1];@@ -301,7 +319,7 @@ test("production wiring: main answers this computer's page, My Cloud's own pagelet switched = async id => { calls.push(["switch", id]); }, loads = true, broadcasts = 0;const context = vm.createContext({registerDesktopPrefs: value => { options = value; }, jsonFile: file => ({ read: () => file, write: () => {} }), ipcMain: {}, updatesConsent: null, cloudAccount: "the client",- nativeText: { prefs: { kept: true }, set: code => { calls.push(["language", code]); return code === "pt-br"; } }, applyNativeLanguage: () => calls.push("relabel"), talk: { relabel: () => calls.push("talk relabel") },+ nativeText: { prefs: { kept: true }, set: code => { calls.push(["language", code]); return code === "pt-br"; }, follow: code => { calls.push(["shown", code]); return code === "de"; } }, applyNativeLanguage: () => calls.push("relabel"), talk: { relabel: () => calls.push("talk relabel") },path: { join: (...parts) => parts.join("/") }, app: { getPath: () => "/user-data" }, desktopDataDir: () => "/home/.openmausbot",navigateMainWindow: async url => { calls.push(["navigate", url]); return loads; },senderIsLocal: localOrigin.isLocalSender, workspaceSenderAllowed: environments.workspaceSenderAllowed,@@ -334,6 +352,8 @@ test("production wiring: main answers this computer's page, My Cloud's own pageassert.deepEqual(sent, [["home", "desktop-language:changed", "en"], ["rail", "desktop-language:changed", "en"]], "every other open window hears the pick, and the window's rail");options.onLanguage("pt-br"); options.onLanguage("en");assert.deepEqual(calls.slice(2), [["language", "pt-br"], "relabel", "talk relabel", ["language", "en"]], "main draws its native surfaces again only when the words change");+ options.onShown("de", {}); options.onShown("de", contents); options.onShown("en", contents);+ assert.deepEqual(calls.slice(6), [["shown", "de"], "relabel", "talk relabel", ["shown", "en"]], "only the window's own page leads main's words, and only a change redraws them");const navigate = main.slice(main.indexOf("function navigateMainWindow(url, keepingRecovery = false) {"), main.indexOf("\n}\n", main.indexOf("function navigateMainWindow(url, keepingRecovery = false) {")) + 3);const load = vm.runInNewContext(`${navigate}; navigateMainWindow`, { homeWindow: { cancel: () => {} }, mainWindow: { isDestroyed: () => false, loadURL: async url => { if (url.endsWith("fail")) throw new Error("ERR_CONNECTION_REFUSED"); } } });assert.equal(await load(`${LOCAL}/ok`), true); assert.equal(await load(`${LOCAL}/fail`), false, "a failed load answers false, never throws");diff --git a/electron/main.mjs b/electron/main.mjsindex cc5d1b815b..5b2f553495 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -3029,7 +3029,7 @@ app.whenReady().then(async () => {for (const win of appWindows()) if (!win.isDestroyed() && win.webContents !== sender) win.webContents.send("desktop-language:changed", language);chromeRail.send("desktop-language:changed", language);},- onLanguage: language => { if (nativeText.set(language)) { applyNativeLanguage(); talk.relabel(); } },+ onLanguage: language => { if (nativeText.set(language)) { applyNativeLanguage(); talk.relabel(); } }, onShown: (language, sender) => { if (sender === mainWindow?.webContents && nativeText.follow(language)) { applyNativeLanguage(); talk.relabel(); } },page: event => senderIsLocal(event) ? "local" : cloudPageAsking(event) ?? (workspaceSenderAllowed(event, mainWindow?.webContents, environmentsState, rendererOrigin()) ? "server" : null) });talk.start({ globalShortcut, screen, prefs: desktopPrefs, remote: () => Boolean(desktopRemoteAccess), away: () => homeWindow.current().kind !== "computer", starting: () => !serverReady, localRequest: localServerRequest, dataDir: () => runningDataDir });// Before the window, so the harness has the CUA descriptor on first render.diff --git a/electron/native-text.cjs b/electron/native-text.cjsindex 19d9cd4d07..22ffdb80c5 100644--- a/electron/native-text.cjs+++ b/electron/native-text.cjs@@ -59,8 +59,9 @@ function createNativeText({ dir = LOCALES_DIR, saved = null, system = () => "",const systemTag = () => {try { return String(system() ?? ""); } catch { return ""; }};- let chosen = resolveLanguage(saved, available());- const language = () => chosen ?? resolveLanguage(systemTag(), available()) ?? ENGLISH;+ let chosen = resolveLanguage(saved, available()), shown = null;+ // With nothing picked, the language the window's page shows (follow), so menus never read in another one beside it.+ const language = () => chosen ?? shown ?? resolveLanguage(systemTag(), available()) ?? ENGLISH;const intlTag = () => {const code = language(), tag = systemTag();if (tag && resolveLanguage(tag, available()) === code) {@@ -79,6 +80,12 @@ function createNativeText({ dir = LOCALES_DIR, saved = null, system = () => "",chosen = resolveLanguage(code, available());return language() !== before;},+ /** The window's page shows `code`: main's words follow it while nothing is picked. True when they change. */+ follow(code) {+ const before = language();+ shown = resolveLanguage(code, available());+ return language() !== before;+ },intlTag,listFormat(names) {if (language() !== ENGLISH) return new Intl.ListFormat(intlTag(), { type: "conjunction" }).format(names);diff --git a/electron/native-text.node-test.mjs b/electron/native-text.node-test.mjsindex a52344f569..476ab9cc15 100644--- a/electron/native-text.node-test.mjs+++ b/electron/native-text.node-test.mjs@@ -78,6 +78,26 @@ test("the saved language wins over the system's, \"\" follows the system again,assert.equal(broken.t("native.x"), "en");});+test("with nothing picked, main's words follow the language the window shows, not the system's beside it", (t) => {+ const dir = packs(t, { "en.json": { "native.x": "en" }, "pt-br.json": { "native.x": "pt" }, "de.json": { "native.x": "de" } });+ const text = createNativeText({ dir, saved: null, system: () => "pt-BR" });+ assert.equal(text.t("native.x"), "pt", "before the window has drawn");+ assert.equal(text.follow("en"), true, "an English window, say a team's default, on a Portuguese system");+ assert.equal(text.t("native.x"), "en");+ assert.equal(text.follow("en"), false);+ for (const code of ["../en", "xx", null]) {+ text.follow("en");+ assert.equal(text.follow(code), true, String(code));+ assert.equal(text.t("native.x"), "pt", `${code}: not a pack, so the system's again`);+ }+ assert.equal(text.follow("de"), true);+ assert.equal(text.set("pt-br"), true, "a pick wins");+ assert.equal(text.follow("de"), false, "the window shows the pick, so this is a stale report");+ assert.equal(text.t("native.x"), "pt");+ assert.equal(text.set(""), true, "System is a pick that follows the window again");+ assert.equal(text.t("native.x"), "de");+});+test("dates and lists follow the app's language; English keeps its own list words", (t) => {const dir = packs(t, { "en.json": {}, "pt-br.json": {} });const pt = createNativeText({ dir, saved: "pt-br", system: () => "en-US" });diff --git a/electron/preload.cjs b/electron/preload.cjsindex c048e39744..d6701937aa 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -673,6 +673,7 @@ const bridge = {languageListeners.add(listener);return () => { languageListeners.delete(listener); };},+ shown: language => { ipcRenderer.send("desktop-language:shown", String(language)); },},};diff --git a/src/App.tsx b/src/App.tsxindex da39fb8475..4c1fef2d46 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -132,7 +132,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {useExternalChatLinks(state, dispatch); useDesktopNotificationOpens(state, dispatch);usePresence(state, dispatch);const [drawerOpen, setDrawerOpen] = useState(false);- usePageLanguage(effectiveLanguage(useLanguageChoice(), state.config?.language));+ usePageLanguage(effectiveLanguage(useLanguageChoice(), state.config?.language), true);const [paletteOpen, setPaletteOpen] = useState(false);// Stays mounted once opened: a Cloud bought in it can arrive after the sheet is closed.const cloudAddOpened = useRef(false);diff --git a/src/lib/language-preference.test.ts b/src/lib/language-preference.test.tsindex 409a954923..4fb080657e 100644--- a/src/lib/language-preference.test.ts+++ b/src/lib/language-preference.test.ts@@ -7,6 +7,8 @@ const hook = vi.hoisted(() => ({}));vi.mock("react", () => ({+ useState: (initial: unknown) => [initial, () => {}],+ useEffect: (effect: () => void) => { effect(); },useSyncExternalStore: (subscribe: (listener: () => void) => () => void,snapshot: () => string | null,@@ -138,6 +140,7 @@ function desktopApp(saved: string | null = null) {return true;}),onChange: (next: (language: string) => void) => { listener = next; return () => { listener = undefined; }; },+ shown: vi.fn(),};},};@@ -198,6 +201,17 @@ describe("app language in the desktop app", () => {expect(page.bridge.set).not.toHaveBeenCalled();});+ it("tells the app the language the window shows, so its menus read in that one too, never the rail's or a stale one", async () => {+ const page = await openPage(desktopApp());+ page.preference.usePageLanguage("", false);+ page.preference.usePageLanguage(page.preference.effectiveLanguage(page.preference.languageChoice(), "pt-br"), true);+ await vi.waitFor(() => expect(page.bridge.shown).toHaveBeenCalledOnce());+ expect(page.bridge.shown).toHaveBeenCalledWith("pt-br");+ page.preference.usePageLanguage("xx-unknown", true);+ await vi.waitFor(() => expect(page.bridge.shown).toHaveBeenLastCalledWith("en"));+ expect(page.bridge.set, "showing a language is not a pick").not.toHaveBeenCalled();+ });+it("carries a pick saved in a page's own storage into the app once", async () => {const app = desktopApp();const thisComputer = await openPage(app, "es");diff --git a/src/lib/language-preference.ts b/src/lib/language-preference.tsindex caa1f80ed5..186cd91a2b 100644--- a/src/lib/language-preference.ts+++ b/src/lib/language-preference.ts@@ -114,10 +114,14 @@ 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 {+/** Shows `language` (the system's when empty) once its pack has loaded, and draws the caller again then. `windowPage`:+ * the window's own page, whose language the desktop app's menus, tray and dialogs follow while nothing is picked. */+export function usePageLanguage(language: string, windowPage = false): void {const [, setShown] = useState(0);useEffect(() => {- void loadLocale(language || globalThis.navigator?.language).then(() => setShown((shown) => shown + 1));- }, [language]);+ void loadLocale(language || globalThis.navigator?.language).then((shown) => {+ if (windowPage) desktop()?.shown?.(shown);+ setShown((count) => count + 1);+ });+ }, [language, windowPage]);}