Skip to content

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

12.3 KB
Raw Blame
import { useEffect, useRef, useState } from "react";
import type { ManagedDesktopState, ManagedMessageCode } from "../../electron/managed-desktop.mjs";
import { activeLocale, t } from "@/lib/i18n";
import type { LocaleKey } from "@/locales";
import { Card, LearnMore, SETTINGS_INPUT, SettingRow, SettingsField, SettingsFoldRow, SettingsRows } from "./SettingsPrimitives";
import { CompanyModels } from "./CompanyModels";

const providerNames: Record<string, string> = { anthropic: "Anthropic", openai: "OpenAI", openrouter: "OpenRouter" };
const DEFAULT_PORTAL_ORIGIN = "https://admin.openmausbot.com";
const STATUS_TEXT: Record<ManagedMessageCode, LocaleKey> = {
  clearFailed: "organization.status.clearFailed",
  disconnected: "organization.status.disconnected",
  runtimeRunning: "organization.status.runtimeRunning",
  portalUnreachable: "organization.status.portalUnreachable",
  confirmStopped: "organization.status.confirmStopped",
  expired: "organization.status.expired",
  accessEnded: "organization.status.accessEnded",
  retrying: "organization.status.retrying",
  codeExpired: "organization.status.codeExpired",
  denied: "organization.status.denied",
  completeFailed: "organization.status.completeFailed",
  removed: "organization.status.removed",
  restoreFailed: "organization.status.restoreFailed",
  startFailed: "organization.status.startFailed",
};

export function connectionMessage(connection: Pick<ManagedDesktopState, "message" | "messageCodes">): string | undefined {
  const codes = connection.messageCodes;
  if (!codes?.length || !codes.every((code) => Object.hasOwn(STATUS_TEXT, code))) return connection.message;
  return codes.map((code) => t(STATUS_TEXT[code])).join(" ");
}

/** Security: only the trusted desktop bridge can enroll this computer or hold its token. */
/** `simple`: Simple mode shows the section only once the person has an organization sign-in; signed out, it draws an
 * empty card, which hides the whole section (search still finds it, tagged Advanced). */
export function OrganizationSettings({ simple = false }: { simple?: boolean } = {}) {
  const bridge = window.ogb?.remoteClient?.active ? undefined : window.ogb?.organization;
  const [connection, setConnection] = useState<ManagedDesktopState | null>(null);
  const [address, setAddress] = useState("");
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState("");
  const [confirmDisconnect, setConfirmDisconnect] = useState(false);
  const [more, setMore] = useState(false);
  const [custom, setCustom] = useState(false);
  const pending = useRef(false);
  const generation = useRef(0);
  const revision = useRef(0);
  const status = useRef<ManagedDesktopState["status"] | undefined>(undefined);

  const acceptConnection = (next: ManagedDesktopState) => {
    const changed = status.current !== next.status;
    status.current = next.status;
    setConnection(next);
    // Outside React's state updater: updaters must stay pure and can run during rendering.
    if (changed) setError("");
    if (next.status !== "connected" && next.status !== "reauth-required") setConfirmDisconnect(false);
  };

  useEffect(() => {
    // Acknowledges only the rendered destination, never enrollment.
    void bridge?.settingsOpened?.().catch(() => {});
    const current = ++generation.current;
    const initialRevision = revision.current;
    const receive = (next: ManagedDesktopState) => {
      if (generation.current !== current) return;
      revision.current++;
      acceptConnection(next);
    };
    const unsubscribe = bridge?.onState(receive);
    void bridge?.state().then((next) => {
      // A push can arrive while the initial snapshot is in flight.
      if (revision.current === initialRevision) receive(next);
    }).catch(() => {
      if (generation.current === current && revision.current === initialRevision) setError(t("organization.loadFailed"));
    });
    return () => { generation.current++; unsubscribe?.(); };
  }, [bridge]);

  const perform = async (action: () => Promise<ManagedDesktopState>) => {
    if (!bridge || pending.current) return;
    pending.current = true;
    setBusy(true); setError("");
    const current = generation.current;
    const startedRevision = revision.current;
    try {
      const next = await action();
      if (generation.current === current && revision.current === startedRevision) {
        acceptConnection(next);
      }
    } catch {
      // IPC exceptions can contain internal paths; display only product copy.
      if (generation.current === current && revision.current === startedRevision) setError(t("organization.actionFailed"));
    } finally {
      pending.current = false;
      if (generation.current === current) setBusy(false);
    }
  };

  if (!bridge) return <p className="text-[13px] text-ink-secondary">{t("organization.desktopOnly")}</p>;
  const enrolled = connection?.status === "connected" || connection?.status === "reauth-required" || connection?.status === "unavailable" || connection?.status === "license-expired";
  const licenseExpired = connection?.status === "license-expired" || connection?.notice === "license-expired";
  const expiry = connection?.enrollment?.expiresAt ?? connection?.expiresAt;
  const date = typeof expiry === "number" && Number.isFinite(expiry) ? new Date(expiry) : null;
  const dateLabel = date && Number.isFinite(date.getTime())
    ? new Intl.DateTimeFormat(activeLocale(), { dateStyle: "medium", timeStyle: "short" }).format(date) : null;
  if (connection?.status === "signed-out" && simple) return <div data-settings-rows="" hidden />;
  if (connection?.status === "signed-out") {
    // One row: sign in with a work email; the long notes behind Learn more, the custom address behind a fold.
    return <SettingsRows>
      <SettingRow title={t("organization.signIn")} subtitle={<>{t("organization.signInShort")}{" "}<LearnMore onClick={() => setMore((open) => !open)} /></>}
        message={<>
          {more && <span data-organization-more="" className="block">{t("organization.additive")} {t("organization.privacy")} {t("cloudAccount.separate")}</span>}
          {connection.message && <span role="status" className="block">{connectionMessage(connection)}</span>}
          {licenseExpired && <span role="alert" className="block text-ink">{t("organization.licenseExpired")}</span>}
          {error && <span role="alert" className="block text-danger">{error}</span>}
        </>}>
        <button type="button" disabled={busy} className="ui-button" data-organization-sign-in="" onClick={() => void perform(() => bridge.begin({ portalOrigin: DEFAULT_PORTAL_ORIGIN }))}>
          {busy ? t("organization.working") : t("organization.useWorkSignIn")}
        </button>
      </SettingRow>
      <SettingsFoldRow id="organization-address" title={t("organization.customTitle")} open={custom} onToggle={() => setCustom((open) => !open)}>
        <form className="flex flex-col gap-2 px-4 py-3" onSubmit={(event) => {
          event.preventDefault();
          if (address.trim()) void perform(() => bridge.begin({ portalOrigin: address.trim() }));
        }}>
          <SettingsField label={t("organization.address")} hint={t("organization.advancedHelp")}>
            <input type="url" required value={address} disabled={busy} onChange={(event) => setAddress(event.target.value)}
              placeholder={DEFAULT_PORTAL_ORIGIN} autoCapitalize="none" autoCorrect="off" autoComplete="off" spellCheck={false} maxLength={2048}
              className={SETTINGS_INPUT} />
          </SettingsField>
          <button type="submit" disabled={busy || !address.trim()} className="ui-button self-end">{t("organization.customSignIn")}</button>
        </form>
      </SettingsFoldRow>
    </SettingsRows>;
  }
  return <>
    <Card>
      {!connection && <p role="status" className="text-[13px] text-ink-secondary">{error || t("organization.loading")}</p>}
      {connection?.message && <p role="status" className="mb-3 text-[13px] text-ink-secondary">{connectionMessage(connection)}</p>}
      {licenseExpired && <p role="alert" className="mb-3 text-[13px] text-ink">{t("organization.licenseExpired")}</p>}
      {connection?.status === "connecting" && <div className="flex flex-col items-start gap-3">
        <p role="status" className="text-[13px] text-ink-secondary">{t("organization.browserConsent")}</p>
        {connection.enrollment && <details className="w-full text-[12px] text-ink-secondary">
          <summary className="w-fit cursor-pointer hover:text-ink">{t("organization.securityDetails")}</summary>
          <p className="mt-2">{t("organization.securityDetailsHelp")}</p>
          <div className="mt-3">{t("organization.code")}</div>
          <code dir="ltr" className="mt-1 block w-fit select-all rounded-lg bg-inset px-3 py-2 text-base tracking-widest text-ink">{connection.enrollment.userCode}</code>
        </details>}
        <div className="flex flex-wrap gap-2">
          {connection.enrollment && bridge.reopen && <button type="button" disabled={busy} className="ui-button" onClick={() => void perform(() => bridge.reopen!())}>{t("organization.reopen")}</button>}
          <button type="button" disabled={busy} className="ui-button" onClick={() => void perform(() => bridge.cancelEnrollment())}>{t("organization.cancel")}</button>
        </div>
      </div>}
      {enrolled && <div className="flex flex-col gap-3">
        <div>{connection.branding?.logo && <img src={connection.branding.logo} alt={t("organization.logo")} className="mb-2 size-12 rounded-lg object-contain" />}<div className="break-words text-[15px] font-medium text-ink">{connection.organization?.name}</div>
          <div className="break-all text-[13px] text-ink-secondary">{connection.email}</div></div>
        {connection.status === "reauth-required" ? <p role="alert" className="text-[13px] text-ink-secondary">{t("organization.reauth")}</p> : connection.status === "license-expired" ? <>
          {connection.providers?.some((provider) => provider.configured && provider.models.length > 0) && <ul className="divide-y divide-hairline/40">{connection.providers.filter((provider) => provider.configured && provider.models.length > 0).map((provider) => <li key={provider.id} className="flex flex-wrap justify-between gap-2 py-2 text-[13px]">
            <span className="text-ink">{providerNames[provider.id] ?? provider.id}</span>
            <span className="text-ink-secondary">{t("organization.companyModelsUnavailable")}</span>
          </li>)}</ul>}
        </> : connection.status === "connected" ? <>
          <p className="text-[13px] text-ink-secondary">{t("organization.modelHelp")}</p>
          {connection.providers?.some((provider) => provider.configured && provider.models.length > 0) ?
            <CompanyModels providers={connection.providers} /> : <p className="text-[13px] text-ink-secondary">{t("organization.noModels")}</p>}
        </> : null}
        {confirmDisconnect ? <div role="group" aria-label={t("organization.disconnectTitle")} className="rounded-lg border border-hairline/40 p-3">
          <p className="text-[13px] text-ink">{t("organization.disconnectWarning")}</p>
          <div className="mt-3 flex flex-wrap gap-2">
            <button type="button" autoFocus disabled={busy} className="ui-button" onClick={() => setConfirmDisconnect(false)}>{t("organization.keepConnection")}</button>
            <button type="button" disabled={busy} className="ui-button text-danger" onClick={() => void perform(() => bridge.disconnect())}>{t("organization.disconnectConfirm")}</button>
          </div>
        </div> : <div className="flex flex-wrap gap-2">
          {connection.status !== "reauth-required" && <button type="button" disabled={busy} className="ui-button" onClick={() => void perform(() => bridge.refresh())}>{t("organization.refresh")}</button>}
          <button type="button" disabled={busy} className="ui-button" onClick={() => setConfirmDisconnect(true)}>{t("organization.disconnect")}</button>
        </div>}
      </div>}
      {connection?.status === "unavailable" && <p role="status" className="text-[13px] text-ink-secondary">{t("organization.unavailable")}</p>}
      {dateLabel && <p className="mt-3 text-[12px] text-ink-secondary">{t("organization.expires", { date: dateLabel })}</p>}
      {error && connection && <p role="alert" className="mt-3 text-[13px] text-danger">{error}</p>}
      {!connection && <button type="button" disabled={busy} className="ui-button mt-3" onClick={() => void perform(() => bridge.refresh())}>{t("organization.refresh")}</button>}
    </Card>
  </>;
}