Skip to content

Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.

19.5 KB
Raw Blame
import { Match, Predicate } from "effect";
import { useAtomValue } from "@effect/atom-react";
import { isAtomCommandInterrupted } from "@akeru/client-runtime/state/runtime";
import { BotId, type EnvironmentId } from "@akeru/contracts";
import { useNavigate } from "@tanstack/react-router";
import { LoaderIcon } from "lucide-react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";

import { useI18n } from "../../i18n";
import { randomUUID } from "../../lib/utils";
import { botEnvironment } from "../../state/bots";
import { serverEnvironment } from "../../state/server";
import { useAtomCommand } from "../../state/use-atom-command";
import {
  AlertDialog,
  AlertDialogClose,
  AlertDialogDescription,
  AlertDialogFooter,
  AlertDialogHeader,
  AlertDialogPopup,
  AlertDialogTitle,
} from "../ui/alert-dialog";
import { Button } from "../ui/button";
import { toastManager } from "../ui/toast";
import { writeBotDraft } from "../roster/botDraftStore";
import { DEFAULT_BOT_RUNTIME_MODE } from "../roster/botSandbox";
import { useRosterStore } from "../roster/rosterStore";
import {
  clearDesktopOnboardingHandoff,
  DESKTOP_ONBOARDING_STEPS,
  type DesktopOnboardingDraft,
  type DesktopOnboardingStep,
  markDesktopOnboardingCompleted,
  markDesktopOnboardingHandoffStarted,
  readDesktopOnboardingHandoff,
  writeDesktopOnboardingDraft,
} from "./desktopOnboardingDraft";
import {
  desktopOnboardingProgress,
  recoverDisappearedDesktopOnboardingBot,
} from "./desktopOnboarding.logic";
import {
  desktopOnboardingModelSelection,
  resolveDesktopOnboardingCreationReadiness,
} from "./desktopOnboardingEngine";
import {
  canStartDesktopOnboardingReveal,
  DESKTOP_ONBOARDING_DESTINATION_TIMEOUT_MS,
  DESKTOP_ONBOARDING_REVEAL_DURATION_MS,
  desktopOnboardingHandoffStages,
  type DesktopOnboardingHandoffPhase,
} from "./desktopOnboardingHandoff";
import { desktopOnboardingBotBrief } from "./goalPlan.logic";
import { OnboardingGoalStep } from "./OnboardingGoalStep";
import { IdentityStep } from "./OnboardingIdentityStep";
import { OnboardingPreview } from "./OnboardingPreview";
import { SubscriptionStep } from "./OnboardingSubscriptionStep";
import { ONBOARDING_HEADING_CLASS } from "./onboardingStyles";
import type { OnboardingTranslate } from "./onboardingTranslate";

const EASE = [0.23, 1, 0.32, 1] as const;

const LEAVE = [0.4, 0, 1, 1] as const;

/** --ease-smooth-out. Carries the setup surface out over the workspace. */
const SMOOTH_OUT = [0.22, 1, 0.36, 1] as const;

/** Seconds. Has to match the wait the reveal leaves before it unmounts setup. */
const REVEAL_DURATION = DESKTOP_ONBOARDING_REVEAL_DURATION_MS / 1000;

const FOCUSABLE_SELECTOR = [
  "a[href]",
  "button:not([disabled])",
  "input:not([disabled])",
  "select:not([disabled])",
  "textarea:not([disabled])",
  '[tabindex]:not([tabindex="-1"])',
].join(",");

/** Rail label for a setup step. Short enough to sit in a four-up stepper. */
function stepLabel(step: DesktopOnboardingStep, t: OnboardingTranslate): string {
  switch (step) {
    case "subscription":
      return t("Connect");
    case "goal":
      return t("Goal");
    case "identity":
      return t("Identity");
    case "message":
      return t("First message");
  }
}

export interface DesktopOnboardingSurfaceProps {
  readonly initialDraft: DesktopOnboardingDraft;
  readonly environmentId: EnvironmentId;
  readonly captureMode: boolean;
  readonly onFinished: () => void;
}

export function OnboardingSurface({
  initialDraft,
  environmentId,
  captureMode,
  onFinished,
}: DesktopOnboardingSurfaceProps) {
  const navigate = useNavigate();
  const reducedMotion = useReducedMotion();
  const { t } = useI18n();
  const createBot = useAtomCommand(botEnvironment.create, { reportFailure: false });
  const providers = useAtomValue(serverEnvironment.providersValueAtom(environmentId));
  const [draft, setDraft] = useState(initialDraft);
  const [creating, setCreating] = useState(false);
  const [createError, setCreateError] = useState<string | null>(null);
  const [message, setMessage] = useState<string | null>(null);
  const [handoff, setHandoff] = useState<DesktopOnboardingHandoffPhase | null>(null);
  /** The chat route has committed, so the workspace is the layer behind setup. */
  const [routeOpened, setRouteOpened] = useState(false);
  /** The sent message and its turn are in the state the chat renders from. */
  const [messageObserved, setMessageObserved] = useState(false);
  const [revealTimedOut, setRevealTimedOut] = useState(false);
  const observeDestination = useCallback(() => setMessageObserved(true), []);
  const [skipConfirmOpen, setSkipConfirmOpen] = useState(false);
  const surfaceRef = useRef<HTMLDivElement>(null);
  const handoffTimers = useRef<number[]>([]);
  const readyBotIdRef = useRef<string | null>(null);

  const rosterBot = useRosterStore((state) =>
    draft.botId ? state.bots.find((bot) => bot.id === draft.botId) : undefined,
  );

  const providerReadiness = useMemo(
    () => resolveDesktopOnboardingCreationReadiness(draft.providerId, providers),
    [draft.providerId, providers],
  );

  /** Reduced motion skips the handoff choreography and reveals at once. */
  const instantHandoff = reducedMotion === true;

  useEffect(
    () => () => {
      for (const timer of handoffTimers.current) window.clearTimeout(timer);
    },
    [],
  );

  useEffect(() => {
    const appRoot = document.getElementById("root");

    if (!appRoot) return;
    const wasInert = appRoot.inert;
    const previousAriaHidden = appRoot.getAttribute("aria-hidden");
    appRoot.inert = true;
    appRoot.setAttribute("aria-hidden", "true");
    surfaceRef.current?.focus();

    const focusableElements = () => {
      const surface = surfaceRef.current;

      if (!surface) return [];

      return Array.from(surface.querySelectorAll<HTMLElement>(FOCUSABLE_SELECTOR)).filter(
        (element) =>
          !element.matches(":disabled") &&
          element.tabIndex >= 0 &&
          element.closest('[inert],[aria-hidden="true"]') === null,
      );
    };

    const containFocus = (event: KeyboardEvent) => {
      if (event.key !== "Tab") return;
      const surface = surfaceRef.current;

      if (!surface) return;
      const focusable = focusableElements();

      if (focusable.length === 0) {
        event.preventDefault();
        surface.focus();

        return;
      }

      const first = focusable[0];
      const last = focusable.at(-1);
      const active = document.activeElement;

      if (!surface.contains(active) || (event.shiftKey && active === first)) {
        event.preventDefault();
        (event.shiftKey ? last : first)?.focus();
      } else if (!event.shiftKey && active === last) {
        event.preventDefault();
        first?.focus();
      }
    };

    document.addEventListener("keydown", containFocus, true);

    return () => {
      document.removeEventListener("keydown", containFocus, true);
      appRoot.inert = wasInert;

      if (previousAriaHidden === null) appRoot.removeAttribute("aria-hidden");
      else appRoot.setAttribute("aria-hidden", previousAriaHidden);
    };
  }, []);

  useEffect(() => {
    if (draft.step !== "message" || draft.botId === null) {
      readyBotIdRef.current = null;

      return;
    }

    if (rosterBot) {
      readyBotIdRef.current = draft.botId;

      return;
    }

    const recoveredDraft = recoverDisappearedDesktopOnboardingBot(draft, readyBotIdRef.current);

    if (recoveredDraft === draft) return;
    readyBotIdRef.current = null;
    setDraft(recoveredDraft);
    writeDesktopOnboardingDraft(window.localStorage, recoveredDraft);
  }, [draft, rosterBot]);

  const updateDraft = (next: DesktopOnboardingDraft) => {
    setCreateError(null);
    setDraft(next);
    writeDesktopOnboardingDraft(window.localStorage, next);
  };

  const create = async () => {
    setCreating(true);
    setCreateError(null);
    const botId = BotId.make(`bot-${randomUUID()}`);
    const goal = desktopOnboardingBotBrief(draft.goal);

    if (providerReadiness.status !== "ready") {
      setCreating(false);

      return;
    }

    const result = await createBot({
      environmentId,
      input: {
        botId,
        name: draft.name.trim(),
        title: "Assistant",
        label: null,
        description: goal.description,
        avatar: draft.avatar,
        engine: providerReadiness.engine,
        sandbox: null,
        runtimeMode: DEFAULT_BOT_RUNTIME_MODE,
        groupId: null,
      },
    });

    setCreating(false);

    if (isAtomCommandInterrupted(result)) return;

    if (Predicate.isTagged(result, "Failure")) {
      setCreateError(t("Could not create your bot."));

      return;
    }

    writeBotDraft(`onboarding:${botId}`, goal.prompt);
    updateDraft({ ...draft, step: "message", botId });
  };

  /**
   * Whether the workspace behind setup is showing the chat the user just
   * started: the chat route has committed and the sent message is visible in
   * the state that route renders from. Capture mode never sends, so it only
   * waits for the route. A draft with no bot has no destination to wait on.
   * Setup cannot reach the send without one, but the overlay still has to
   * lift if it ever does.
   */
  const destinationReady =
    draft.botId === null || (routeOpened && (captureMode || messageObserved));

  /**
   * Hands the user from setup to the workspace. The message lands, the bot
   * wakes, and the workspace is opened behind setup, which stays fully opaque
   * until that workspace is genuinely showing the conversation. A clock cannot
   * know when a projection arrives, so nothing here guesses at one.
   */
  const finish = (firstMessage: string) => {
    setMessage(firstMessage);
    setHandoff("sending");

    if (draft.botId)
      markDesktopOnboardingHandoffStarted(window.localStorage, environmentId, draft.botId);
    else markDesktopOnboardingCompleted(window.localStorage);

    for (const stage of desktopOnboardingHandoffStages(instantHandoff)) {
      if (stage.phase === "sending") continue;
      handoffTimers.current.push(
        window.setTimeout(() => {
          if (stage.phase !== "opening" || !draft.botId) {
            setHandoff(stage.phase);

            return;
          }

          const pending = readDesktopOnboardingHandoff(window.localStorage);

          if (pending?.environmentId !== environmentId || pending.botId !== draft.botId) {
            onFinished();

            return;
          }

          setHandoff(stage.phase);
          useRosterStore.getState().selectBot(draft.botId);

          const opened = () => {
            clearDesktopOnboardingHandoff(window.localStorage);
            setRouteOpened(true);
          };

          void navigate({ to: "/bots/$botId", params: { botId: draft.botId }, replace: true }).then(
            opened,
            () =>
              toastManager.add({
                type: "error",
                title: `Could not open ${draft.name}'s chat. Open it from the roster or reload to retry.`,
              }),
          );
        }, stage.atMs),
      );
    }

    // Failure safety, never the normal path: a destination that never reports
    // itself (a stalled projection, a dropped socket) must not leave the
    // user stuck behind an overlay that will not lift.
    handoffTimers.current.push(
      window.setTimeout(() => setRevealTimedOut(true), DESKTOP_ONBOARDING_DESTINATION_TIMEOUT_MS),
    );
  };

  /**
   * The reveal. It starts from readiness rather than from the send, so the
   * fade always lands on a painted conversation, and it owns the rest of the
   * handoff: setup unmounts on the fade's last frame, never before it.
   */
  useEffect(() => {
    if (
      !canStartDesktopOnboardingReveal({
        phase: handoff,
        destinationReady,
        timedOut: revealTimedOut,
      })
    ) {
      return;
    }

    setHandoff("revealing");
    handoffTimers.current.push(
      window.setTimeout(
        () => {
          setHandoff("done");
          onFinished();
        },
        instantHandoff ? 0 : DESKTOP_ONBOARDING_REVEAL_DURATION_MS,
      ),
    );
  }, [destinationReady, handoff, instantHandoff, onFinished, revealTimedOut]);

  const skip = () => {
    setSkipConfirmOpen(false);
    markDesktopOnboardingCompleted(window.localStorage);
    onFinished();
  };

  const progress = desktopOnboardingProgress(draft.step);
  // Page-side-by-side with the exit slide switched off. The workspace mounts
  // behind setup at `opening` and paints while setup still covers it, then the
  // whole surface fades off it as one opaque layer. Nothing inside animates
  // out, so no piece of setup reads as leaving on its own.
  const revealing = handoff === "revealing" || handoff === "done";

  return createPortal(
    <motion.div
      ref={surfaceRef}
      data-testid="desktop-onboarding"
      role="dialog"
      aria-modal="true"
      aria-label={t("Set up Akeru Bot")}
      tabIndex={-1}
      className={`fixed inset-0 z-10000 flex flex-col overflow-hidden bg-background text-foreground lg:flex-row ${
        revealing ? "pointer-events-none" : ""
      }`}
      initial={reducedMotion ? false : { opacity: 0 }}
      animate={{ opacity: revealing ? 0 : 1 }}
      // The reveal fade already took the surface to nothing, and `done` fires
      // the instant it lands, so unmounting has nothing left to animate.
      exit={{ opacity: 0, transition: { duration: 0 } }}
      transition={{
        duration: revealing ? (instantHandoff ? 0 : REVEAL_DURATION) : reducedMotion ? 0 : 0.18,
        ease: revealing ? SMOOTH_OUT : LEAVE,
      }}
    >
      <aside className="relative z-10 flex min-h-0 w-full min-w-0 flex-1 flex-col border-b border-border/70 bg-card/45 px-6 pb-6 pt-6 backdrop-blur-xl lg:w-19/50 lg:min-w-95 lg:max-w-135 lg:flex-none lg:border-b-0 lg:border-r lg:px-10 lg:pb-10 lg:pt-8">
        <div className="space-y-5">
          <span className="text-sm font-semibold tracking-title">Akeru Bot</span>
          <ol className="flex items-start gap-2" aria-label={t("Setup steps")}>
            {DESKTOP_ONBOARDING_STEPS.map((definition, index) => {
              const position = index + 1;
              const current = position === progress.number;
              const reached = position <= progress.number;

              return (
                <li
                  key={definition.id}
                  className="flex min-w-0 flex-1 flex-col gap-1.5"
                  aria-current={current ? "step" : undefined}
                >
                  <span
                    className={`h-1 rounded-full transition-colors duration-300 motion-reduce:transition-none ${
                      reached ? "bg-foreground" : "bg-foreground/15"
                    }`}
                  />
                  <span
                    className={`truncate text-11px leading-4 transition-colors duration-300 motion-reduce:transition-none ${
                      current ? "font-medium text-foreground" : "text-muted-foreground"
                    }`}
                  >
                    {stepLabel(definition.id, t)}
                  </span>
                </li>
              );
            })}
          </ol>
        </div>
        <div className="flex min-h-0 flex-1 overflow-y-auto overscroll-contain py-5 pe-1 lg:py-6">
          <AnimatePresence mode="wait" initial={false}>
            <motion.div
              key={draft.step}
              className="my-auto w-full py-4"
              initial={reducedMotion ? false : { opacity: 0, x: 18 }}
              animate={{ opacity: 1, x: 0 }}
              exit={{ opacity: 0, x: -12 }}
              transition={{ duration: reducedMotion ? 0 : 0.24, ease: EASE }}
            >
              {Match.value(draft).pipe(
                Match.when({ step: "subscription" }, (draft) => (
                  <SubscriptionStep
                    environmentId={environmentId}
                    draft={draft}
                    captureMode={captureMode}
                    onChange={updateDraft}
                    onContinue={() => updateDraft({ ...draft, step: "goal" })}
                  />
                )),
                Match.when({ step: "goal" }, (draft) => (
                  <OnboardingGoalStep
                    draft={draft}
                    onChange={updateDraft}
                    onBack={() => updateDraft({ ...draft, step: "subscription" })}
                    onContinue={() => updateDraft({ ...draft, step: "identity" })}
                  />
                )),
                Match.when({ step: "identity" }, (draft) => (
                  <IdentityStep
                    draft={draft}
                    creating={creating}
                    providerReadiness={providerReadiness}
                    error={createError}
                    onChange={updateDraft}
                    onBack={() => updateDraft({ ...draft, step: "goal" })}
                    onContinue={() => void create()}
                  />
                )),
                Match.orElse((draft) => (
                  <div className="space-y-4">
                    <h1 className={ONBOARDING_HEADING_CLASS}>
                      {t("Say hello to {name}", { name: draft.name })}
                    </h1>
                    <p className="text-sm leading-6 text-muted-foreground">
                      {t(
                        "Your goal and the plan for it, written out. Edit it however you like, then send. This is the real conversation, not a demo.",
                      )}
                    </p>
                    {!rosterBot ? (
                      <div className="flex items-center gap-2 text-sm text-muted-foreground">
                        <LoaderIcon className="size-4 animate-spin motion-reduce:animate-none" />
                        {t("Waking up {name}", { name: draft.name })}
                      </div>
                    ) : null}
                  </div>
                )),
              )}
            </motion.div>
          </AnimatePresence>
        </div>
        <div className="flex items-center justify-between gap-3">
          <p className="text-xs text-muted-foreground">
            {t("Step {number} of {total}", { number: progress.number, total: progress.total })}
          </p>
          <Button
            size="xs"
            variant="ghost-muted"
            disabled={creating || handoff !== null}
            onClick={() => setSkipConfirmOpen(true)}
          >
            {t("Skip setup")}
          </Button>
        </div>
      </aside>
      <div
        className={`min-h-0 min-w-0 flex-1 ${draft.step === "message" ? "flex" : "hidden lg:flex"}`}
      >
        <OnboardingPreview
          draft={draft}
          message={message}
          createdBotReady={rosterBot !== undefined}
          captureMode={captureMode}
          handoff={handoff}
          modelSelection={desktopOnboardingModelSelection(rosterBot?.engine ?? null)}
          onMessageSent={finish}
          onDestinationReady={observeDestination}
        />
      </div>
      <AlertDialog open={skipConfirmOpen} onOpenChange={setSkipConfirmOpen}>
        <AlertDialogPopup portalContainer={surfaceRef}>
          <AlertDialogHeader>
            <AlertDialogTitle>{t("Skip setup?")}</AlertDialogTitle>
            <AlertDialogDescription>
              {t("You can connect a subscription and create a bot later.")}
            </AlertDialogDescription>
          </AlertDialogHeader>
          <AlertDialogFooter>
            <AlertDialogClose render={<Button variant="outline" />}>{t("Cancel")}</AlertDialogClose>
            <Button onClick={skip}>{t("Skip setup")}</Button>
          </AlertDialogFooter>
        </AlertDialogPopup>
      </AlertDialog>
    </motion.div>,
    document.body,
  );
}