Skip to content

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

19.0 KB
Raw Blame
import { createAdaptiveScheduler } from "@/lib/adaptive-poll";
import { boatCapableEngine } from "@/lib/remote-desktop";
import { useEffect, useRef, useState } from "react";
import { CalendarClock, CalendarDays, Globe, ImageOff, Loader2, Monitor, Plus, X } from "lucide-react";

import { cn } from "@/lib/cn";
import { useCaptionChrome } from "@/components/DesktopCapabilities";
import { usePageVisible } from "@/lib/page-visible";
import { isRemoteScreenshotContention, localVmScreenshotSource, remoteScreenshotSource } from "@/lib/remote-desktop";
import type { Routine } from "@/lib/routines";
import { dayName, scheduleLabel } from "@/lib/schedule-label";
import { intlLocale, t } from "@/lib/i18n";
import { api, ApiError, useStore, type Bot } from "@/state/store";
import { releaseComputerPanelFocus, takeComputerPanelBrowserView, useComputerPanelEntry } from "@/lib/computer-panel-focus";
import { RoutineEditor } from "./RoutinesPage";
import { BrowserPanel, type BrowserSignIn } from "./BrowserPanel";
import { SignInBanner } from "./SignInRequestCard";
import { openProviderDesktop } from "./computer-takeover";
import { LocalizedPanelError, panelErrorText } from "@/lib/computer-messages";

function viewerAddress(raw: unknown): string {
  if (typeof raw !== "string" || !raw) throw new Error(t("remoteDesktop.noLink"));
  if (raw.startsWith("/vps-viewer/")) return new URL(raw, window.location.origin).toString();
  return raw;
}

function routineScheduleLabel(routine: Routine) {
  if (routine.schedule.type === "cron" || routine.schedule.type === "limit_reset") return scheduleLabel(routine.schedule);
  if (routine.schedule.type === "once") {
    return new Date(routine.schedule.at).toLocaleString(intlLocale(), {
      month: "short",
      day: "numeric",
      hour: "numeric",
      minute: "2-digit",
    });
  }
  if (routine.schedule.type === "interval") {
    const cadence = routine.schedule.everyMinutes % 60 === 0
      ? t("routines.interval.hours", { hours: routine.schedule.everyMinutes / 60 })
      : t("routines.interval.minutes", { minutes: routine.schedule.everyMinutes });
    return t("remoteDesktop.startingAt", { cadence, date: new Date(routine.schedule.anchorAt).toLocaleString(intlLocale(), {
      month: "short",
      day: "numeric",
      hour: "numeric",
      minute: "2-digit",
    }) });
  }
  const days = routine.schedule.weekdays;
  const cadence =
    days.length === 7
      ? t("routines.repeat.daily")
      : days.join(",") === "1,2,3,4,5"
        ? t("routines.repeat.weekdays")
        : days.map(dayName).join(", ");
  const [hour, minute] = routine.schedule.time.split(":").map(Number);
  return `${cadence} · ${new Date(2000, 0, 1, hour, minute).toLocaleTimeString(intlLocale(), { hour: "numeric", minute: "2-digit" })}`;
}

function nextRunLabel(at: number | null) {
  if (at == null) return t("routines.pausedSchedule");
  const date = new Date(at);
  const today = new Date();
  const sameDay = date.toDateString() === today.toDateString();
  return `${sameDay ? t("routines.today") : date.toLocaleDateString(intlLocale(), { month: "short", day: "numeric" })}, ${date.toLocaleTimeString(intlLocale(), { hour: "numeric", minute: "2-digit" })}`;
}

export function RemoteDesktopPanel({ bot }: { bot: Bot }) {
  const { state, dispatch } = useStore();
  const { dragProps } = useCaptionChrome();
  const panelRef = useComputerPanelEntry(bot.id);
  const [pending, setPending] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [frame, setFrame] = useState<string | null>(null);
  const [previewPending, setPreviewPending] = useState(true);
  const [previewUnavailable, setPreviewUnavailable] = useState(false);
  const [viewerOpen, setViewerOpen] = useState(false);
  const pageVisible = usePageVisible();
  const previewBusy = useRef(bot.busy);
  const previewReschedule = useRef<(() => void) | null>(null);
  useEffect(() => { previewBusy.current = bot.busy; previewReschedule.current?.(); }, [bot.busy]);
  const [creatingRoutine, setCreatingRoutine] = useState(false);
  // The host runs this bot on its Local VM: preview, control and viewer all go to that desktop, not the cloud computer.
  const localVm = bot.computer === "vm";
  const [view, setView] = useState<"desktop" | "browser">(() => takeComputerPanelBrowserView(bot.id) ? "browser" : "desktop");
  const [signIn, setSignIn] = useState<BrowserSignIn>();
  const help = state.computerControl[bot.id]?.help ?? null;
  const asker = help ? state.bots.find((candidate) => candidate.id === help.botId)?.name ?? bot.name : bot.name;
  const requestedSignIn = state.signInFocus?.botId === bot.id ? state.signInFocus : undefined;
  useEffect(() => {
    if (!requestedSignIn || requestedSignIn.consumed) return;
    setView(requestedSignIn.place === "browser" ? "browser" : "desktop");
    if (requestedSignIn.place === "browser") setSignIn({ url: requestedSignIn.url, site: requestedSignIn.site, nonce: requestedSignIn.requestId, ...(requestedSignIn.expand ? { expand: true } : {}) });
    dispatch({ type: "signInFocusConsumed", requestId: requestedSignIn.requestId });
  }, [dispatch, requestedSignIn]);
  const botRoutines = state.routines
    .filter((routine) => routine.botId === bot.id)
    .sort((a, b) => Number(b.enabled) - Number(a.enabled) || (a.nextRunAt ?? Infinity) - (b.nextRunAt ?? Infinity));
  const activeRoutineRun = state.routineRuns.find(
    (run) => run.botId === bot.id && ["queued", "running", "waiting"].includes(run.status),
  );
  const cloudRoutineReady = Boolean(
    state.config?.box.configured &&
      boatCapableEngine(state.instances, bot.modelSelection.instanceId)?.snapshot.state === "available",
  );

  useEffect(() => {
    setFrame(null);
    setPreviewPending(true);
    setPreviewUnavailable(false);
  }, [bot.id, localVm]);

  useEffect(() => {
    const viewer = window.ogb?.desktopViewer;
    if (!viewer) return;
    let alive = true;
    void viewer.currentState().then((state) => {
      if (alive) setViewerOpen(state.open && state.contextId === bot.id);
    }).catch(() => {});
    const dispose = viewer.onState((state) => {
      if (state.contextId === bot.id || !state.open) setViewerOpen(state.open && state.contextId === bot.id);
    });
    return () => {
      alive = false;
      dispose();
    };
  }, [bot.id]);

  useEffect(() => {
    if (view !== "desktop" || !pageVisible || viewerOpen || pending) return;
    const controller = new AbortController();
    let requestRunning = false;
    let lastAttemptAt = -Infinity;
    let retryDelay: number | null = null;
    let contentionSince: number | null = null;
    const nextWait = () => lastAttemptAt + (retryDelay ?? (previewBusy.current ? 4000 : 30_000)) - Date.now();
    const scheduler = createAdaptiveScheduler(nextWait, () => void shoot());
    const schedule = () => { if (!controller.signal.aborted && !requestRunning) scheduler.schedule(); };
    previewReschedule.current = schedule;
    const shoot = async () => {
      if (requestRunning || controller.signal.aborted) return;
      if (nextWait() > 0) { schedule(); return; }
      requestRunning = true;
      retryDelay = null;
      try {
        const shot = await api(`/api/bots/${bot.id}/${localVm ? "local-computer" : "computer"}/screenshot`, {
          method: "POST",
          body: "{}",
          signal: AbortSignal.any([controller.signal, AbortSignal.timeout(90_000)]),
        });
        const source = localVm ? localVmScreenshotSource(shot) : remoteScreenshotSource(shot);
        if (!controller.signal.aborted && source) {
          setFrame(source);
          setPreviewUnavailable(false);
          contentionSince = null;
        } else if (!controller.signal.aborted) {
          setPreviewUnavailable(true);
        }
      } catch (cause) {
        if (!controller.signal.aborted) {
          if (cause instanceof ApiError && isRemoteScreenshotContention(cause)) {
            retryDelay = 1000;
            contentionSince ??= Date.now();
            const prolonged = Date.now() - contentionSince >= 10_000;
            setPreviewUnavailable(prolonged);
            setPreviewPending(!prolonged);
          } else {
            contentionSince = null;
            setPreviewUnavailable(true);
          }
        }
      } finally {
        if (!controller.signal.aborted && retryDelay === null) setPreviewPending(false);
        requestRunning = false;
        lastAttemptAt = Date.now();
        schedule();
      }
    };
    void shoot();
    return () => {
      if (previewReschedule.current === schedule) previewReschedule.current = null;
      controller.abort();
      scheduler.cancel();
    };
  }, [bot.id, localVm, pageVisible, viewerOpen, pending, view]);

  const open = async () => {
    setPending(true);
    setError(null);
    // Set when another view holds the Local VM: this attempt opened nothing, so it must not close that view's viewer.
    let heldElsewhere = false;
    try {
      if (!window.ogb?.desktopViewer) throw new Error(t("remoteDesktop.viewerUnavailable"));
      // A take with no target holds the desktop the host runs this bot on, its Local VM included, as a phone's does.
      const target = !localVm && bot.cloudBackend === "vps" ? `vps/${bot.id}` : undefined;
      await openProviderDesktop({
        botId: bot.id, title: t("computer.viewerTitle", { name: bot.name }), current: () => true,
        request: (action, controlLeaseId) => api(`/api/bots/${bot.id}/computer/control`, {
          method: "POST", body: JSON.stringify({ action, controlLeaseId, ...(target ? { target } : {}) }),
        }),
        join: async (signal, controlLeaseId) => {
          // The host binds a Local VM viewer to the lease holding it; a hold another view owns can't be joined from here.
          let path = "computer/join";
          if (localVm) {
            if (!controlLeaseId) {
              heldElsewhere = true;
              throw new LocalizedPanelError("vm.workspace.alreadyControlled");
            }
            path = `local-computer/join?${new URLSearchParams({ controlLeaseId })}`;
          }
          return { joinUrl: viewerAddress((await api(`/api/bots/${bot.id}/${path}`, { method: "POST", body: "{}", signal })).joinUrl) };
        },
      });
    } catch (cause) {
      if (!heldElsewhere) {
        await api(`/api/bots/${bot.id}/computer/viewer-close`, {
          method: "POST",
          body: "{}",
        }).catch(() => {});
      }
      setError(panelErrorText(cause instanceof Error ? cause : String(cause)));
    } finally {
      setPending(false);
    }
  };

  return (
    <aside className="relative z-20 flex h-full w-[400px] shrink-0 flex-col border-l border-hairline bg-panel" ref={panelRef} data-computer-panel>
      <div {...dragProps} className="flex items-center justify-between border-b border-hairline px-5 py-4">
        <div>
          <div className="text-[14px] font-medium text-ink">{t("remoteDesktop.title", { name: bot.name })}</div>
          <div className="mt-0.5 text-[11px] text-ink-secondary">
            {t(localVm ? "vm.dest.vm" : bot.cloudBackend === "vps" ? "botAccess.cloud.selfHostedVps" : "remoteDesktop.cloudDesktop")}
          </div>
        </div>
        <div className="flex items-center gap-1">
          <div className="flex rounded-full bg-inset p-0.5" aria-label={t("computer.tabsAria")}>
            {(["desktop", "browser"] as const).map((option) => (
              <button
                key={option}
                type="button"
                onClick={() => setView(option)}
                aria-pressed={view === option}
                className={cn("flex items-center gap-1 rounded-full px-2.5 py-1 text-[12px]", view === option ? "bg-card text-ink shadow-sm" : "text-ink-secondary hover:text-ink")}
              >
                {option === "desktop" ? <Monitor size={12} /> : <Globe size={12} />}
                {t(option === "desktop" ? "remoteDesktop.desktop" : "place.browser")}
              </button>
            ))}
          </div>
          <button
            type="button"
            data-computer-panel-close
            onClick={() => {
              releaseComputerPanelFocus(panelRef.current, bot.id);
              dispatch({ type: "toggleComputer", open: false });
            }}
            className="rounded-md p-1 text-ink-secondary hover:bg-control hover:text-ink"
            aria-label={t("remoteDesktop.close")}
          >
            <X size={18} />
          </button>
        </div>
      </div>

      {view === "browser" ? (
        <div className="flex min-h-0 flex-1 flex-col px-4 pb-4 pt-1">
          {help?.place === "browser" && <div className="-mt-2 mb-3"><SignInBanner help={help} askerName={asker} onError={setError} /></div>}
          <BrowserPanel bot={bot} signIn={signIn} />
          {error && <div role="alert" className="mt-2 rounded-lg border border-danger/30 bg-danger/10 px-3 py-2 text-[12px] text-danger">{error}</div>}
          <p className="mt-2 text-[11px] leading-relaxed text-ink-secondary">
            {t("remoteDesktop.browserHintDevices")}
          </p>
        </div>
      ) : (
      <div className="flex flex-1 flex-col items-center gap-4 overflow-y-auto px-6 py-5 text-center">
        {help && help.place !== "browser" && <div className="-mt-3 w-full"><SignInBanner help={help} askerName={asker} onError={setError} /></div>}
        <button
          type="button"
          onClick={() => void open()}
          disabled={pending || !frame}
          className="group relative flex aspect-video w-full items-center justify-center overflow-hidden rounded-xl border border-hairline bg-black disabled:cursor-default"
          aria-label={frame ? t("computer.openLiveDesktopAria", { name: bot.name }) : t("remoteDesktop.previewUnavailableLabel")}
        >
          {frame ? (
            <img src={frame} alt={t("remoteDesktop.previewAlt", { name: bot.name })} className="h-full w-full object-contain" />
          ) : previewPending ? (
            <Loader2 size={22} className="animate-spin text-ink-secondary" />
          ) : (
            <div className="flex flex-col items-center gap-2 text-ink-secondary">
              <ImageOff size={24} />
              <span className="text-[11px]">{t(previewUnavailable ? "remoteDesktop.previewUnavailable" : "remoteDesktop.previewWaiting")}</span>
            </div>
          )}
          {frame && (
            <span className="absolute inset-x-0 bottom-0 bg-black/65 py-2 text-[11px] font-medium text-white opacity-0 transition-opacity group-hover:opacity-100">
              {t("computer.openLiveDesktop")}
            </span>
          )}
        </button>
        <div>
          <div className="text-[14px] font-medium text-ink">{t("remoteDesktop.openLive")}</div>
          <p className="mt-2 text-[12px] leading-relaxed text-ink-secondary">
            {t("remoteDesktop.relayHint")}
          </p>
        </div>
        <button
          type="button"
          onClick={() => void open()}
          disabled={pending}
          className="flex w-full items-center justify-center gap-2 rounded-lg bg-accent px-4 py-2.5 text-[13px] font-medium text-white hover:brightness-110 disabled:opacity-50"
        >
          {pending ? <Loader2 size={15} className="animate-spin" /> : <Monitor size={15} />}
          {t(pending ? "settings.updates.opening" : "computer.takeControl")}
        </button>
        {error && (
          <div role="alert" className="w-full rounded-lg border border-danger/30 bg-danger/10 px-3 py-2 text-left text-[12px] text-danger">
            {error}
          </div>
        )}
        <p className="text-[11px] leading-relaxed text-ink-secondary">
          {t("remoteDesktop.accessHintDevices")}
        </p>

        <div className="w-full rounded-xl bg-card p-4 text-left">
          <div className="flex items-center justify-between gap-2">
            <div className="flex items-center gap-2 text-[15px] font-medium text-ink">
              <CalendarClock size={16} className="text-accent" />
              {t("computer.routines.title")}
            </div>
            {botRoutines.length > 0 && (
              <span className="rounded-full bg-control px-2 py-0.5 text-[10px] font-medium text-ink-secondary">
                {botRoutines.length}
              </span>
            )}
          </div>
          {activeRoutineRun && (
            <button
              type="button"
              onClick={() => dispatch({ type: "showRoutines" })}
              className="mt-3 flex w-full items-center gap-2 rounded-lg border border-accent/25 bg-accent/10 px-3 py-2 text-left text-[12px] text-accent hover:bg-accent/15"
            >
              <Loader2 size={13} className={activeRoutineRun.status === "queued" ? "" : "animate-spin"} />
              <span className="min-w-0 flex-1 truncate">
                {activeRoutineRun.routineName} · {t(activeRoutineRun.status === "waiting" ? "computer.routines.needsYou" : activeRoutineRun.status === "queued" ? "computer.runStatus.queued" : "computer.runStatus.running")}
              </span>
            </button>
          )}
          {botRoutines.length > 0 && (
            <div className="mt-3 space-y-1.5">
              {botRoutines.slice(0, 3).map((routine) => (
                <button
                  type="button"
                  key={routine.id}
                  onClick={() => dispatch({ type: "showRoutines" })}
                  className="flex w-full items-center gap-2 rounded-lg bg-inset px-3 py-2 text-left hover:bg-control/60"
                >
                  <span className={cn("size-1.5 shrink-0 rounded-full", routine.enabled ? "bg-success" : "bg-ink-secondary/40")} />
                  <span className="min-w-0 flex-1">
                    <span className="block truncate text-[13px] font-medium text-ink">{routine.name}</span>
                    <span className="block truncate text-[11px] text-ink-secondary">
                      {routineScheduleLabel(routine)}{routine.runOn === "cloud" ? ` · ${t("remoteDesktop.runsOnVm")}` : ""}
                    </span>
                  </span>
                  <span className="shrink-0 text-[10px] text-ink-secondary">{nextRunLabel(routine.nextRunAt)}</span>
                </button>
              ))}
            </div>
          )}
          <div className="mt-3 flex gap-2">
            <button
              type="button"
              onClick={() => setCreatingRoutine(true)}
              className="flex flex-1 items-center justify-center gap-1.5 rounded-lg bg-accent py-2 text-[13px] font-medium text-white hover:brightness-110"
            >
              <Plus size={14} />
              {t("computer.routines.create")}
            </button>
            <button
              type="button"
              onClick={() => dispatch({ type: "showRoutines" })}
              className="flex items-center justify-center gap-1.5 rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover"
              title={t("computer.routines.openTitle")}
            >
              <CalendarDays size={14} />
              {t("computer.routines.schedules")}
            </button>
          </div>
        </div>
      </div>
      )}
      {creatingRoutine && (
        <RoutineEditor
          bots={[bot]}
          lockedBotId={bot.id}
          defaultRunOn={cloudRoutineReady ? "cloud" : "maus"}
          onClose={() => setCreatingRoutine(false)}
        />
      )}
    </aside>
  );
}