Skip to content

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

7.4 KB
Raw Blame
// Dev-only: the Boat row of Settings → AI → Other services (the real Settings) and the computer panel's key card,
// against made-up answers, served at /boat-sign-in-preview.html; not in the packaged app. Every request is answered here.
// ?view=settings|panel&state=none|waiting|connected|both-sign-in|both-key|missing|ended|cancelled|refused|key|hosted|server
//  &skin=midnight|daylight&lang=pt-br
// Sign-in is offered only on the desktop app's own ports, so serve this page on one of them to see it
// (pnpm dev --port 18799 --strictPort); on any other port every state shows the key field alone, as a self-hosted server does.
import { StrictMode, useEffect } from "react";
import { createRoot } from "react-dom/client";
import type { BoatSignInStatus } from "../shared/boat-sign-in";
import "./styles.css";

const params = new URLSearchParams(location.search);
const view = params.get("view") ?? "settings";
const state = params.get("state") ?? "none";

const ALL = { available: true, keySaved: false } as const;
const SIGN_IN: Record<string, BoatSignInStatus | undefined> = {
  none: { ...ALL, state: "none" },
  waiting: { ...ALL, state: "none", pending: true },
  connected: { ...ALL, state: "connected", account: "[email protected]", missingScopes: [], used: true, last: { outcome: "connected" } },
  "both-sign-in": { available: true, keySaved: true, state: "connected", account: "[email protected]", missingScopes: [], used: true },
  "both-key": { available: true, keySaved: true, state: "connected", account: "[email protected]", missingScopes: [], used: false },
  missing: { ...ALL, state: "connected", account: "[email protected]", missingScopes: ["sandbox.create", "desktop"], used: true },
  ended: { ...ALL, state: "needs-sign-in", missingScopes: [], used: true },
  cancelled: { ...ALL, state: "none", last: { outcome: "cancelled" } },
  refused: { ...ALL, state: "none", last: { outcome: "refused" } },
  key: { available: true, keySaved: true, state: "none" },
  // A self-hosted server and a hosted Cloud say nothing about sign-in.
  server: undefined,
  hosted: undefined,
};
const signIn = SIGN_IN[state];
const keySaved = signIn?.keySaved === true || state === "server-key";
const box = state === "hosted"
  ? { configured: true, included: true, keySaved: false }
  : { configured: keySaved || signIn?.state === "connected" || signIn?.state === "needs-sign-in", ...(keySaved ? { last4: "c3d4" } : {}), keySaved, ...(signIn ? { signIn } : {}) };

const CONFIG = {
  composio: { configured: false }, box, vps: { configured: false, sshAlias: "" },
  rooms: { turnTimeoutMinutes: 10 }, localVm: { mode: "shared", maxInstances: 1 },
  profile: { name: "Maya Shah", email: "[email protected]" }, features: { savedSteps: false },
  onboarding: { completedAt: "2026-01-01", version: 1, reelSeen: true, hintsSeen: [] },
  edition: { edition: "community", features: [] }, browserProfiles: [], managedPolicy: null,
  signIn: { admins: [], members: [] }, membership: { authority: "local", pairingCodes: true }, cloudHome: state === "hosted",
};
const ANSWERS: Record<string, unknown> = {
  "/api/instances": { instances: [] }, "/api/config": CONFIG,
  "/api/auth/session": { kind: "session", id: "s1", label: "Chrome on Mac", email: "[email protected]", scopes: ["admin", "client"], expiresAt: 0 },
  "/api/auth/sessions": { sessions: [{ id: "s1" }], current: "s1" }, "/api/routines": { routines: [], runs: [] }, "/api/webhooks": { webhooks: [], attempts: [] },
  "/api/bots": { bots: [{ id: "chief", name: "Chief", threadId: "t-chief" }], groups: [] },
};
const realFetch = window.fetch.bind(window);
window.fetch = (input: RequestInfo | URL, init?: RequestInit) => {
  const url = new URL(String(input instanceof Request ? input.url : input), location.href);
  if (url.origin !== location.origin || !url.pathname.startsWith("/api/")) return realFetch(input, init);
  // Nothing here signs in: the buttons are answered with a refusal so no browser page is ever opened.
  if (url.pathname.startsWith("/api/boat/sign-in")) return Promise.resolve(new Response(JSON.stringify({ error: "This is a preview." }), { status: 503, headers: { "content-type": "application/json" } }));
  return Promise.resolve(new Response(JSON.stringify(ANSWERS[url.pathname] ?? {}), { headers: { "content-type": "application/json" } }));
};
class QuietEventSource {
  onopen: (() => void) | null = null; onerror: (() => void) | null = null; onmessage: ((event: { data: string }) => void) | null = null;
  readyState = 1;
  constructor(readonly url: string) { setTimeout(() => this.onmessage?.({ data: JSON.stringify({ kind: "hello", resumed: false, cursor: "run:0" }) }), 50); }
  addEventListener() {} removeEventListener() {} close() {}
}
Object.assign(window, { EventSource: QuietEventSource });
try { localStorage.setItem("omb-advanced-mode", "0"); } catch { /* blocked storage */ }

const [{ StoreProvider }, { useStoreDispatch, useStoreSelector }, { SettingsModal }, { KeyRow }, { requestKeyFocus }, { applySkin, readSkin, SKIN_IDS }, { loadLocale }] = await Promise.all([
  import("@/state/store"), import("@/state/store-select"), import("@/components/SettingsModal"), import("@/components/keys/KeyRow"), import("@/components/keys/key-focus"),
  import("@/lib/skins"), import("@/lib/i18n"),
]);

function SettingsView() {
  const loaded = useStoreSelector((app) => app.config !== null), open = useStoreSelector((app) => app.appSettingsOpen), dispatch = useStoreDispatch();
  useEffect(() => {
    if (!loaded) return;
    dispatch({ type: "toggleAppSettings", open: true, section: "ai" });
  }, [loaded, dispatch]);
  return open ? <SettingsModal /> : null;
}

/** The card the computer panel shows when a cloud desktop has no Boat account yet, at the panel's width. */
function PanelView() {
  const loaded = useStoreSelector((app) => app.config !== null);
  if (!loaded) return <div className="h-screen bg-app" />;
  return (
    <div className="flex min-h-screen justify-center bg-app px-4 py-10 text-ink">
      <div className="w-full max-w-[420px]">
        <div data-boat-key className="mt-3 rounded-xl bg-card py-1.5"><KeyRow id="box" via="computer_panel" /></div>
      </div>
    </div>
  );
}

/** The pictures are taken once the Boat row is in view: in Settings that means opening Other services first, as a person does. */
function markReady() {
  const started = Date.now();
  let asked = false;
  const timer = setInterval(() => {
    const fold = document.querySelector<HTMLButtonElement>("[data-settings-disclosure='ai-other-services'] button[aria-expanded='false']");
    if (fold) fold.click();
    const page = document.querySelector("[data-keys-page]");
    if (page && !asked) { asked = true; requestKeyFocus("box"); }
    const row = document.querySelector<HTMLElement>("[data-key-row='box']");
    const settled = row && !row.hasAttribute("data-key-highlight") && Date.now() - started > 2_500;
    if (settled || Date.now() - started > 9_000) {
      clearInterval(timer);
      row?.scrollIntoView({ block: "center" });
      requestAnimationFrame(() => document.body.setAttribute("data-preview-ready", ""));
    }
  }, 150);
}
markReady();

const asked = params.get("skin");
applySkin((SKIN_IDS as readonly string[]).includes(asked ?? "") ? asked as Parameters<typeof applySkin>[0] : readSkin());
await loadLocale(params.get("lang") ?? "en");
createRoot(document.getElementById("root")!).render(<StrictMode><StoreProvider>{view === "panel" ? <PanelView /> : <SettingsView />}</StoreProvider></StrictMode>);