Skip to content

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

app_settings: window preferences change only while the app window is open

aivsomkar73414bfcd30d
diff --git a/server/app-settings.e2e.test.ts b/server/app-settings.e2e.test.ts
index 239ebed1c9..3c0e4e3f75 100644
--- a/server/app-settings.e2e.test.ts
+++ b/server/app-settings.e2e.test.ts
@@ -163,6 +163,39 @@ it("an owner-only setting is refused with where to change it", async () => {
text: "Approval modes is changed only by the owner, in a bot's Settings. Tell the user where to find it; do not try another way." })]);
}, 60_000);
+it("a window preference changes only while the app window's stream is open: refused with none, applied once one connects, refused after it closes, applied again on reconnect", async () => {
+ const openWindow = async () => {
+ const closed = new AbortController();
+ const response = await fetch(`${url}/api/events?window=1`, { headers: { origin: url }, signal: closed.signal });
+ const reader = response.body!.getReader();
+ let seen = "";
+ const pump = (async () => { try { for (;;) { const { value, done } = await reader.read(); if (done) return; seen += new TextDecoder().decode(value); } } catch {} })();
+ await expect.poll(() => seen.includes('"kind":"hello"')).toBe(true);
+ return { frames: () => seen, close: async () => { closed.abort(); await pump; } };
+ };
+ await api("PUT", "/api/window-prefs", { values: { "appearance.skin": "daylight" } });
+ await start("WINDOW-NONE", [step({ action: "set", id: "appearance.skin", value: "midnight" }, true)]);
+ expect(results(await finished("WINDOW-NONE"))).toEqual([expect.objectContaining({ isError: true, text: "Open MausBot on this computer first; this setting lives in the app window." })]);
+
+ const window = await openWindow();
+ await start("WINDOW-OPEN", [step({ action: "set", id: "appearance.skin", value: "midnight" })]);
+ expect(results(await finished("WINDOW-OPEN"))).toEqual([expect.objectContaining({ isError: false, text: expect.stringMatching(/^Changed Skin from daylight to midnight\./) })]);
+ expect(window.frames()).toContain('"kind":"window-pref","id":"appearance.skin","value":"midnight"');
+ await window.close();
+
+ await expect.poll(async () => {
+ const key = `WINDOW-CLOSED-${Date.now()}`;
+ await start(key, [step({ action: "set", id: "appearance.skin", value: "dusk" }, true)]);
+ return results(await finished(key))[0]?.text;
+ }, { timeout: 30_000, message: "the closed window's stream is gone" }).toBe("Open MausBot on this computer first; this setting lives in the app window.");
+
+ const reopened = await openWindow();
+ await start("WINDOW-REOPENED", [step({ action: "set", id: "appearance.skin", value: "dusk" })]);
+ expect(results(await finished("WINDOW-REOPENED"))[0]).toMatchObject({ isError: false, text: expect.stringMatching(/^Changed Skin from midnight to dusk\./) });
+ expect(reopened.frames()).toContain('"value":"dusk"');
+ await reopened.close();
+}, 120_000);
+
it("a webhook's run may read a setting but not change it", async () => {
const value = config().rooms?.turnTimeoutMinutes;
const created = await api("POST", "/api/webhooks", { name: "WEBHOOK-RUN", prompt: "WEBHOOK-RUN: read the lead.", botId: bot.id }, 201);
diff --git a/server/index.ts b/server/index.ts
index fb730cc973..1ad03aad3e 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -4620,6 +4620,8 @@ interface SseClient {
/** On a Team Cloud, who the stream is for: its config frames carry that person's own profile. */
person?: SessionRecord;
screens: boolean;
+ /** The app window's own stream (`?window=1`): only it applies window-pref frames. */
+ window: boolean;
/** Revoking or expiring this session must end the stream, not just future requests. */
sessionId?: string;
backpressured: boolean;
@@ -12352,7 +12354,7 @@ const postiz = createPostiz({ cfg: () => cfg, mcpOAuth, persistMcpServers: persi
...(CLOUD_TEAM ? { ownProfile: (auth: RequestAuth, profile: { name?: string; avatarUrl?: string; aboutMe?: string }) => auth.kind === "session" ? (teamHost.saveMemberProfile(auth.session, profile), true) : false, ownHints: (auth: RequestAuth, hints: string[]) => auth.kind === "session" ? (teamWelcome.save(personKey(auth.session), { hints }), true) : false } : {}),
resyncOpenCodeProviderKeys, revokeEngineCapabilities, reloadProviders, broadcast, drainQueuedSends, postiz,
}); ROUTES.push(createPostizRoutes({ postiz }), configRoutes);
-const windowPrefs = createWindowPrefs({ broadcast, ownerOrAdmin }); const appSettings = createAppSettings({ store, dataDir: DATA_DIR, entries: routeBackedRegistry({ cfg: () => cfg, store, routes: { config: configRoutes, botOrder: botOrderRoutes, sections: sidebarRoutes }, credentials: () => botLogins.credentialConfig(cfg), window: windowPrefs }), turnOwner: (turn) => phones.turnOwner(turn), guestDriven: cloudGuestDriven, requestCredential: (bot, threadId, body) => secretCards.requestCredential(bot, threadId, body), connectorThread, activeGroupTurnForBot, notify, language: threadLanguage }); ROUTES.push(windowPrefs.routes);
+const windowPrefs = createWindowPrefs({ broadcast, ownerOrAdmin, windowOpen: () => [...sseClients].some((client) => client.admin && client.window) }); const appSettings = createAppSettings({ store, dataDir: DATA_DIR, entries: routeBackedRegistry({ cfg: () => cfg, store, routes: { config: configRoutes, botOrder: botOrderRoutes, sections: sidebarRoutes }, credentials: () => botLogins.credentialConfig(cfg), window: windowPrefs }), turnOwner: (turn) => phones.turnOwner(turn), guestDriven: cloudGuestDriven, requestCredential: (bot, threadId, body) => secretCards.requestCredential(bot, threadId, body), connectorThread, activeGroupTurnForBot, notify, language: threadLanguage }); ROUTES.push(windowPrefs.routes);
ROUTES.push(createInstanceRoutes({
store, cfg, registry, sessions, providerAuthSessions,
hostedModels: Boolean(hostedModels),
@@ -14673,7 +14675,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const client: SseClient = {
res,
admin: auth.scopes.includes("admin"),
- screens: url.searchParams.get("screens") !== "off",
+ screens: url.searchParams.get("screens") !== "off", window: url.searchParams.get("window") === "1",
backpressured: false,
viewer, ask: teamOwners.viewer(auth),
seen: viewer.kind === "all" && !visibleNow.filtersThreads ? { bots: new Set(), groups: new Set() } : {
diff --git a/server/routes/app-settings.test.ts b/server/routes/app-settings.test.ts
index 0325067ce1..93d8c5f049 100644
--- a/server/routes/app-settings.test.ts
+++ b/server/routes/app-settings.test.ts
@@ -10,8 +10,7 @@ const phone: RequestAuth = { kind: "loopback", scopes: ["client"] };
describe("window preferences on the server", () => {
it("keeps what an owner's window reports, drops what the schema refuses, and pushes a change as a frame", async () => {
const frames: Record<string, unknown>[] = [];
- const prefs = createWindowPrefs({ broadcast: (frame) => frames.push(frame), ownerOrAdmin: (auth) => auth.scopes.includes("admin") });
- expect(prefs.write("appearance.skin", "midnight")).toContain("Open MausBot on this computer first");
+ const prefs = createWindowPrefs({ broadcast: (frame) => frames.push(frame), ownerOrAdmin: (auth) => auth.scopes.includes("admin"), windowOpen: () => true });
expect(await callRoute(prefs.routes, { method: "PUT", path: "/api/window-prefs", body: { values: { "appearance.skin": "daylight" } }, auth: phone })).toMatchObject({ status: 403 });
expect(await callRoute(prefs.routes, { method: "PUT", path: "/api/window-prefs", body: { values: { "appearance.skin": "daylight", "appearance.font": "comic", "nope": 1 } }, auth: owner })).toMatchObject({ status: 200 });
expect(prefs.read("appearance.skin")).toBe("daylight");
@@ -20,4 +19,18 @@ describe("window preferences on the server", () => {
expect(prefs.read("appearance.skin")).toBe("midnight");
expect(frames).toEqual([{ kind: "window-pref", id: "appearance.skin", value: "midnight" }]);
});
+
+ it("changes nothing while no window is open, and works again once one reconnects", async () => {
+ const frames: Record<string, unknown>[] = [];
+ let open = true;
+ const prefs = createWindowPrefs({ broadcast: (frame) => frames.push(frame), ownerOrAdmin: () => true, windowOpen: () => open });
+ await callRoute(prefs.routes, { method: "PUT", path: "/api/window-prefs", body: { values: { "appearance.skin": "daylight" } }, auth: owner });
+ expect(prefs.write("appearance.skin", "midnight")).toBeNull();
+ open = false;
+ expect(prefs.write("appearance.skin", "dusk")).toBe("Open MausBot on this computer first; this setting lives in the app window.");
+ expect(prefs.read("appearance.skin")).toBe("midnight");
+ open = true;
+ expect(prefs.write("appearance.skin", "dusk")).toBeNull();
+ expect(frames.map((frame) => frame.value)).toEqual(["midnight", "dusk"]);
+ });
});
diff --git a/server/routes/app-settings.ts b/server/routes/app-settings.ts
index 04feb58063..70d9058558 100644
--- a/server/routes/app-settings.ts
+++ b/server/routes/app-settings.ts
@@ -19,8 +19,13 @@ 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. Nothing is reported until a window has, so `set` can tell the bot to open the app first. */
-export function createWindowPrefs(deps: { broadcast(frame: Record<string, unknown>, options: { adminOnly: true }): void; ownerOrAdmin(auth: RequestAuth): boolean }) {
+ * `window-pref` frame, which only an open window can apply. */
+export function createWindowPrefs(deps: {
+ broadcast(frame: Record<string, unknown>, options: { adminOnly: true }): void;
+ ownerOrAdmin(auth: RequestAuth): boolean;
+ /** An owner's app window holds its live event stream open now. */
+ windowOpen(): boolean;
+}) {
const values = new Map<WindowPrefId, unknown>();
const routes: RouteHandler = async ({ req, res, path, method, auth, json, readBody }) => {
if (method !== "PUT" || path !== WINDOW_PREFS_PATH) return PASS;
@@ -36,7 +41,7 @@ export function createWindowPrefs(deps: { broadcast(frame: Record<string, unknow
routes,
read: (id: WindowPrefId) => values.get(id),
write(id: WindowPrefId, value: unknown): string | null {
- if (!values.size) return "Open MausBot on this computer first: this preference lives in the app window.";
+ if (!deps.windowOpen()) return "Open MausBot on this computer first; this setting lives in the app window.";
values.set(id, value);
deps.broadcast({ kind: "window-pref", id, value }, { adminOnly: true });
return null;
diff --git a/src/lib/live-events.test.ts b/src/lib/live-events.test.ts
index 19981eb8e0..bee1e2988e 100644
--- a/src/lib/live-events.test.ts
+++ b/src/lib/live-events.test.ts
@@ -98,10 +98,10 @@ afterEach(() => { vi.useRealTimers(); resetCloudPowerForTests(); });
describe("live events URL", () => {
it("builds cold and resumable stream URLs", () => {
- expect(liveEventsUrl()).toBe("/api/events");
- expect(liveEventsUrl({ since: "ab12cd34:9" })).toBe("/api/events?since=ab12cd34%3A9");
- expect(liveEventsUrl({ since: "ab12cd34:9", screens: false })).toBe("/api/events?since=ab12cd34%3A9&screens=off");
- expect(liveEventsUrl({ screens: true })).toBe("/api/events");
+ expect(liveEventsUrl()).toBe("/api/events?window=1");
+ expect(liveEventsUrl({ since: "ab12cd34:9" })).toBe("/api/events?since=ab12cd34%3A9&window=1");
+ expect(liveEventsUrl({ since: "ab12cd34:9", screens: false })).toBe("/api/events?since=ab12cd34%3A9&screens=off&window=1");
+ expect(liveEventsUrl({ screens: true })).toBe("/api/events?window=1");
});
});
@@ -139,7 +139,7 @@ describe("live events supervisor", () => {
test.sources[0].error();
retryLiveEvents();
expect(test.sources).toHaveLength(2);
- expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4&screens=off");
+ expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4&screens=off&window=1");
test.sources[1].open();
test.sources[1].message({ kind: "ping" });
vi.advanceTimersByTime(500);
@@ -196,7 +196,7 @@ describe("live events supervisor", () => {
test.setNow(1_900);
vi.advanceTimersByTime(500);
expect(test.sources).toHaveLength(2);
- expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4&screens=off");
+ expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4&screens=off&window=1");
expect(test.sources[0].close).toHaveBeenCalledOnce();
stop();
});
@@ -238,19 +238,19 @@ describe("live events supervisor", () => {
test.sources[0].message({ kind: "message" }, "oldrun00:10");
test.sources[0].error();
vi.advanceTimersByTime(100);
- expect(test.sources[1].url).toBe("/api/events?since=oldrun00%3A10&screens=off");
+ expect(test.sources[1].url).toBe("/api/events?since=oldrun00%3A10&screens=off&window=1");
test.sources[1].message({ kind: "hello", resumed: true, cursor: "oldrun00:13" });
test.sources[1].error();
vi.advanceTimersByTime(100);
- expect(test.sources[2].url).toBe("/api/events?since=oldrun00%3A10&screens=off");
+ expect(test.sources[2].url).toBe("/api/events?since=oldrun00%3A10&screens=off&window=1");
test.sources[2].message({ kind: "hello", resumed: false, cursor: "newrun00:7" });
test.sources[2].message({ kind: "message", value: "behind failed snapshot" }, "newrun00:8");
snapshotResolutions.shift()?.(false);
await Promise.resolve();
vi.advanceTimersByTime(100);
- expect(test.sources[3].url).toBe("/api/events?since=oldrun00%3A10&screens=off");
+ expect(test.sources[3].url).toBe("/api/events?since=oldrun00%3A10&screens=off&window=1");
test.sources[3].message({ kind: "hello", resumed: false, cursor: "newrun00:8" });
test.sources[3].message({ kind: "message", value: "after snapshot" }, "newrun00:9");
@@ -258,7 +258,7 @@ describe("live events supervisor", () => {
await Promise.resolve();
test.sources[3].error();
vi.advanceTimersByTime(100);
- expect(test.sources[4].url).toBe("/api/events?since=newrun00%3A9&screens=off");
+ expect(test.sources[4].url).toBe("/api/events?since=newrun00%3A9&screens=off&window=1");
expect(frames).toEqual([
{ kind: "message" },
{ kind: "message", value: "behind failed snapshot" },
@@ -423,7 +423,7 @@ describe("a Cloud home that goes to sleep", () => {
expect(test.sources).toHaveLength(1);
markCloudAwake();
expect(test.sources).toHaveLength(2);
- expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4&screens=off");
+ expect(test.sources[1].url).toBe("/api/events?since=run00000%3A4&screens=off&window=1");
stop();
});
@@ -465,7 +465,7 @@ describe("a Cloud home that goes to sleep", () => {
loading.sources[0].message(sleeping, "run00000:5");
expect(cloudAsleep()).toBe(true);
markCloudAwake();
- expect(loading.sources[1].url).toBe("/api/events?screens=off");
+ expect(loading.sources[1].url).toBe("/api/events?screens=off&window=1");
stopLoading();
});
@@ -483,7 +483,7 @@ describe("live screens", () => {
it("leave screens out until a view that draws them listens, then reopen from the cursor both ways", async () => {
const test = harness();
const stop = openLiveEvents({ onFrame: vi.fn(), onSnapshotRequired: async () => true }, test.platform);
- expect(test.sources[0].url).toBe("/api/events?screens=off");
+ expect(test.sources[0].url).toBe("/api/events?screens=off&window=1");
test.sources[0].open();
test.sources[0].message({ kind: "hello", resumed: true, cursor: "run00000:3" });
test.sources[0].message({ kind: "message" }, "run00000:4");
@@ -494,7 +494,7 @@ describe("live screens", () => {
const viewer = listenLiveFrames({ screens: true, onFrame: () => {} });
const second = listenLiveFrames({ screens: true, onFrame: () => {} });
await Promise.resolve();
- expect(test.sources.map((source) => source.url)).toEqual(["/api/events?screens=off", "/api/events?since=run00000%3A4"]);
+ expect(test.sources.map((source) => source.url)).toEqual(["/api/events?screens=off&window=1", "/api/events?since=run00000%3A4&window=1"]);
expect(test.sources[0].close).toHaveBeenCalledOnce();
viewer();
@@ -502,7 +502,7 @@ describe("live screens", () => {
expect(test.sources).toHaveLength(2);
second();
await Promise.resolve();
- expect(test.sources[2].url).toBe("/api/events?since=run00000%3A4&screens=off");
+ expect(test.sources[2].url).toBe("/api/events?since=run00000%3A4&screens=off&window=1");
quiet();
stop();
});
diff --git a/src/lib/live-events.ts b/src/lib/live-events.ts
index f0e9ff0595..1c9f04261d 100644
--- a/src/lib/live-events.ts
+++ b/src/lib/live-events.ts
@@ -59,13 +59,13 @@ export interface LiveEventsHandlers {
retryMaxMs?: number;
}
-/** `screens: false` asks the server to leave out live screen frames. */
+/** `screens: false` asks the server to leave out live screen frames; `window=1` tells it an app window is open. */
export function liveEventsUrl(options?: { since?: string | null; screens?: boolean }): string {
const params = new URLSearchParams();
if (options?.since) params.set("since", options.since);
if (options?.screens === false) params.set("screens", "off");
- const query = params.toString();
- return query ? `${LIVE_EVENTS_PATH}?${query}` : LIVE_EVENTS_PATH;
+ params.set("window", "1");
+ return `${LIVE_EVENTS_PATH}?${params}`;
}
export interface LiveFrameListener {
diff --git a/src/state/live-frames.test.ts b/src/state/live-frames.test.ts
index 4fb8b3ed83..e5d7ede0c6 100644
--- a/src/state/live-frames.test.ts
+++ b/src/state/live-frames.test.ts
@@ -69,7 +69,7 @@ afterAll(() => {
describe("live frames the store does not keep", () => {
it("come from the app's one stream", () => {
expect(seen.bots.map((candidate) => candidate.id)).toEqual(["bot"]);
- expect(FixtureEventSource.opened.map((source) => source.url)).toEqual(["/api/events?screens=off"]);
+ expect(FixtureEventSource.opened.map((source) => source.url)).toEqual(["/api/events?screens=off&window=1"]);
});
it("hand a screen frame to its listener without touching app state", async () => {