Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Cloud guest: say why a waiting card needs the Cloud's owner
AdityaUmalebfc6dd8b5cde
diff --git a/server/index.ts b/server/index.tsindex ba50e85191..cf40752f13 100644--- a/server/index.ts+++ b/server/index.ts@@ -80,7 +80,7 @@ import { groupTurnCwd } from "./room-cwd.ts";import { RoomTurnDeadline, RoomTurnStallRegistry, effectiveRoomTurnTimeoutMinutes, parseConversationTurnTimeout, roomTurnTimeoutMessage } from "./room-turn-timeout.ts";import { roomTurnEnd, type RoomClaimEnd } from "./room-turn-end.ts";import { applyHoldDirective, classifyHoldDirective, heldMemberLine, rememberHeldMessage, stopWordPlacement } from "./room-holds.ts";-import { refusalBody, userError, userErrorFields, userErrorThrown } from "./user-errors.ts";+import { refusalBody, USER_ERROR, userError, userErrorFields, userErrorThrown } from "./user-errors.ts";import { chatNotice, failedNoticeTool, noticeTool, runtimeNoticeTool } from "./chat-notices.ts";import type { ServerErrorBody } from "../shared/server-text.ts";import { emailSignInRoute } from "./routes/email-sign-in.ts";@@ -1060,7 +1060,7 @@ function cloudOwnerDevice(person: string): boolean {}function cloudCardRefusal(auth: RequestAuth & { kind: "session" }): string | null {- return auth.scopes.includes("admin") ? null : "Only the owner of this Cloud can answer this card.";+ return auth.scopes.includes("admin") ? null : USER_ERROR["serverError.card.cloudOwnerOnly"];}/** Decides only whose answer to an existing card counts; it adds no card, gate or prompt. */diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.tsindex 579a5959c3..42933a05ab 100644--- a/server/routes/bot-messages.ts+++ b/server/routes/bot-messages.ts@@ -39,7 +39,7 @@ import { noteTypedSend } from "../typed-sends.ts";import { startFresh } from "../fresh-start.ts";import { parseMentionPicks } from "../../shared/room-mentions.ts";import { pinnedClientThreadGuard } from "./pinned-client-thread.ts";-import { refusalBody, userError } from "../user-errors.ts";+import { refusalBody, refusalText, userError } from "../user-errors.ts";import { PASS, type RouteHandler } from "./table.ts";type RunningInstance = ReturnType<ProviderRegistry["get"]>;@@ -576,7 +576,7 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerif (!behavior) return json(res, 400, { error: "behavior must be allow, deny, or answer" });const refusal = cardAnswerRefusal(auth, selected.threadId, String(body.requestId), behavior) ??(selected.threadId === bot.threadId ? null : cardAnswerRefusal(auth, bot.threadId, String(body.requestId), behavior));- if (refusal) return json(res, 403, { error: refusal });+ if (refusal) return json(res, 403, refusalText(refusal));if (body.rememberCommand === true) {const refusal = commandRememberRefusal(auth, bot.threadId, String(body.requestId), behavior);if (refusal) return json(res, 403, { error: refusal });@@ -647,7 +647,7 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerconst requestId = String(body.requestId);const threadId = answeredIn(m[1], requestId);const refusal = cardAnswerRefusal(auth, m[1], requestId, behavior) ?? (threadId === m[1] ? null : cardAnswerRefusal(auth, threadId, requestId, behavior));- if (refusal) return json(res, 403, { error: refusal });+ if (refusal) return json(res, 403, refusalText(refusal));if (body.rememberCommand === true) {const refusal = commandRememberRefusal(auth, threadId, requestId, behavior);if (refusal) return json(res, 403, { error: refusal });diff --git a/server/routes/bot-settings.ts b/server/routes/bot-settings.tsindex 8df70baf17..00eec47d1d 100644--- a/server/routes/bot-settings.ts+++ b/server/routes/bot-settings.ts@@ -19,7 +19,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, refusalText } from "../user-errors.ts";import { readThreadNotifications, type NotificationListed } from "./notifications.ts";export interface BotSettingsRouteDeps {@@ -221,7 +221,7 @@ 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 });+ if (refusal) return json(res, 403, refusalText(refusal));const savedBot = store.bot(bot.id)!;store.patchBot(bot.id, {alwaysAllow: [...new Set([...(savedBot.alwaysAllow ?? []), allowKey])].slice(0, 200),diff --git a/server/user-errors.test.ts b/server/user-errors.test.tsindex 966b5a32f9..715b3871de 100644--- a/server/user-errors.test.ts+++ b/server/user-errors.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";import englishCatalog from "../src/locales/en.json" with { type: "json" };import { redactSecretsInText } from "../shared/redact.ts";-import { USER_ERROR, refusalBody, userError, userErrorFields, userErrorThrown } from "./user-errors.ts";+import { USER_ERROR, refusalBody, refusalText, userError, userErrorFields, userErrorThrown } from "./user-errors.ts";describe("user errors", () => {it("the catalog's server errors are exactly the ones the server sends", () => {@@ -51,4 +51,12 @@ describe("user errors", () => {const thrown = Object.assign(new Error("x"), { errorKey: "serverError.chat.busyInRoom", errorParams: { room: "Launch" } });expect(userErrorFields(thrown)).toEqual({ errorKey: "serverError.chat.busyInRoom", errorParams: { room: "Launch" } });});++ it("a guest pressing a card on someone's My Cloud is told in their own language why only the owner answers it", () => {+ expect(refusalText(USER_ERROR["serverError.card.cloudOwnerOnly"])).toEqual({+ error: "Only the owner of this Cloud can answer this card. Chats started by other people always ask the owner first, whatever the bot's access level.",+ errorKey: "serverError.card.cloudOwnerOnly",+ });+ expect(refusalText("Only a workspace admin can review shared team memory.")).toEqual({ error: "Only a workspace admin can review shared team memory." });+ });});diff --git a/server/user-errors.ts b/server/user-errors.tsindex 58a63a0758..818659c7cb 100644--- a/server/user-errors.ts+++ b/server/user-errors.ts@@ -186,6 +186,7 @@ export const USER_ERROR = {"serverError.postiz.addressAsText": "Send the Postiz address as text.","serverError.secret.localService": "A local service cannot enter a secret. Enter it in OpenMausBot.","serverError.secret.cloudOwnerOnly": "Only the owner of this Cloud can enter this secret.",+ "serverError.card.cloudOwnerOnly": "Only the owner of this Cloud can answer this card. Chats started by other people always ask the owner first, whatever the bot's access level.","serverError.secret.conversationOwnerOnly": "Only the person this conversation belongs to can enter this secret.","serverError.secret.credentialSavingFromPhone": "this credential is currently being saved from a phone","serverError.secret.credentialDismissed": "this credential request was dismissed",@@ -246,6 +247,12 @@ export function userErrorFields(value: unknown): Pick<ServerErrorBody, "errorKeyreturn { errorKey, ...(params ? { errorParams: params } : {}) };}+/** A refusal another module words in English, with its language-pack key when it is one of these lines word for word. */+export function refusalText(error: string): ServerErrorBody {+ const key = (Object.keys(USER_ERROR) as UserErrorKey[]).find((candidate) => USER_ERROR[candidate] === error);+ return key ? userError(key) : { error };+}+export function refusalBody(refusal: { error: string; errorKey?: string; errorParams?: ServerTextParams }): ServerErrorBody {return { error: refusal.error, ...userErrorFields(refusal) };}diff --git a/src/components/ApprovalCard.cloud-guest.dom.test.ts b/src/components/ApprovalCard.cloud-guest.dom.test.tsnew file mode 100644index 0000000000..94aef61753--- /dev/null+++ b/src/components/ApprovalCard.cloud-guest.dom.test.ts@@ -0,0 +1,50 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { setLocale } from "@/lib/i18n";+import type { Message } from "@/state/store";++const session = vi.hoisted(() => ({ state: null as unknown }));+vi.mock("@/lib/session", async (original) => ({ ...await original<typeof import("@/lib/session")>(), readSessionState: async () => session.state }));++// A browser tool call waiting for an answer in a chat, as the guest's and the owner's devices draw it.+const waiting: Message = {+ id: "browser-card", role: "bot", kind: "options", at: 1,+ card: { title: "Approval needed", subtitle: "agent_browser_status", options: ["Allow", "Deny"], requestId: "r1", tool: "mcp__browser__agent_browser_status" },+};+const GUEST = { kind: "session", id: "s1", label: "Guest phone", scopes: ["client"], expiresAt: 1, cloudGuest: true, openedThreads: ["t1"] };+const OWNER = { kind: "session", id: "s2", label: "Mac", scopes: ["admin", "client"], expiresAt: 1 };+const NOTE = "The owner of this Cloud has to approve this.";++let container: HTMLDivElement, root: Root;+beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ setLocale("en");+ container = document.createElement("div"); document.body.append(container); root = createRoot(container);+});+afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.unstubAllGlobals(); vi.resetModules(); });++async function shown(state: unknown, message: Message = waiting): Promise<string> {+ session.state = state;+ const { ApprovalCard } = await import("./ApprovalCard");+ await act(async () => { root.render(createElement(ApprovalCard, { message, threadId: "t1" })); });+ for (let i = 0; i < 4; i++) await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); });+ return container.textContent ?? "";+}++describe("a waiting card on someone's My Cloud", () => {+ it("tells a guest the Cloud's owner has to approve it, and why", async () => {+ const text = await shown(GUEST);+ expect(text).toContain(NOTE);+ expect(text).toContain("whatever the bot's access level, because the bot uses the owner's browser and sign-ins");+ });++ it("shows the owner the card as before", async () => {+ expect(await shown(OWNER)).not.toContain(NOTE);+ });++ it("adds nothing once the card is answered", async () => {+ expect(await shown(GUEST, { ...waiting, card: { ...waiting.card!, answered: "allow" } })).not.toContain(NOTE);+ });+});diff --git a/src/components/ApprovalCard.tsx b/src/components/ApprovalCard.tsxindex fcd297541b..2d76c95abf 100644--- a/src/components/ApprovalCard.tsx+++ b/src/components/ApprovalCard.tsx@@ -15,6 +15,7 @@ import type { RoutineRequestSchedule } from "../../shared/routine-request";import { isSkillSwitchAction, type SkillShareRecord } from "../../shared/skill-request";import { cardAutomation } from "@/lib/automations";import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";+import { useCloudGuest } from "@/lib/cloud-guest";import { yourComputerAsk } from "@/lib/your-computer";import { computerAskWords } from "@/lib/computer-ask";import { mcpRequestActionLabel } from "@/lib/mcp-request-label";@@ -439,6 +440,13 @@ function CompactApprovalRow({);}+/** A guest on someone's My Cloud sees why the card waits: only that Cloud's owner may answer it. `guest` overrides the session. */+export function CloudGuestApprovalNote({ guest, className }: { guest?: boolean; className?: string }) {+ const known = useCloudGuest();+ if (!(guest ?? known)) return null;+ return <p data-cloud-guest-note className={cn("text-[13px] text-ink-secondary", className)}>{t("chat.cloudGuest.ownerApproves")}</p>;+}+export function ApprovalCard({bot,message,@@ -520,7 +528,7 @@ export function ApprovalCard({answeredBelow={Boolean(card.requestId && card.tool && !card.dismissed)}/>);- return waiting && card.requestId && card.tool ? <div className="flex w-full flex-col gap-1">{row}<CardHint id="spot.approval" /></div> : row;+ return waiting && card.requestId && card.tool ? <div className="flex w-full flex-col gap-1">{row}<CloudGuestApprovalNote /><CardHint id="spot.approval" /></div> : row;}return (@@ -584,6 +592,7 @@ export function ApprovalCard({</>)}</div>+ {!outcome && <CloudGuestApprovalNote className="mt-2" />}</div>);}diff --git a/src/lib/cloud-guest.ts b/src/lib/cloud-guest.tsindex 1bed6a564c..2a7bf39807 100644--- a/src/lib/cloud-guest.ts+++ b/src/lib/cloud-guest.ts@@ -52,3 +52,18 @@ export function currentReactor(): string {export function useReactor(): string {return useSyncExternalStore(subscribeReactor, () => reactor, () => "user");}++/** True once the server says this device is a guest on someone's My Cloud; false for its owner and everywhere else. */+export function useCloudGuest(): boolean {+ const [guest, setGuest] = useState(false);+ useEffect(() => {+ let alive = true;+ void read().then((state) => {+ if (alive) setGuest(state?.kind === "session" && state.cloudGuest === true);+ });+ return () => {+ alive = false;+ };+ }, []);+ return guest;+}diff --git a/src/locales/en.json b/src/locales/en.jsonindex af765bf9e1..5285b03432 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -2641,6 +2641,7 @@"error.plain.generic": "Something went wrong. Try again.","chat.cloudGuest.notYours": "You can only write in conversations you started on this Cloud.","chat.cloudGuest.newConversation": "New conversation",+ "chat.cloudGuest.ownerApproves": "The owner of this Cloud has to approve this. Chats started by other people always ask first, whatever the bot's access level, because the bot uses the owner's browser and sign-ins.","chat.claudeUpdate.aria": "Update Claude Code","chat.claudeUpdate.offer": "This model needs a newer Claude Code. I can update Claude for you.","chat.claudeUpdate.doIt": "Update Claude for me",@@ -10054,6 +10055,7 @@"serverError.postiz.addressAsText": "Send the Postiz address as text.","serverError.secret.localService": "A local service cannot enter a secret. Enter it in OpenMausBot.","serverError.secret.cloudOwnerOnly": "Only the owner of this Cloud can enter this secret.",+ "serverError.card.cloudOwnerOnly": "Only the owner of this Cloud can answer this card. Chats started by other people always ask the owner first, whatever the bot's access level.","serverError.secret.conversationOwnerOnly": "Only the person this conversation belongs to can enter this secret.","serverError.secret.credentialSavingFromPhone": "this credential is currently being saved from a phone","serverError.secret.credentialDismissed": "this credential request was dismissed",