Skip to content

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

Always allow: never approve a request whose grant was not saved; refuse a full list instead of dropping the grant

Bugfixer 253b718db1138
diff --git a/server/always-allow.test.ts b/server/always-allow.test.ts
new file mode 100644
index 0000000000..a3321a0f36
--- /dev/null
+++ b/server/always-allow.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from "vitest";
+
+import { MAX_ALWAYS_ALLOW, withAlwaysAllowKey } from "./always-allow.ts";
+
+const full = Array.from({ length: MAX_ALWAYS_ALLOW }, (_, i) => `provider-tool:claude:linear:tool_${i}:0123456789abcdef`);
+
+describe("adding an Always allow grant", () => {
+ it("adds a new key once and keeps the ones already there", () => {
+ expect(withAlwaysAllowKey(undefined, "Read")).toEqual(["Read"]);
+ expect(withAlwaysAllowKey(["Read"], "Grep")).toEqual(["Read", "Grep"]);
+ expect(withAlwaysAllowKey(["Read", "Grep"], "Read")).toEqual(["Read", "Grep"]);
+ });
+
+ it("refuses a new key when the list is full instead of dropping it", () => {
+ expect(withAlwaysAllowKey(full.slice(1), full[0])).toHaveLength(MAX_ALWAYS_ALLOW);
+ expect(withAlwaysAllowKey(full, "provider-tool:claude:linear:one_more:0123456789abcdef")).toBeNull();
+ });
+
+ it("still accepts a key that is already on a full list", () => {
+ expect(withAlwaysAllowKey(full, full[7])).toEqual(full);
+ });
+});
diff --git a/server/always-allow.ts b/server/always-allow.ts
new file mode 100644
index 0000000000..36696d4a36
--- /dev/null
+++ b/server/always-allow.ts
@@ -0,0 +1,9 @@
+// A bot's (and each of its threads') "Always allow" list has a fixed size. A grant past it is refused, never dropped,
+// so the approval card that asked to remember it stays waiting instead of being allowed as if it had been saved.
+export const MAX_ALWAYS_ALLOW = 200;
+
+/** `keys` with `key` added (once), or null when there is no room for it. */
+export function withAlwaysAllowKey(keys: readonly string[] | undefined, key: string): string[] | null {
+ const next = [...new Set([...(keys ?? []), key])];
+ return next.length > MAX_ALWAYS_ALLOW ? null : next;
+}
diff --git a/server/routes/bot-patch.test.ts b/server/routes/bot-patch.test.ts
index 9e5a99e17b..57efcee1a4 100644
--- a/server/routes/bot-patch.test.ts
+++ b/server/routes/bot-patch.test.ts
@@ -263,6 +263,19 @@ describe("PATCH /api/bots/:id toolsOff", () => {
});
});
+describe("PATCH /api/bots/:id alwaysAllow", () => {
+ it("stores the list once each, and refuses a list over the limit instead of cutting it", async () => {
+ const { store, bot, patch } = fixture();
+ const keys = Array.from({ length: 200 }, (_, i) => `tool_${i}`);
+ expect((await patch(bot.id, { alwaysAllow: [...keys, keys[0]] })).status).toBe(200);
+ expect(store.bot(bot.id)?.alwaysAllow).toEqual(keys);
+ const refused = await patch(bot.id, { alwaysAllow: [...keys, "tool_200"] });
+ expect(refused.status).toBe(400);
+ expect(refused.body.errorKey).toBe("serverError.bot.alwaysAllowFull");
+ expect(store.bot(bot.id)?.alwaysAllow).toEqual(keys);
+ });
+});
+
describe("PATCH /api/bots/:id phoneApps", () => {
it("stores phoneApps and clears it with null", async () => {
const { store, bot, patch } = fixture();
diff --git a/server/routes/bot-patch.ts b/server/routes/bot-patch.ts
index 2bed4c9e65..b611d1ffed 100644
--- a/server/routes/bot-patch.ts
+++ b/server/routes/bot-patch.ts
@@ -7,6 +7,7 @@ import { normalizePhoneApps } from "../../shared/phone-apps.ts";
import { parseToolScope, toolScopeWidens } from "../../shared/tool-scope.ts";
import { parseToolsOff, TOOL_GROUPS } from "../../shared/tool-groups.ts";
import { isMausColor, MAUS_COLOR_NAMES, type BotUpdateResponse, type WireBot, type WireGroup } from "../../shared/wire.ts";
+import { MAX_ALWAYS_ALLOW } from "../always-allow.ts";
import { checkBrowserProfileChange, settleBrowserChange } from "../bot-browser-profile.ts";
import { validateBotCwd } from "../bot-cwd.ts";
import { parseBotProfilePatch } from "../bot-profile.ts";
@@ -571,7 +572,11 @@ export function createBotPatchRoutes(deps: BotPatchRouteDeps): RouteHandler {
if (!Array.isArray(body.alwaysAllow) || body.alwaysAllow.some((t: unknown) => typeof t !== "string")) {
return json(res, 400, { error: "alwaysAllow must be a list of tool keys" });
}
- patch.alwaysAllow = [...new Set(body.alwaysAllow as string[])].slice(0, 200);
+ const alwaysAllow = [...new Set(body.alwaysAllow as string[])];
+ if (alwaysAllow.length > MAX_ALWAYS_ALLOW) {
+ return json(res, 400, userError("serverError.bot.alwaysAllowFull", { max: MAX_ALWAYS_ALLOW }));
+ }
+ patch.alwaysAllow = alwaysAllow;
}
// Known gap: outside the packaged desktop, loopback is the owner, so these loosenings are one curl from
// the bot they constrain. An originless, session-less loopback caller may loosen only while every bot is idle.
diff --git a/server/routes/bot-settings.ts b/server/routes/bot-settings.ts
index 8df70baf17..bcd70dfbfa 100644
--- a/server/routes/bot-settings.ts
+++ b/server/routes/bot-settings.ts
@@ -3,6 +3,7 @@ import { botAvatarUrlFromStoredPath } from "../../shared/bot-avatar.ts";
import type { CommandAllowlistResponse } from "../../shared/command-allowlist.ts";
import type { WireBot } from "../../shared/wire.ts";
import { deleteAttachment, saveImage } from "../attachments.ts";
+import { MAX_ALWAYS_ALLOW, withAlwaysAllowKey } from "../always-allow.ts";
import { avatarGenerationRequestSchema, avatarGenerationStateMatches, generateAvatarImage, snapshotAvatarGenerationState } from "../avatar-image.ts";
import { parseBotProfilePatch } from "../bot-profile.ts";
import { commandAllowlistCandidate, type CommandAllowlistStore } from "../command-allowlist.ts";
@@ -19,7 +20,7 @@ import type { ModelSelectionCheck } from "./bots-create.ts";
import { PASS, type RouteHandler } from "./table.ts";
import { pinnedClientThreadGuard } from "./pinned-client-thread.ts";
import { sawThread } from "../thread-presence.ts";
-import { refusalBody } from "../user-errors.ts";
+import { refusalBody, userError } from "../user-errors.ts";
import { readThreadNotifications, type NotificationListed } from "./notifications.ts";
export interface BotSettingsRouteDeps {
@@ -222,15 +223,16 @@ export function createBotSettingsRoutes(deps: BotSettingsRouteDeps): RouteHandle
// A standing grant is an approval: only those who may approve the card may remember it.
const refusal = cardAnswerRefusal(auth, bot.threadId, pending.card!.requestId!, "allow");
if (refusal) return json(res, 403, { error: refusal });
- const savedBot = store.bot(bot.id)!;
- store.patchBot(bot.id, {
- alwaysAllow: [...new Set([...(savedBot.alwaysAllow ?? []), allowKey])].slice(0, 200),
- });
- store.patchTask(bot.id, bot.threadId, {
- alwaysAllow: [...new Set([...(bot.alwaysAllow ?? []), allowKey])].slice(0, 200),
- });
const live = directTurnBots.get(bot.threadId);
- if (live) live.alwaysAllow = [...new Set([...(live.alwaysAllow ?? []), allowKey])].slice(0, 200);
+ const botAllow = withAlwaysAllowKey(store.bot(bot.id)!.alwaysAllow, allowKey);
+ const taskAllow = withAlwaysAllowKey(bot.alwaysAllow, allowKey);
+ const liveAllow = live ? withAlwaysAllowKey(live.alwaysAllow, allowKey) : null;
+ if (!botAllow || !taskAllow || (live && !liveAllow)) {
+ return json(res, 400, userError("serverError.bot.alwaysAllowFull", { max: MAX_ALWAYS_ALLOW }));
+ }
+ store.patchBot(bot.id, { alwaysAllow: botAllow });
+ store.patchTask(bot.id, bot.threadId, { alwaysAllow: taskAllow });
+ if (live && liveAllow) live.alwaysAllow = liveAllow;
const updated = store.bot(bot.id)!;
const visible = wireBot(updated);
broadcast({ kind: "bot", bot: visible });
diff --git a/server/user-errors.ts b/server/user-errors.ts
index 58a63a0758..1d35f3066d 100644
--- a/server/user-errors.ts
+++ b/server/user-errors.ts
@@ -200,6 +200,7 @@ export const USER_ERROR = {
"serverError.attachment.alreadyInMessage": "This file is already in a message, so it stays.",
"serverError.engine.signedOut": "{name} is signed out.",
"serverError.bot.viewOnly": "You can view {bot}, not chat with it.",
+ "serverError.bot.alwaysAllowFull": "This bot already always-allows {max} tools. Remove one under Access in its settings, then try again.",
"serverError.share.ownBot": "Chats with your own MausBot stay yours, so they can't be shared.",
"serverError.share.alreadyTeam": "This conversation is already shared with the team.",
"serverError.share.notYours": "Only the person this conversation belongs to can share it.",
diff --git a/src/locales/en.json b/src/locales/en.json
index af765bf9e1..0e74ac98ba 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -10204,6 +10204,7 @@
"time.invalid": "Invalid Date",
"shortcuts.send-follow-up": "While a bot works: queue instead of steering, or the other way round",
"serverError.bot.viewOnly": "You can view {bot}, not chat with it.",
+ "serverError.bot.alwaysAllowFull": "This bot already always-allows {max} tools. Remove one under Access in its settings, then try again.",
"serverError.share.ownBot": "Chats with your own MausBot stay yours, so they can't be shared.",
"serverError.share.alreadyTeam": "This conversation is already shared with the team.",
"serverError.share.notYours": "Only the person this conversation belongs to can share it.",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index da216e5d0f..a43dd0151c 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -10135,6 +10135,7 @@
"time.invalid": "Data inválida",
"shortcuts.send-follow-up": "Enquanto um bot trabalha: colocar na fila em vez de enviar agora, ou o contrário",
"serverError.bot.viewOnly": "Você pode ver {bot}, mas não conversar com ele.",
+ "serverError.bot.alwaysAllowFull": "Este bot já permite sempre {max} ferramentas. Remova uma em Acesso nas configurações dele e tente de novo.",
"serverError.share.ownBot": "As conversas com o seu próprio MausBot são só suas, então não podem ser compartilhadas.",
"serverError.share.alreadyTeam": "Esta conversa já está compartilhada com a equipe.",
"serverError.share.notYours": "Só a pessoa dona desta conversa pode compartilhá-la.",
diff --git a/src/locales/source-hashes.json b/src/locales/source-hashes.json
index 3230206f5d..78a9c3beb5 100644
--- a/src/locales/source-hashes.json
+++ b/src/locales/source-hashes.json
@@ -36966,7 +36966,8 @@
"remote.diagnosis.next.otherCopy": "29f59104ac96620533eecfef5e6bd7e612e84c6b2a6f71ebdb02550d4cd3518e",
"devices.computers.pairButton": "60f8288e33f9f57d2b51409fdb540b47a89c25447061bd354122442818a36ee0",
"devices.computers.pairTitle": "b7cda6a11ab410daa4b8977624ca72261c0168e7c3d83ae0eed93ac4e3540bc8",
- "devices.computers.typeCode": "2a528dfe78f6b331e8cca951872961169ca6f340a886e40e84cc0b53d441c174"
+ "devices.computers.typeCode": "2a528dfe78f6b331e8cca951872961169ca6f340a886e40e84cc0b53d441c174",
+ "serverError.bot.alwaysAllowFull": "1caf76fd33c01df36490a0cc1aeff51c85c3b6b5f3d35c5df748db434fdf15c3"
},
"zh": {
"pro.fromPrice": "a48a04a457d60b08b54fc83e7a6c4584ffedb1e23621859084900c8521a3af7b",
diff --git a/src/state/always-allow-save.test.ts b/src/state/always-allow-save.test.ts
new file mode 100644
index 0000000000..eecc204df2
--- /dev/null
+++ b/src/state/always-allow-save.test.ts
@@ -0,0 +1,95 @@
+// @vitest-environment happy-dom
+import { createElement, type Dispatch } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
+import type { Action, AppState, BotAnnouncement, Message } from "./store";
+
+class FixtureEventSource {
+ static opened: FixtureEventSource[] = [];
+ onopen: (() => void) | null = null;
+ onerror: (() => void) | null = null;
+ onmessage: ((event: { data: string; lastEventId?: string }) => void) | null = null;
+ constructor(readonly url: string) { FixtureEventSource.opened.push(this); }
+ close() {}
+ send(frame: object, id?: string) { this.onmessage?.({ data: JSON.stringify(frame), lastEventId: id }); }
+}
+
+const allowKey = "provider-tool:claude:linear:list_issues:0123456789abcdef";
+const approval: Message = {
+ id: "approval", role: "bot", kind: "options", at: 1,
+ card: { title: "Approval needed", subtitle: "list issues", options: ["Allow", "Deny"], requestId: "request-1", allowKey },
+};
+const bot: BotAnnouncement = {
+ id: "bot", threadId: "thread", name: "Fixture", title: "", description: "",
+ notifications: true, unread: false, color: "green",
+ modelSelection: { instanceId: "fake", model: "m" },
+ tasks: [{ threadId: "thread", title: "Thread", createdAt: 1 }],
+ messages: [approval],
+};
+
+let saveGrant: () => Promise<Response>;
+const writes: string[] = [];
+const json = (body: unknown, status = 200) => Promise.resolve(new Response(JSON.stringify(body), { status }));
+
+const { StoreProvider, useStore } = await import("./store");
+
+let seen!: AppState;
+let dispatch!: Dispatch<Action>;
+function Probe() {
+ ({ state: seen, dispatch } = useStore());
+ return null;
+}
+let root: Root;
+const settle = async () => { for (let i = 0; i < 5; i++) await new Promise((resolve) => setTimeout(resolve, 0)); };
+
+beforeAll(async () => {
+ vi.stubGlobal("EventSource", FixtureEventSource);
+ vi.stubGlobal("fetch", (path: string, options?: RequestInit) => {
+ if (options?.method && options.method !== "GET") writes.push(path);
+ if (path.startsWith("/api/bots?")) return json({ bots: [bot], groups: [] });
+ if (path === "/api/bots/bot/always-allow") return saveGrant();
+ if (path.endsWith("/respond")) return json({ ok: true });
+ return json({});
+ });
+ const container = document.createElement("div");
+ document.body.append(container);
+ root = createRoot(container);
+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(Probe))));
+ await settle();
+ FixtureEventSource.opened[0].send({ kind: "hello", resumed: false, cursor: "run:0" });
+ await settle();
+});
+beforeEach(() => {
+ writes.length = 0;
+ flushSync(() => dispatch({ type: "error", message: null }));
+});
+afterAll(() => {
+ root.unmount();
+ vi.unstubAllGlobals();
+});
+
+const alwaysAllow = (onError?: (message: string) => void) => flushSync(() => dispatch({
+ type: "decideRequest", threadId: "thread", requestId: "request-1", behavior: "allow",
+ alwaysAllow: { botId: "bot", key: allowKey }, onError,
+}));
+
+describe("Always allow on an approval card", () => {
+ it("saves the grant and then approves the request", async () => {
+ saveGrant = () => json({ bot });
+ alwaysAllow();
+ await settle();
+ expect(writes).toEqual(["/api/bots/bot/always-allow", "/api/threads/thread/respond"]);
+ expect(seen.error).toBeNull();
+ });
+
+ it("leaves the request waiting when the grant could not be saved", async () => {
+ saveGrant = () => json({ error: "This bot already always-allows 200 tools." }, 400);
+ const onError = vi.fn();
+ alwaysAllow(onError);
+ await settle();
+ expect(writes).toEqual(["/api/bots/bot/always-allow"]);
+ expect(seen.error).toContain("200 tools");
+ expect(onError).toHaveBeenCalledOnce();
+ });
+});
diff --git a/src/state/store.tsx b/src/state/store.tsx
index c018d808ba..a38445c4be 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -2448,15 +2448,12 @@ export function StoreProvider({ children }: { children: ReactNode }) {
const bot = stateRef.current.bots.find((candidate) => candidate.id === action.alwaysAllow?.botId);
const owner = bot?.tasks?.some((task) => task.threadId === action.threadId);
const next = [...new Set([...(bot ? currentTaskBot(bot, action.threadId).alwaysAllow ?? [] : []), action.alwaysAllow.key])];
- // Save the grant BEFORE releasing the bot: it may ask again within milliseconds.
- try {
- await api(owner ? `/api/bots/${action.alwaysAllow.botId}/always-allow` : `/api/bots/${action.alwaysAllow.botId}`, {
- method: owner ? "POST" : "PATCH",
- body: JSON.stringify(owner ? { threadId: action.threadId, allowKey: action.alwaysAllow.key } : { alwaysAllow: next }),
- });
- } catch (error) {
- showError(error);
- }
+ // Save the grant BEFORE releasing the bot: it may ask again within milliseconds. A grant that was not
+ // saved leaves the request waiting (the catch below), never allowed as if it had been remembered.
+ await api(owner ? `/api/bots/${action.alwaysAllow.botId}/always-allow` : `/api/bots/${action.alwaysAllow.botId}`, {
+ method: owner ? "POST" : "PATCH",
+ body: JSON.stringify(owner ? { threadId: action.threadId, allowKey: action.alwaysAllow.key } : { alwaysAllow: next }),
+ });
}
const response = await respond();
if (response?.settlementPending && typeof response.message === "string") {
@@ -2464,7 +2461,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
}
})
.catch((error) => {
- // A failed settings flush stops the response so work never resumes under a stale approval level.
+ // A failed settings flush or grant save stops the response so work never resumes under a stale approval level.
showError(error);
action.onError?.(error instanceof Error ? error.message : String(error));
});