Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Move from Grok Bot: a Connect Grok Bot section that lists the Bots as they arrive
aivsomkarca8c34dd417f
diff --git a/src/components/GrokMoveDialog.test.ts b/src/components/GrokMoveDialog.test.tsindex 0db459d9ad..df20e3055a 100644--- a/src/components/GrokMoveDialog.test.ts+++ b/src/components/GrokMoveDialog.test.ts@@ -162,7 +162,8 @@ describe("Move from Grok Bot", () => {it("reads nothing on this computer from a browser or a Cloud", async () => {await open();- expect(f.api.mock.calls.map(([path]) => path)).not.toContain("/api/setup-import/grok");+ expect(f.api.mock.calls.map(([path]) => path).filter((path) => String(path).startsWith("/api/setup-import/grok"))).toEqual([]);+ expect(host.querySelector("[data-grok-move-connect]")).toBeNull();});it("on the desktop app looks once it is open, and offers what it found in one tap", async () => {@@ -178,6 +179,99 @@ describe("Move from Grok Bot", () => {expect(host.querySelector('[data-grok-move="preview"]')).not.toBeNull();});+ it("on the desktop app gives a link for Grok Bot, shows the Bots that arrive through it, and ends the link once they are imported", async () => {+ vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });+ const openExternal = vi.fn();+ vi.stubGlobal("ogb", { remoteClient: { active: false }, openExternal });+ const link = "https://quiet-test-words.trycloudflare.com/mcp/move/abc";+ let made = false, sent = false;+ const calls: string[] = [];+ f.api.mockImplementation(async (path: string, init?: { method?: string }) => {+ if (path.startsWith("/api/setup-import/grok/connector")) {+ calls.push(`${init?.method} ${path}`);+ if (init?.method === "POST") made = true;+ if (init?.method === "DELETE") made = false;+ const after = Number(new URL(path, "http://x").searchParams.get("after") ?? 0);+ return { available: true, ...(made ? { connectorUrl: link } : {}), arrived: made && sent && after < 1 ? [{ seq: 1, at: 5, text: EXPORT }] : [] };+ }+ return path.startsWith("/api/teams/import")+ ? { bots: [{ id: "b1", name: "Job Search", threadId: "t1" }], routines: [], connections: [] }+ : path === "/api/mcp/servers" ? { servers: [] } : {};+ });+ await open();+ expect(shown()).toContain("Connect Grok Bot");+ expect(shown()).not.toContain("Add a custom connector");+ await act(async () => button("Get the link")!.click());+ await tick();+ expect(host.querySelector<HTMLInputElement>('input[aria-label="Link for Grok Bot"]')!.value).toBe(link);+ expect(shown()).toContain("open Connect apps, choose Add a custom connector at the bottom, name it MausBot, paste this as the Server URL, then choose Add plugin");+ await act(async () => button("Add the MausBot bot in Grok Bot")!.click());+ expect(openExternal).toHaveBeenCalledWith("https://x.ai/bot/3i4Tvjckmdk05UwntFeNo");+ expect(host.querySelector("[data-grok-move-arrived]")).toBeNull();++ sent = true;+ await act(async () => { vi.advanceTimersByTime(3_000); });+ await tick();+ expect(shown()).toContain("Arrived from Grok Bot: Job Search");+ expect(shown()).toContain("The link works for an hour, while MausBot stays open.");+ await act(async () => { vi.advanceTimersByTime(3_000); });+ await tick();+ expect(calls.at(-1)).toBe("GET /api/setup-import/grok/connector?after=1");+ expect(shown().match(/Arrived from Grok Bot/g)).toHaveLength(1);++ await act(async () => host.querySelector<HTMLButtonElement>("[data-grok-move-use-arrived]")!.click());+ await tick();+ expect(host.querySelector('[data-grok-move="preview"]')).not.toBeNull();+ expect(counts()).toMatchObject({ Skills: 2, Routines: 1 });+ await importIt();+ expect(shown()).toContain("Job Search is here");+ expect(calls.at(-1)).toBe("DELETE /api/setup-import/grok/connector");+ vi.useRealTimers();+ });++ it("says when the link stopped, keeps the Bots that had arrived, and offers a new link", async () => {+ vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] });+ vi.stubGlobal("ogb", { remoteClient: { active: false } });+ let stopped = false;+ f.api.mockImplementation(async (path: string) => {+ if (!path.startsWith("/api/setup-import/grok/connector")) return path === "/api/mcp/servers" ? { servers: [] } : {};+ const after = Number(new URL(path, "http://x").searchParams.get("after") ?? 0);+ return { available: true, ...(stopped ? { stopped: true } : { connectorUrl: "https://quiet-test-words.trycloudflare.com/mcp/move/abc" }), arrived: after < 1 ? [{ seq: 1, at: 5, text: EXPORT }] : [] };+ });+ await open();+ expect(shown()).toContain("Arrived from Grok Bot: Job Search");+ expect(host.querySelector("[data-grok-move-stopped]")).toBeNull();+ stopped = true;+ await act(async () => { vi.advanceTimersByTime(3_000); });+ await tick();+ expect(host.querySelector("[data-grok-move-stopped]")?.textContent).toBe("The link stopped working. Get a new one and paste it into Grok Bot in place of the old one.");+ expect(host.querySelector('input[aria-label="Link for Grok Bot"]')).toBeNull();+ expect(button("Get the link")).toBeDefined();+ expect(shown().match(/Arrived from Grok Bot: Job Search/g)).toHaveLength(1);+ await act(async () => host.querySelector<HTMLButtonElement>("[data-grok-move-use-arrived]")!.click());+ await tick();+ expect(host.querySelector('[data-grok-move="preview"]')).not.toBeNull();+ vi.useRealTimers();+ });++ it("offers no link where the app cannot make one, and says so when making it fails", async () => {+ vi.stubGlobal("ogb", { remoteClient: { active: false } });+ await open();+ expect(host.querySelector("[data-grok-move-connect]")).toBeNull();+ await act(async () => root.unmount());+ root = createRoot(host);++ f.api.mockImplementation(async (path: string, init?: { method?: string }) => {+ if (path.startsWith("/api/setup-import/grok/connector") && init?.method === "POST") throw new Error("502");+ return path.startsWith("/api/setup-import/grok/connector") ? { available: true, arrived: [] } : {};+ });+ await open();+ await act(async () => button("Get the link")!.click());+ await tick();+ expect(host.querySelector('[data-grok-move-connect] [role="alert"]')?.textContent).toBe("Couldn't make the link. Check that you're online and try again.");+ expect(button("Get the link")).toBeDefined();+ });+it("inside Settings it opens in place, with no overlay to end up behind the Settings window", async () => {await act(async () => root.render(createElement(GrokMoveDialog, { onClose: vi.fn(), inline: true })));await tick();diff --git a/src/components/GrokMoveDialog.tsx b/src/components/GrokMoveDialog.tsxindex 64abdad937..caf337f17e 100644--- a/src/components/GrokMoveDialog.tsx+++ b/src/components/GrokMoveDialog.tsx@@ -1,10 +1,11 @@-import { Check, Copy, FileUp, Loader2, X } from "lucide-react";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { Check, Copy, ExternalLink, FileUp, Loader2, X } from "lucide-react";+import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from "react";import { track } from "@/lib/analytics";+import { openExternalLink } from "@/lib/app-links";import { cn } from "@/lib/cn";import { useCopyFeedback } from "@/lib/copy-text";-import { foundExports, grokErrorText, lookForGrokBot, NOTHING_FOUND, previewGrokMove, runGrokMove, type GrokLook, type GrokPreview, type GrokReport } from "@/lib/grok-move";+import { foundExports, grokConnector, grokErrorText, lookForGrokBot, MAUSBOT_GROK_TEMPLATE_URL, NOTHING_FOUND, previewGrokMove, runGrokMove, type GrokConnector, type GrokLook, type GrokPreview, type GrokReport } from "@/lib/grok-move";import { t } from "@/lib/i18n";import { localSetupImport } from "@/lib/setup-import";import { api, useStore } from "@/state/store";@@ -49,7 +50,57 @@ export function GrokMoveLines({ paused, files = null, apps, moved, unreadable, freturn lines.length > 0 && <div className="flex flex-col gap-1">{lines.map((line) => <p key={line} className={LINE}>{line}</p>)}</div>;}-function BringBack({ local, look, found, reply, error, onReply, onFile, onFound }: {+const NO_CONNECTOR: Pick<GrokConnector, "available" | "connectorUrl" | "stopped"> = { available: false, stopped: false };+const POLL_MS = 3_000;++/** The other way over: a link Grok Bot is given once, which the MausBot bot there sends every Bot through. */+function ConnectGrokBot({ url, stopped, names, error, busy, onConnect, onUse }: {+ url: string | undefined; stopped: boolean; names: readonly string[]; error: boolean; busy: boolean; onConnect: () => void; onUse: () => void;+}) {+ const arrived = names.length > 0 && (+ <div data-grok-move-arrived role="status" className="mt-1 flex w-full items-center justify-between gap-3 rounded-xl border border-accent/40 bg-accent/[0.06] px-3 py-2">+ <span className="min-w-0 break-words text-[13px] text-ink">{t("grokMove.connect.arrived", { names: names.join(", ") })}</span>+ <button type="button" data-grok-move-use-arrived onClick={onUse} className={cn(PRIMARY, "shrink-0")}>{t("grokMove.useFound")}</button>+ </div>+ );+ const { state: copied, copy } = useCopyFeedback(url ?? "");+ return (+ <section data-grok-move-connect className="flex flex-col items-start gap-1.5">+ <h3 className="text-[14px] font-medium text-ink">{t("grokMove.connect.title")}</h3>+ <p className={LINE}>{t("grokMove.connect.hint")}</p>+ {url ? (+ <>+ <div className="mt-1 flex w-full items-center gap-2">+ <input readOnly value={url} aria-label={t("grokMove.connect.linkLabel")} onFocus={(event) => event.target.select()}+ className="min-w-0 flex-1 rounded-xl border border-hairline/40 bg-inset px-3 py-2 font-mono text-[12px] text-ink focus:outline-none" />+ <button type="button" data-grok-move-copy-link onClick={copy} className={cn(SECONDARY, "inline-flex shrink-0 items-center gap-2")}>+ {copied === "copied" ? <Check size={15} /> : <Copy size={15} />}+ {copied === "copied" ? t("grokMove.copied") : copied === "failed" ? t("grokMove.copyFailed") : t("grokMove.connect.copy")}+ </button>+ </div>+ <p className={LINE}>{t("grokMove.connect.where")}</p>+ <p className={LINE}>{t("grokMove.connect.private")}</p>+ <button type="button" data-grok-move-template onClick={() => void openExternalLink(MAUSBOT_GROK_TEMPLATE_URL)} className={cn(SECONDARY, "mt-1 inline-flex items-center gap-2")}>+ <ExternalLink size={15} />{t("grokMove.connect.addBot")}+ </button>+ {arrived}+ </>+ ) : (+ <>+ {stopped && <p role="status" data-grok-move-stopped className={LINE}>{t("grokMove.connect.stopped")}</p>}+ {arrived}+ <button type="button" data-grok-move-connect-start disabled={busy} onClick={onConnect} className={cn(SECONDARY, "mt-1 inline-flex items-center gap-2")}>+ {busy && <Loader2 size={15} className="animate-spin" />}{t("grokMove.connect.start")}+ </button>+ </>+ )}+ {error && <p role="alert" className="text-[13px] leading-relaxed text-danger">{t("grokMove.connect.failed")}</p>}+ </section>+ );+}++function BringBack({ connect, local, look, found, reply, error, onReply, onFile, onFound }: {+ connect: ReactNode;local: boolean;look: GrokLook;found: ReturnType<typeof foundExports>;@@ -64,6 +115,7 @@ function BringBack({ local, look, found, reply, error, onReply, onFile, onFoundreturn (<><p className="text-[13px] leading-relaxed text-ink-secondary">{t("grokMove.intro")}</p>+ {connect}<section className="flex flex-col items-start gap-1.5"><h3 className="text-[14px] font-medium text-ink">{t("grokMove.step1")}</h3><p className="text-[13px] leading-relaxed text-ink-secondary">{t("grokMove.step1Hint")}</p>@@ -121,9 +173,46 @@ export function GrokMoveDialog({ onClose, inline = false }: { onClose: () => voiconst found = useMemo(() => foundExports(look.files), [look.files]);- const show = async (read: () => GrokBot[]) => {+ const onStart = !preview && !report;+ const [connector, setConnector] = useState(NO_CONNECTOR);+ const [arrivedFiles, setArrivedFiles] = useState<GrokLook["files"]>([]);+ const [connecting, setConnecting] = useState(false);+ const [connectFailed, setConnectFailed] = useState(false);+ const lastSeq = useRef(0);+ /** The Bots in the preview came through the link, so a finished import ends it. */+ const viaLink = useRef(false);+ const arrived = useMemo(() => foundExports(arrivedFiles).bots, [arrivedFiles]);+ const takeConnector = useCallback((next: GrokConnector) => {+ setConnector({ available: next.available, stopped: next.stopped, ...(next.connectorUrl ? { connectorUrl: next.connectorUrl } : {}) });+ if (!next.connectorUrl && !next.stopped) {+ lastSeq.current = 0;+ setArrivedFiles([]);+ } else if (next.seq > lastSeq.current) {+ // Two looks may overlap: each arrival is taken once.+ const fresh = next.arrived.filter((file) => Number(file.name) > lastSeq.current);+ lastSeq.current = next.seq;+ setArrivedFiles((files) => [...files, ...fresh]);+ }+ }, []);+ useEffect(() => {+ if (local) void grokConnector("GET").then(takeConnector, () => {});+ }, [local, takeConnector]);+ useEffect(() => {+ if (!connector.connectorUrl || !onStart) return;+ const timer = setInterval(() => void grokConnector("GET", lastSeq.current).then(takeConnector, () => {}), POLL_MS);+ return () => clearInterval(timer);+ }, [connector.connectorUrl, onStart, takeConnector]);+ const connect = async () => {+ setConnecting(true);+ setConnectFailed(false);+ await grokConnector("POST").then(takeConnector, () => setConnectFailed(true));+ setConnecting(false);+ };++ const show = async (read: () => GrokBot[], fromLink = false) => {try {const bots = read();+ viaLink.current = fromLink;const servers = await api<{ servers?: Array<{ name: string }> }>("/api/mcp/servers").then((answer) => answer.servers ?? [], () => []);setPreview(previewGrokMove(bots, { bots: state.bots, servers: new Set(servers.map((server) => server.name)), timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone }));setError("");@@ -138,7 +227,6 @@ export function GrokMoveDialog({ onClose, inline = false }: { onClose: () => voiif (file.size > GROK_EXPORT_MAX_CHARS) return setError(t("grokMove.error.tooLarge"));void file.text().then((text) => show(() => parseGrokExport(text)));};- const onStart = !preview && !report;// The chat box behind this dialog attaches any file dropped on the window, and one Send would hand a private export to its// model. So nothing behind the dialog sees a drag, on any step, and only the first step reads what was dropped.useEffect(() => {@@ -162,6 +250,10 @@ export function GrokMoveDialog({ onClose, inline = false }: { onClose: () => voisetImporting(true);const done = await runGrokMove(preview, dispatch);track("team_imported", { members: preview.plans.length, source: "grok", mode: "add", format: "package" });+ if (viaLink.current && done.bots.length > 0 && done.failed.length === 0) {+ // Best effort: a link left behind stops working on its own within the hour.+ void grokConnector("DELETE").then(takeConnector, () => {});+ }setReport(done);setPreview(null);setImporting(false);@@ -211,7 +303,11 @@ export function GrokMoveDialog({ onClose, inline = false }: { onClose: () => voi</>) : (<BringBack local={local} look={look} found={found} reply={reply} error={error} onReply={setReply}- onFile={(file) => readFile.current(file)} onFound={() => void show(() => found.bots)} />+ onFile={(file) => readFile.current(file)} onFound={() => void show(() => found.bots)}+ connect={local && connector.available && (+ <ConnectGrokBot url={connector.connectorUrl} stopped={connector.stopped} names={arrived.map((bot) => bot.name)} error={connectFailed} busy={connecting}+ onConnect={() => void connect()} onUse={() => void show(() => arrived, true)} />+ )} />)}</div><div className="ui-modal-divider shrink-0" />diff --git a/src/lib/grok-move.ts b/src/lib/grok-move.tsindex cc73b5b1b9..87dfc12822 100644--- a/src/lib/grok-move.ts+++ b/src/lib/grok-move.ts@@ -20,6 +20,36 @@ export function lookForGrokBot(): Promise<GrokLook> {);}+/** The MausBot bot in Grok Bot: it sends each Bot's setup to the link below. */+export const MAUSBOT_GROK_TEMPLATE_URL = "https://x.ai/bot/3i4Tvjckmdk05UwntFeNo";++/** The link Grok Bot sends Bots to, when this app can make one, and what arrived through it. */+export interface GrokConnector {+ available: boolean;+ connectorUrl?: string;+ /** The link was made and no longer works; what arrived through it is still here. */+ stopped: boolean;+ arrived: GrokLook["files"];+ /** The last arrival's number: the next look asks for what came after it. */+ seq: number;+}++/** POST opens the link (or gives the one already open; a new one takes a few seconds), GET looks for what arrived after `after`, DELETE ends it. */+export async function grokConnector(method: "GET" | "POST" | "DELETE", after = 0): Promise<GrokConnector> {+ const answer = await api<{ available?: boolean; connectorUrl?: string; stopped?: boolean; arrived?: Array<{ seq: number; at: number; text: string }> } | null>(+ `/api/setup-import/grok/connector${method === "GET" && after ? `?after=${after}` : ""}`,+ { method, timeoutMs: 60_000, ...(method === "POST" ? { body: "{}" } : {}) },+ );+ const arrived = Array.isArray(answer?.arrived) ? answer.arrived : [];+ return {+ available: answer?.available === true,+ ...(typeof answer?.connectorUrl === "string" ? { connectorUrl: answer.connectorUrl } : {}),+ stopped: answer?.stopped === true,+ arrived: arrived.map((item) => ({ name: String(item.seq), modifiedAt: item.at, text: item.text })),+ seq: arrived.reduce((last, item) => Math.max(last, item.seq), after),+ };+}+/** A refusal or an unreadable reply, in the person's words. */export function grokErrorText(cause: unknown): string {if (!(cause instanceof GrokImportError)) return cause instanceof Error ? cause.message : String(cause);diff --git a/src/locales/en.json b/src/locales/en.jsonindex d480e9c506..c815d7ef0f 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -8202,6 +8202,17 @@"botApi.password": "A key is like a password: whoever holds it can read what this bot can read.","botApi.cantTake": "This bot's AI can't take Bot API calls. Choose another AI to use them.","grokMove.intro": "Grok Bot has no export button, so each Bot writes down its own setup. Nothing changes in Grok Bot.",+ "grokMove.connect.title": "Connect Grok Bot",+ "grokMove.connect.hint": "Your Bots send their own setup here, all in one go. Or use the two steps below.",+ "grokMove.connect.start": "Get the link",+ "grokMove.connect.linkLabel": "Link for Grok Bot",+ "grokMove.connect.copy": "Copy the link",+ "grokMove.connect.where": "In Grok Bot, open Connect apps, choose Add a custom connector at the bottom, name it MausBot, paste this as the Server URL, then choose Add plugin. Then add the MausBot bot and ask it to move your Bots.",+ "grokMove.connect.private": "The link works for an hour, while MausBot stays open. It goes through Cloudflare to this computer and nothing is stored anywhere else. Anyone who has it can send Bots here, so keep it to yourself.",+ "grokMove.connect.stopped": "The link stopped working. Get a new one and paste it into Grok Bot in place of the old one.",+ "grokMove.connect.addBot": "Add the MausBot bot in Grok Bot",+ "grokMove.connect.arrived": "Arrived from Grok Bot: {names}",+ "grokMove.connect.failed": "Couldn't make the link. Check that you're online and try again.","grokMove.step1": "1. Send your Bot this message","grokMove.step1Hint": "Copy it and send it in your Bot's chat. Do this once per Bot.","grokMove.roster": "Your Bots on this computer: {names}",diff --git a/src/locales/everyday-words.test.ts b/src/locales/everyday-words.test.tsindex 9d937beeb8..6de2edbb77 100644--- a/src/locales/everyday-words.test.ts+++ b/src/locales/everyday-words.test.ts@@ -84,6 +84,7 @@ const PENDING_WORDS: readonly Word[] = [];const ALLOWED: Record<string, string> = {+ "grokMove.connect.where": "names the Server URL field of Grok Bot's own form, where the link is pasted","sidebar.servers": "the switcher's own Servers list, renamed with the one-workspace switcher","sidebar.switchServer": "the switcher's own Servers list, renamed with the one-workspace switcher","sidebar.switchServerError": "points at the app menu's Server menu",