Skip to content

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

app_settings: the window applies every Appearance, General and remote-access preference

aivsomkar5524cc2f79c4
diff --git a/server/routes/app-settings.test.ts b/server/routes/app-settings.test.ts
index 93d8c5f049..71e999a89f 100644
--- a/server/routes/app-settings.test.ts
+++ b/server/routes/app-settings.test.ts
@@ -33,4 +33,11 @@ describe("window preferences on the server", () => {
expect(prefs.write("appearance.skin", "dusk")).toBeNull();
expect(frames.map((frame) => frame.value)).toEqual(["midnight", "dusk"]);
});
+
+ it("refuses a preference the window never reported, such as a desktop-only one from a browser", () => {
+ const frames: Record<string, unknown>[] = [];
+ const prefs = createWindowPrefs({ broadcast: (frame) => frames.push(frame), ownerOrAdmin: () => true, windowOpen: () => true });
+ expect(prefs.write("remote.relay", true)).toMatch(/^The open MausBot window can't change this here\./);
+ expect(frames).toEqual([]);
+ });
});
diff --git a/server/routes/app-settings.ts b/server/routes/app-settings.ts
index 70d9058558..2f83309c84 100644
--- a/server/routes/app-settings.ts
+++ b/server/routes/app-settings.ts
@@ -17,9 +17,9 @@ export function createInternalAppSettingsRoutes(deps: {
};
}
-/** The window's own preferences (skin, Simple or Advanced, font, chat width, send key, sounds) live in its
- * localStorage. The window reports them here; the server keeps the last report and pushes a change back as a
- * `window-pref` frame, which only an open window can apply. */
+/** The window's own preferences live in its localStorage or behind the desktop app's bridge. The window reports them
+ * here; the server keeps the last report and pushes a change back as a `window-pref` frame, which only an open window
+ * can apply. One the window never reported is one it can't change (a browser has no desktop bridge). */
export function createWindowPrefs(deps: {
broadcast(frame: Record<string, unknown>, options: { adminOnly: true }): void;
ownerOrAdmin(auth: RequestAuth): boolean;
@@ -42,6 +42,7 @@ export function createWindowPrefs(deps: {
read: (id: WindowPrefId) => values.get(id),
write(id: WindowPrefId, value: unknown): string | null {
if (!deps.windowOpen()) return "Open MausBot on this computer first; this setting lives in the app window.";
+ if (!values.has(id)) return "The open MausBot window can't change this here. It is changed in MausBot's desktop app on this computer.";
values.set(id, value);
deps.broadcast({ kind: "window-pref", id, value }, { adminOnly: true });
return null;
diff --git a/shared/app-settings.ts b/shared/app-settings.ts
index 5883ac6a1d..1a0963a58d 100644
--- a/shared/app-settings.ts
+++ b/shared/app-settings.ts
@@ -32,8 +32,12 @@ export const FONT_IDS = ["skin", "system", "inter", "poppins", "serif"] as const
export const CHAT_WIDTH_IDS = ["standard", "wide", "full"] as const;
/** The Enter-adds-a-line modes are for input methods that confirm a conversion with Enter (Japanese). */
export const SEND_KEYS = ["enter", "shift-enter", "mod-enter"] as const;
+export const PLACE_SWATCHES = ["blue", "green", "amber", "rose", "violet", "slate"] as const;
+export const TALK_KEYS = ["ctrl-opt-space", "ctrl-shift-space", "opt-shift-space"] as const;
+const pinnedPage = z.object({ name: z.string().trim().min(1).max(40), url: z.string().trim().max(2048).regex(/^https?:\/\/\S+$/, "an http(s) address") }).strict();
-/** Preferences kept in the window, by setting id; the renderer applies a frame with the matching setter. */
+/** Preferences kept in the window or behind the desktop app's own bridge, by setting id; the renderer applies a frame with
+ * the matching setter. */
export const WINDOW_PREFS = {
"appearance.skin": z.enum([...SKIN_IDS, "system"]),
"appearance.advanced": z.boolean(),
@@ -41,6 +45,28 @@ export const WINDOW_PREFS = {
"appearance.chatWidth": z.enum(CHAT_WIDTH_IDS),
"general.sendKey": z.enum(SEND_KEYS),
"general.notificationSounds": z.boolean(),
+ "appearance.userBubbles": z.boolean(),
+ "appearance.runCard": z.boolean(),
+ "appearance.showThreads": z.boolean(),
+ "appearance.toolsLayout": z.enum(["rows", "toolbar"]),
+ "appearance.pinnedCircles": z.boolean(),
+ "appearance.universalPins": z.boolean(),
+ "appearance.pinnedPages": z.array(pinnedPage).max(6),
+ "appearance.showComputers": z.boolean(),
+ "appearance.windowFrame": z.boolean(),
+ "appearance.sidebarColor": z.enum([...PLACE_SWATCHES, "none"]),
+ "general.followUp": z.enum(["steer", "queue"]),
+ "general.finishedNotifications": z.boolean(),
+ "general.notificationFeed": z.boolean(),
+ "general.analytics": z.boolean(),
+ "general.openAtLogin": z.boolean(),
+ "general.talkShortcut": z.object({ enabled: z.boolean(), key: z.enum(TALK_KEYS) }).strict(),
+ "account.productEmails": z.boolean(),
+ "remote.wifi": z.boolean(),
+ "remote.relay": z.boolean(),
+ "remote.tailscale": z.boolean(),
+ "remote.keepAwake": z.boolean(),
+ "remote.httpsAddress": z.boolean(),
} as const;
export type WindowPrefId = keyof typeof WINDOW_PREFS;
export type WindowPrefValue<I extends WindowPrefId> = z.infer<(typeof WINDOW_PREFS)[I]>;
diff --git a/src/lib/run-card-preferences.ts b/src/lib/run-card-preferences.ts
index e00029837b..ec559219a3 100644
--- a/src/lib/run-card-preferences.ts
+++ b/src/lib/run-card-preferences.ts
@@ -13,7 +13,7 @@ function storage(): Storage | undefined {
}
}
-function showRunCard(): boolean {
+export function showRunCard(): boolean {
if (sessionChoice !== undefined) return sessionChoice;
try {
return storage()?.getItem(RUN_CARD_KEY) !== "0";
diff --git a/src/lib/thread-preferences.ts b/src/lib/thread-preferences.ts
index dc8da3f956..868aa64fe9 100644
--- a/src/lib/thread-preferences.ts
+++ b/src/lib/thread-preferences.ts
@@ -15,7 +15,7 @@ function storage(): Storage | undefined {
}
}
-function showThreads(): boolean {
+export function showThreads(): boolean {
if (sessionChoice !== undefined) return sessionChoice;
try {
return storage()?.getItem(SHOW_THREADS_KEY) !== "0";
diff --git a/src/lib/window-prefs.test.ts b/src/lib/window-prefs.test.ts
index ab2cbc97bf..bd8643e858 100644
--- a/src/lib/window-prefs.test.ts
+++ b/src/lib/window-prefs.test.ts
@@ -14,13 +14,14 @@ afterEach(() => {
});
describe("window preferences", () => {
- it("applies a frame with the preference's setter and ignores a value the schema refuses", () => {
+ it("applies a frame with the preference's setter and ignores a value the schema refuses", async () => {
applyWindowPref({ kind: "window-pref", id: "general.sendKey", value: "mod-enter" });
expect(values.get("omb-send-key")).toBe("mod-enter");
applyWindowPref({ kind: "window-pref", id: "general.sendKey", value: "space" });
expect(values.get("omb-send-key")).toBe("mod-enter");
applyWindowPref({ kind: "window-pref", id: "general.notificationSounds", value: false });
- expect(windowPrefValues()).toMatchObject({ "general.sendKey": "mod-enter", "general.notificationSounds": false });
+ applyWindowPref({ kind: "window-pref", id: "appearance.pinnedCircles", value: true });
+ expect(await windowPrefValues()).toMatchObject({ "general.sendKey": "mod-enter", "general.notificationSounds": false, "appearance.pinnedCircles": true });
});
it("reports the window's values once after a burst of setters", async () => {
@@ -36,4 +37,21 @@ describe("window preferences", () => {
expect(url).toBe("/api/window-prefs");
expect(JSON.parse(String(init.body)).values).toMatchObject({ "general.sendKey": "shift-enter" });
});
+
+ it("leaves out a preference whose desktop bridge this window lacks, so the server refuses it here", async () => {
+ const values = await windowPrefValues();
+ expect(values).not.toHaveProperty("remote.relay");
+ expect(values).not.toHaveProperty("general.openAtLogin");
+ });
+
+ it("reads and switches a remote route through the companion bridge on this computer's page", async () => {
+ const routes = { wifi: { on: false, since: null }, relay: { on: true, since: 1 } };
+ const setRoute = vi.fn(async (route: "wifi" | "relay", on: boolean) => { routes[route].on = on; return { routes } as never; });
+ const ogb = { companion: { state: async () => ({ routes, keepAwake: false }), setRoute } };
+ vi.stubGlobal("window", { ogb });
+ vi.stubGlobal("ogb", ogb);
+ expect(await windowPrefValues()).toMatchObject({ "remote.wifi": false, "remote.relay": true, "remote.keepAwake": false });
+ applyWindowPref({ kind: "window-pref", id: "remote.wifi", value: true });
+ expect(setRoute).toHaveBeenCalledWith("wifi", true);
+ });
});
diff --git a/src/lib/window-prefs.ts b/src/lib/window-prefs.ts
index 3275998062..035795cb52 100644
--- a/src/lib/window-prefs.ts
+++ b/src/lib/window-prefs.ts
@@ -1,31 +1,113 @@
// The window's own preferences, as the server's app_settings tool reaches them: a `window-pref` frame is applied with
-// the preference's setter, and every setter reports the current values back so a bot can read them.
-import { WINDOW_PREFS, type WindowPrefFrame, type WindowPrefId } from "../../shared/app-settings";
+// the preference's setter, and every setter reports the current values back so a bot can read them. Some live behind the
+// desktop app's bridge; where that bridge is absent they read as undefined, which the server takes as "not here".
+import { WINDOW_PREFS, type WindowPrefFrame, type WindowPrefId, type WindowPrefValue } from "../../shared/app-settings";
+import { analyticsEnabled, setAnalyticsEnabled } from "./analytics";
import { applyChatWidth, readChatWidth } from "./chat-width";
+import { companionBridge, pageIsThisComputer } from "./companion-bridge";
+import type { CompanionRoute } from "./companion-types";
import { applyFont, readFont } from "./fonts";
+import { readFollowUpDefault, setFollowUpDefault } from "./follow-up";
import { readAdvancedMode, setAdvancedMode } from "./interface-mode";
-import { notificationSoundsEnabled, setNotificationSounds } from "./notification-preferences";
+import { finishedNotificationsEnabled, notificationFeedEnabled, notificationSoundsEnabled, setFinishedNotifications, setNotificationFeed, setNotificationSounds } from "./notification-preferences";
+import { requestNotificationPermission } from "./notify";
+import { choosePlaceColor } from "./place-look";
+import { setShowRunCard, showRunCard } from "./run-card-preferences";
import { readSendKey, setSendKey } from "./send-key";
+import { loadPinnedCircles, loadSidebarToolsLayout, loadUniversalPins, setPinnedCircles, setSidebarToolsLayout, setUniversalPins } from "./sidebar-preferences";
import { applySkinChoice, readSkinChoice } from "./skins";
+import { setShowThreads, showThreads } from "./thread-preferences";
+import { readColorUserBubbles, setColorUserBubbles } from "./user-bubble-preference";
+import { latestWebPanels, setWebPanels } from "./web-panel-preferences";
+import { newWebPanelId, validateWebPanel, type WebPanel } from "./web-panels";
-const PREFS: Record<WindowPrefId, { read(): unknown; write(value: never): void }> = {
+type Pref<I extends WindowPrefId> = { read(): unknown; write(value: WindowPrefValue<I>): unknown };
+const ogb = () => (typeof window === "undefined" ? undefined : window.ogb);
+const companion = () => (pageIsThisComputer() ? companionBridge() : null);
+const route = (name: CompanionRoute): { read(): unknown; write(on: boolean): unknown } => ({
+ read: async () => (await companion()?.state())?.routes?.[name]?.on,
+ write: (on) => {
+ const bridge = companion();
+ if (!bridge) return;
+ if (name === "tailscale") return bridge.setTailscale ? bridge.setTailscale(on) : on ? bridge.refreshTailscale() : bridge.state();
+ return bridge.setRoute ? bridge.setRoute(name, on) : on ? bridge.start([name]) : bridge.state();
+ },
+});
+
+// Called, never referenced at load: many tests mock these modules with only the exports they use.
+const PREFS: { [I in WindowPrefId]: Pref<I> } = {
"appearance.skin": { read: readSkinChoice, write: applySkinChoice },
"appearance.advanced": { read: readAdvancedMode, write: setAdvancedMode },
"appearance.font": { read: readFont, write: applyFont },
"appearance.chatWidth": { read: readChatWidth, write: applyChatWidth },
"general.sendKey": { read: readSendKey, write: setSendKey },
"general.notificationSounds": { read: notificationSoundsEnabled, write: setNotificationSounds },
+ "appearance.userBubbles": { read: () => readColorUserBubbles(), write: (on) => setColorUserBubbles(on) },
+ "appearance.runCard": { read: () => showRunCard(), write: (on) => setShowRunCard(on) },
+ "appearance.showThreads": { read: () => showThreads(), write: (on) => setShowThreads(on) },
+ "appearance.toolsLayout": { read: () => loadSidebarToolsLayout(), write: (layout) => setSidebarToolsLayout(layout) },
+ "appearance.pinnedCircles": { read: () => loadPinnedCircles(), write: (on) => setPinnedCircles(on) },
+ "appearance.universalPins": { read: () => loadUniversalPins(), write: (on) => setUniversalPins(on) },
+ "appearance.pinnedPages": {
+ read: () => latestWebPanels().flatMap((panel) => (panel.url === undefined ? [] : [{ name: panel.name, url: panel.url }])),
+ write: (pages) => {
+ // Chat pages pinned from a conversation stay; only the web pages are replaced.
+ const next: WebPanel[] = latestWebPanels().filter((panel) => panel.url === undefined);
+ for (const page of pages) {
+ const check = validateWebPanel(page, window.location.origin);
+ if (!check.ok) return;
+ next.push({ id: newWebPanelId(next), name: check.name, url: check.url });
+ }
+ setWebPanels(next);
+ },
+ },
+ "appearance.showComputers": {
+ read: async () => { const state = await ogb()?.rail?.state?.(); return state?.available ? !state.hidden : undefined; },
+ write: (on) => ogb()?.rail?.setHidden?.(!on),
+ },
+ "appearance.windowFrame": { read: async () => (await ogb()?.windowFrame?.state())?.on, write: (on) => ogb()?.windowFrame?.set(on) },
+ "appearance.sidebarColor": {
+ read: async () => {
+ const workspaces = ogb()?.remoteClient?.active ? undefined : ogb()?.workspaces;
+ const look = await workspaces?.look?.();
+ return look?.change ? look.swatch ?? "none" : undefined;
+ },
+ write: (swatch) => choosePlaceColor(swatch === "none" ? null : swatch),
+ },
+ "general.followUp": { read: () => readFollowUpDefault(), write: (choice) => setFollowUpDefault(choice) },
+ "general.finishedNotifications": {
+ read: () => finishedNotificationsEnabled(),
+ // As the row does: turning it on asks the system for permission first.
+ write: async (on) => { if (!on) return setFinishedNotifications(false); if ((await requestNotificationPermission()) === "granted") setFinishedNotifications(true); },
+ },
+ "general.notificationFeed": { read: () => notificationFeedEnabled(), write: (on) => setNotificationFeed(on) },
+ "general.analytics": { read: () => analyticsEnabled(), write: (on) => setAnalyticsEnabled(on) },
+ "general.openAtLogin": { read: async () => { const state = await ogb()?.openAtLogin?.state(); return state?.available ? state.on : undefined; }, write: (on) => ogb()?.openAtLogin?.set(on) },
+ "general.talkShortcut": {
+ read: async () => { const state = await ogb()?.talkShortcut?.state(); return state?.available ? { enabled: state.enabled, key: state.key } : undefined; },
+ write: (change) => ogb()?.talkShortcut?.set(change),
+ },
+ "account.productEmails": {
+ read: async () => { const state = await ogb()?.updatesConsent?.state(); return state?.available ? state.status === "opted_in" : undefined; },
+ write: (on) => ogb()?.updatesConsent?.choose({ status: on ? "opted_in" : "withdrawn" }),
+ },
+ "remote.wifi": route("wifi"),
+ "remote.relay": route("relay"),
+ "remote.tailscale": route("tailscale"),
+ "remote.httpsAddress": route("https"),
+ "remote.keepAwake": { read: async () => (await companion()?.state())?.keepAwake, write: (on) => companion()?.keepAwake(on) },
};
export function applyWindowPref(frame: WindowPrefFrame): void {
- const schema = WINDOW_PREFS[frame.id];
- const parsed = schema?.safeParse(frame.value);
+ const parsed = WINDOW_PREFS[frame.id]?.safeParse(frame.value);
if (!parsed?.success) return;
- PREFS[frame.id].write(parsed.data as never);
+ void Promise.resolve((PREFS[frame.id] as Pref<WindowPrefId>).write(parsed.data as never)).catch(() => undefined).finally(reportWindowPrefs);
}
-export function windowPrefValues(): Record<WindowPrefId, unknown> {
- return Object.fromEntries((Object.keys(PREFS) as WindowPrefId[]).map((id) => [id, PREFS[id].read()])) as Record<WindowPrefId, unknown>;
+export async function windowPrefValues(): Promise<Partial<Record<WindowPrefId, unknown>>> {
+ const ids = Object.keys(PREFS) as WindowPrefId[];
+ const values = await Promise.all(ids.map((id) => Promise.resolve().then(() => PREFS[id].read()).catch(() => undefined)));
+ return Object.fromEntries(ids.flatMap((id, index) => (values[index] === undefined ? [] : [[id, values[index]]])));
}
let report: ReturnType<typeof setTimeout> | null = null;
@@ -35,6 +117,8 @@ export function reportWindowPrefs(): void {
if (report) clearTimeout(report);
report = setTimeout(() => {
report = null;
- fetch("/api/window-prefs", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ values: windowPrefValues() }) }).catch(() => undefined);
+ void windowPrefValues()
+ .then((values) => fetch("/api/window-prefs", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ values }) }))
+ .catch(() => undefined);
}, 200);
}