Skip to content

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

10.1 KB
Raw Blame
import { useEffect, useRef, useState, type Ref } from "react";
import { Check, ChevronDown, CircleAlert, FolderOpen, Plug } from "lucide-react";
import { cloudEngineChoices, useCloudEngineChoices } from "@/components/CloudEngineSignIn";
import { useCloudPlanSnapshot } from "@/components/CloudTrialNotice";
import { engineReady } from "@/components/EngineLibrary";
import { EngineCheckLine, type EngineLiveCheck } from "@/components/EngineLiveCheck";
import { EngineSetup } from "@/components/EngineSetup";
import { usd } from "@/lib/cloud-plan";
import { welcomeCredit } from "@/lib/cloud-welcome";
import { cn } from "@/lib/cn";
import { connectAiStep, ConnectAiPlaceContext, useConnectAiSteps } from "@/lib/connect-ai-events";
import { t } from "@/lib/i18n";
import { firstAis, signInFollows } from "@/lib/onboarding";
import { useStore, type Bot, type InstanceInfo } from "@/state/store";
import { CARD, CARD_IDLE, CardIcon, Footer, PRIMARY, QUIET, SECONDARY, StepHeading } from "./parts";

/** Connecting an AI: an AI that already works when the step opens (one signed in here, or the plan's credit) is used as
 * it is and the step finishes itself; otherwise Claude's, ChatGPT's and OpenCode's own setups, every other way folded
 * under them. */
export function WelcomeEngine({ name, headingRef, onFinish }: { name: string; headingRef: Ref<HTMLHeadingElement>; onFinish: () => void }) {
  const engines = useCloudEngineChoices();
  const plan = useCloudPlanSnapshot(window.ogb?.cloudPlan);
  const own = engines.instances.some((instance) => !instance.trialCredit && engineReady(instance));
  const credit = own ? null : welcomeCredit(engines.instances, plan);
  const readyOnOpen = useRef(own || credit?.state === "active");
  const [more, setMore] = useState(false);
  const step = useConnectAiSteps("cloud_welcome");
  useEffect(() => {
    step("opened", { aiReady: readyOnOpen.current });
    if (readyOnOpen.current) onFinish();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);
  useCheckSteps(engines.live.checks, engines.instances);
  if (readyOnOpen.current) return null;
  const first = firstAis(engines.instances, engineReady);
  const shown = new Set(first.map(({ instance }) => instance.driverKind));
  const others = { ...engines, choices: engines.choices.filter((choice) => !shown.has(choice.driverKind)) };
  return <ConnectAiPlaceContext.Provider value="cloud_welcome"><section aria-labelledby="cloud-welcome-step" data-welcome-step="engine" className="flex flex-col">
    <StepHeading headingRef={headingRef} title={t("cloudSetup.engine.title")} sub={t("cloudWelcome.engine.sub", { name })} />
    {credit?.state === "active" && <p role="status" data-welcome-credit className="mt-5 flex items-start gap-2.5 rounded-xl bg-success/12 px-3.5 py-3 text-[13px] leading-relaxed text-ink">
      <Check size={16} strokeWidth={2.5} aria-hidden="true" className="mt-px shrink-0 text-success" />
      <span>{credit.left !== null ? t("cloudWelcome.engine.credit", { amount: usd(credit.left) }) : t("cloudWelcome.engine.creditPlain")}</span>
    </p>}
    {credit && credit.state !== "active" && <p role="status" data-welcome-credit={credit.state} className="mt-5 flex items-start gap-2.5 rounded-xl bg-warning/10 px-3.5 py-3 text-[13px] leading-relaxed text-ink">
      <CircleAlert size={16} aria-hidden="true" className="mt-px shrink-0 text-warning" />
      <span>{t(credit.state === "used_up" ? "cloudSignIn.creditUsedUp" : "cloudSignIn.creditEnded")}</span>
    </p>}
    {first.map(({ kind, instance }, index) => {
      const name = kind === "chatgpt" ? t("cloudSignIn.codex") : instance.displayName;
      const check = engines.live.checks[instance.instanceId];
      return <div key={kind} data-welcome-recommended={instance.instanceId} className={cn(index ? "mt-3" : "mt-6", "rounded-2xl border border-hairline/50 bg-card px-4 py-4")}
        onClickCapture={() => step("chosen", { driverKind: instance.driverKind })}>
        {engineReady(instance)
          ? check && <EngineCheckLine name={name} check={check} onRetry={() => void engines.live.run(instance.instanceId)} />
          : <EngineSetup instance={instance} unframed description={signInFollows(instance) ? t("onboarding.engines.signInHint", { name }) : undefined} />}
      </div>;
    })}
    <button type="button" data-welcome-other-ways aria-expanded={more} onClick={() => setMore((value) => !value)}
      className="mt-4 flex items-center gap-1.5 self-start rounded-md px-1.5 py-1 text-[13px] font-medium text-ink-secondary transition-colors hover:text-ink motion-reduce:transition-none">
      {t("onboarding.engines.otherWays")}
      <ChevronDown size={14} aria-hidden="true" className={cn("transition-transform duration-200 motion-reduce:transition-none", more && "rotate-180")} />
    </button>
    {more && cloudEngineChoices(others, { columns: others.choices.length === 1 ? "grid-cols-1" : "grid-cols-1 @sm/step:grid-cols-2" })}
    <Footer className="mt-7">
      {own
        ? <button type="button" className={PRIMARY} onClick={onFinish}>{t("onboarding.continue")}</button>
        : credit?.state === "active"
          ? <button type="button" className={PRIMARY} onClick={onFinish}>{t("cloudWelcome.engine.useCredit")}</button>
          : <button type="button" className={QUIET} onClick={() => { step("later"); onFinish(); }}>{t("cloudIntent.skip")}</button>}
    </Footer>
  </section></ConnectAiPlaceContext.Provider>;
}

/** A test message the step's setups sent (right after a sign-in) ending, once each time. */
function useCheckSteps(checks: Record<string, EngineLiveCheck>, instances: readonly InstanceInfo[]) {
  const before = useRef<Record<string, EngineLiveCheck>>({});
  const started = useRef<Record<string, number>>({});
  useEffect(() => {
    for (const [instanceId, check] of Object.entries(checks)) {
      const was = before.current[instanceId];
      const driverKind = instances.find((instance) => instance.instanceId === instanceId)?.driverKind ?? "";
      if (check.state === "checking" && was?.state !== "checking") {
        started.current[instanceId] = Date.now();
        connectAiStep("test_started", "cloud_welcome", { driverKind });
      }
      if (check.state === "checking" || was?.state !== "checking") continue;
      const seconds = (Date.now() - (started.current[instanceId] ?? Date.now())) / 1000;
      connectAiStep(check.state === "working" ? "test_ok" : "test_failed", "cloud_welcome",
        { driverKind, seconds, ...(check.state === "failed" ? { reason: check.reason ?? "other" } : {}) });
    }
    before.current = checks;
  }, [checks, instances]);
}

/** "folders": in the app on a Cloud of the person's own, this computer is lent to it by itself; from a browser or on a
 * Team Cloud, the desktop app shares folders through Files. */
export function WelcomeFiles({ name, headingRef, onFinish }: { name: string; headingRef: Ref<HTMLHeadingElement>; onFinish: () => void }) {
  const { state, dispatch } = useStore();
  const lent = Boolean(window.ogb?.cloudPlan) && !state.config?.team;
  const card = (id: string, icon: typeof Plug, title: string, body: string, action?: { label: string; run: () => void }) =>
    <div data-welcome-files={id} className={cn(CARD, CARD_IDLE)}>
      <CardIcon icon={icon} />
      <span className="text-[15px] font-semibold text-ink">{title}</span>
      <span className="text-[13px] leading-relaxed text-ink-secondary">{body}</span>
      {action && <span className="mt-1"><button type="button" className={SECONDARY} onClick={action.run}>{action.label}</button></span>}
    </div>;
  return <section aria-labelledby="cloud-welcome-step" data-welcome-step="files" className="flex flex-col gap-5">
    <StepHeading headingRef={headingRef} title={t("cloudWelcome.files.title")} aside={t("cloudWelcome.files.optional")} sub={t("cloudWelcome.files.sub")} />
    <div className="grid gap-3 @lg/step:grid-cols-2">
      {card("folders", FolderOpen, t("cloudWelcome.files.folders"), t(lent ? "cloudWelcome.files.foldersLent" : "cloudWelcome.files.foldersDesktop", { name }))}
      {card("apps", Plug, t("cloudWelcome.files.apps"), t("cloudWelcome.files.appsHint"),
        { label: t("cloudWelcome.files.appsAction"), run: () => dispatch({ type: "togglePlugins", open: true, surface: "apps" }) })}
    </div>
    <Footer>
      <button type="button" className={PRIMARY} onClick={onFinish}>{t("cloudWelcome.files.finish")}</button>
      <button type="button" className={QUIET} onClick={onFinish}>{t("cloudIntent.skip")}</button>
    </Footer>
  </section>;
}

export function WelcomeDone({ name, bot, team = false, headingRef, onSayHi, onJob, invite = null }: {
  name: string; bot: Bot | null; headingRef: Ref<HTMLHeadingElement>; onSayHi: () => void; onJob: () => void;
  /** A Team Cloud: its first bot is named, never called anyone's Chief of Staff. */
  team?: boolean;
  /** The team's People page on MausBot Cloud, its invite box open, for its Owner: the last step is bringing people in. */
  invite?: string | null;
}) {
  return <section aria-labelledby="cloud-welcome-step" data-welcome-step="done" className="flex flex-col items-start gap-4">
    <span aria-hidden="true" className="check-in flex size-[42px] items-center justify-center rounded-full bg-success">
      <Check size={22} strokeWidth={2.5} />
    </span>
    <StepHeading headingRef={headingRef} title={t("cloudWelcome.done.title", { name })} sub={t("cloudWelcome.done.body")} />
    {invite && <div data-welcome-invite className="flex w-full max-w-[520px] flex-col items-start gap-2 rounded-2xl border border-hairline/50 bg-card/50 p-4">
      <p className="text-[14px] font-medium text-ink">{t("cloudWelcome.invite.title", { name })}</p>
      <p className="text-[13px] leading-relaxed text-ink-secondary">{t("cloudWelcome.invite.bodySeats", { name })}</p>
      <a href={invite} target="_blank" rel="noreferrer" className={SECONDARY}>{t("cloudWelcome.invite.action")}</a>
    </div>}
    <Footer>
      <button type="button" className={PRIMARY} onClick={onSayHi}>
        {bot && (team || !bot.chiefOfStaff) ? t("cloudWelcome.done.bot", { name: bot.name }) : t("cloudWelcome.done.chief")}
      </button>
      {bot && <button type="button" className={SECONDARY} onClick={onJob}>{t("cloudSetup.job.action")}</button>}
    </Footer>
  </section>;
}