Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

18.7 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0

import { DiagnosticsCopyActions } from "@/components/tauri/diagnostics-copy-actions";
import InstallLocation from "@/components/tauri/install-location";
import { LogDetails } from "@/components/tauri/log-details";
import {
  installProgressMessage,
  startupWaitingMessage,
  STATUS_MESSAGE_ROTATION_MS,
  type StartupMessage,
} from "@/components/tauri/startup-messages";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { Label } from "@/components/ui/label";
import { Spinner } from "@/components/ui/spinner";
import type { BackendStatus } from "@/hooks/use-tauri-backend";
import { useT } from "@/i18n";
import { useDocumentFlag } from "@/lib/document-flag";
import type { CopySupportDiagnosticsResult } from "@/lib/tauri-diagnostics";
import {
  enableWindowsLongPaths,
  windowsLongPathsNeedPrompt,
} from "@/lib/windows-long-paths";

import { AnimatePresence, motion } from "motion/react";
import { type ReactNode, useEffect, useRef, useState } from "react";
import { MODAL_SURFACE, useSurfaceRef } from "@/lib/surface-registry";

interface StartupScreenProps {
  status: BackendStatus;
  logs: string[];
  error: string | null;
  diskFull: boolean;
  currentStepIndex: number;
  progressDetail: string | null;
  startupMessage: StartupMessage;
  elevationPackages: string[];
  upgradingToFull?: boolean;
  onInstall: (options?: InstallOptions) => void;
  onRetry: () => void;
  onRetryInstall: () => void;
  onApproveElevation: () => void;
  onStartServer: () => void;
  onCopyDiagnostics: () => Promise<CopySupportDiagnosticsResult>;
}

const EASE_OUT_QUART: [number, number, number, number] = [0.165, 0.84, 0.44, 1];

// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
function Logo() {
  return (
    <div className="flex items-center justify-center gap-3">
      <img
        src="/sticker.png"
        alt=""
        aria-hidden="true"
        className="h-[calc(60px*var(--ui-space-scale,1))] w-[calc(60px*var(--ui-space-scale,1))] object-contain"
      />
      <span
        className="text-ui-50 font-semibold leading-none tracking-[-0.02em] text-foreground"
        style={{ fontFamily: '"Hellix", sans-serif' }}
      >
        unsloth
      </span>
    </div>
  );
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

function CheckingContent() {
  const t = useT();
  return (
    <div className="flex h-full flex-col items-center">
      <div className="flex flex-1 items-center">
        <Logo />
      </div>
      <div className="mb-10 flex flex-col items-center gap-2">
        <Spinner className="size-6 text-primary" />
        <p className="text-sm text-muted-foreground">{t("desktopStartup.checking")}</p>
      </div>
    </div>
  );
}

type InstallOptions = { skipLongPaths?: boolean; chatOnly?: boolean };

function NotInstalledContent({
  onInstall,
}: {
  onInstall: (options?: InstallOptions) => void;
}) {
  const [phase, setPhase] = useState<
    "idle" | "checking" | "explain" | "elevating"
  >("idle");
  const [chatOnly, setChatOnly] = useState(false);
  const t = useT();

  // Synchronous: a double click lands before the re-render that disables the buttons.
  const busy = useRef(false);

  async function getStarted() {
    if (busy.current) {
      return;
    }
    busy.current = true;
    setPhase("checking");
    if (await windowsLongPathsNeedPrompt()) {
      busy.current = false;
      setPhase("explain");
    } else {
      onInstall({ chatOnly });
    }
  }

  async function allowLongPaths() {
    if (busy.current) {
      return;
    }
    busy.current = true;
    setPhase("elevating");
    const outcome = await enableWindowsLongPaths();
    // "failed" leaves setup.ps1's own UAC as the fallback.
    onInstall({ skipLongPaths: outcome === "declined", chatOnly });
  }

  function skipLongPaths() {
    if (busy.current) {
      return;
    }
    busy.current = true;
    onInstall({ skipLongPaths: true, chatOnly });
  }

  if (phase === "explain" || phase === "elevating") {
    return (
      <LongPathsExplainer
        waiting={phase === "elevating"}
        onContinue={allowLongPaths}
        onSkip={skipLongPaths}
      />
    );
  }

  return (
    <div className="flex h-full flex-col items-center">
      <div className="flex flex-1 flex-col items-center justify-center">
        <Logo />
      </div>
      <div className="mb-10 flex flex-col items-center gap-3">
        <p
          className="text-ui-13 font-semibold tracking-[-0.01em] text-muted-foreground"
          style={{ fontFamily: '"Hellix", sans-serif' }}
        >
          {t("desktopStartup.installPrompt")}
        </p>
        <Button
          variant="dark"
          size="hero"
          onClick={getStarted}
          disabled={phase === "checking"}
        >
          {t("desktopStartup.getStarted")}
        </Button>
        <div className="flex items-center gap-2">
          <Checkbox
            id="install-chat-only"
            checked={chatOnly}
            disabled={phase !== "idle"}
            onCheckedChange={(checked) => setChatOnly(checked === true)}
          />
          <Label
            htmlFor="install-chat-only"
            className="text-ui-12 font-normal text-muted-foreground"
          >
            {t("desktopStartup.chatOnly")}
          </Label>
        </div>
        <InstallLocation disabled={phase !== "idle"} />
      </div>
    </div>
  );
}

function LongPathsExplainer({
  waiting,
  onContinue,
  onSkip,
}: {
  waiting: boolean;
  onContinue: () => void;
  onSkip: () => void;
}) {
  const t = useT();
  const [approveBefore, approveAfter] = t("desktopStartup.longPaths.approve").split("{tool}");
  return (
    <>
      <Logo />
      <div className="mt-8 flex max-w-md flex-col items-center gap-2">
        <p className="text-sm font-medium text-foreground">
          {t("desktopStartup.longPaths.title")}
        </p>
        <p className="text-xs text-muted-foreground">
          {approveBefore}
          <span className="font-medium text-foreground">Registry Console Tool</span>
          {approveAfter}
        </p>
        {waiting ? (
          <div className="mt-4 flex items-center gap-2">
            <Spinner className="size-4 text-primary" />
            <p className="text-xs text-muted-foreground" aria-live="polite">
              {t("desktopStartup.longPaths.waiting")}
            </p>
          </div>
        ) : (
          <div className="mt-4 flex gap-3">
            <Button variant="muted" size="hero" onClick={onSkip}>
              {t("desktopStartup.skip")}
            </Button>
            <Button variant="dark" size="hero" onClick={onContinue}>
              {t("desktopStartup.continue")}
            </Button>
          </div>
        )}
      </div>
    </>
  );
}

function useRotatingMessageIndex(): number {
  const [messageIndex, setMessageIndex] = useState(0);

  useEffect(() => {
    const interval = window.setInterval(
      () => setMessageIndex((current) => current + 1),
      STATUS_MESSAGE_ROTATION_MS,
    );
    return () => window.clearInterval(interval);
  }, []);

  return messageIndex;
}

function InstallingContent({
  logs,
  currentStepIndex,
  progressDetail,
}: {
  logs: string[];
  currentStepIndex: number;
  progressDetail: string | null;
}) {
  const t = useT();
  const messageIndex = useRotatingMessageIndex();
  const message = installProgressMessage(currentStepIndex, messageIndex);
  const detailLines = progressDetail
    ? [...logs, progressDetail]
    : logs;

  return (
    <div className="flex h-full w-full flex-col items-center">
      <div className="flex flex-1 items-center">
        <Logo />
      </div>
      <div className="mb-10 flex w-full flex-col items-center gap-2">
        <Spinner className="size-6 text-primary" />
        <p className="text-sm font-bold text-foreground" aria-live="polite">
          {t(message.title)}
        </p>
        <p className="text-sm text-muted-foreground">{t(message.subtitle)}</p>
        <LogDetails
          showLabel={t("desktopStartup.details.showInstall")}
          hideLabel={t("desktopStartup.details.hideInstall")}
          lines={detailLines}
        />
      </div>
    </div>
  );
}

function RepairingContent({
  logs,
  progressDetail,
  upgradingToFull,
}: {
  logs: string[];
  progressDetail: string | null;
  upgradingToFull: boolean;
}) {
  const t = useT();
  const detailLines = progressDetail
    ? [...logs, progressDetail]
    : logs;

  return (
    <div className="flex h-full w-full flex-col items-center">
      <div className="flex flex-1 items-center">
        <Logo />
      </div>
      <div className="mb-10 flex w-full flex-col items-center gap-2">
        <Spinner className="size-6 text-primary" />
        <p className="text-sm font-bold text-foreground">
          {upgradingToFull
            ? t("desktopStartup.repair.upgrading")
            : t("desktopStartup.repair.gettingReady")}
        </p>
        <p className="text-sm text-muted-foreground">
          {upgradingToFull
            ? t("desktopStartup.repair.upgradingDetail")
            : t("desktopStartup.repair.wontTakeLong")}
        </p>
        <LogDetails
          showLabel={t("desktopStartup.details.showSetup")}
          hideLabel={t("desktopStartup.details.hideSetup")}
          lines={detailLines}
        />
      </div>
    </div>
  );
}

function ClosingContent() {
  const t = useT();
  return (
    <div className="flex h-full w-full flex-col items-center">
      <div className="flex flex-1 items-center">
        <Logo />
      </div>
      <div className="mb-10 flex w-full flex-col items-center gap-2">
        <Spinner className="size-6 text-primary" />
        <p className="text-sm font-bold text-foreground" aria-live="polite">
          {t("desktopStartup.closing")}
        </p>
        <p className="text-sm text-muted-foreground">{t("desktopStartup.closingDetail")}</p>
      </div>
    </div>
  );
}

function InstallErrorContent({
  error,
  diskFull,
  onRetryInstall,
  onCopyDiagnostics,
}: {
  error: string | null;
  diskFull: boolean;
  onRetryInstall: () => void;
  onCopyDiagnostics: () => Promise<CopySupportDiagnosticsResult>;
}) {
  const t = useT();
  return (
    <>
      <Logo />
      <div className="mt-8 flex flex-col items-center gap-2">
        <p className="text-sm font-medium text-destructive">
          {diskFull ? t("desktopStartup.diskFull") : t("desktopStartup.setupFailed")}
        </p>
        {error && (
          <p className="max-w-xs text-center text-xs text-muted-foreground">{error}</p>
        )}
        <DiagnosticsCopyActions onCopyDiagnostics={onCopyDiagnostics}>
          <Button variant="dark" size="hero" onClick={onRetryInstall}>
            {t("desktopStartup.tryAgain")}
          </Button>
        </DiagnosticsCopyActions>
      </div>
    </>
  );
}

function RepairErrorContent({
  error,
  upgradingToFull,
  onRetry,
  onCopyDiagnostics,
}: {
  error: string | null;
  upgradingToFull: boolean;
  onRetry: () => void;
  onCopyDiagnostics: () => Promise<CopySupportDiagnosticsResult>;
}) {
  const t = useT();
  return (
    <>
      <Logo />
      <div className="mt-8 flex flex-col items-center gap-2">
        <p className="text-sm font-medium text-destructive">
          {upgradingToFull
            ? t("desktopStartup.repair.upgradeFailed")
            : t("desktopStartup.repair.updateFailed")}
        </p>
        {error && (
          <p className="max-w-md text-center text-xs text-muted-foreground">{error}</p>
        )}
        <DiagnosticsCopyActions onCopyDiagnostics={onCopyDiagnostics}>
          <Button variant="dark" size="hero" onClick={onRetry}>
            {t("desktopStartup.retry")}
          </Button>
        </DiagnosticsCopyActions>
      </div>
    </>
  );
}

function NeedsElevationContent({
  elevationPackages,
  onApproveElevation,
  onRetryInstall,
}: {
  elevationPackages: string[];
  onApproveElevation: () => void;
  onRetryInstall: () => void;
}) {
  const t = useT();
  return (
    <>
      <Logo />
      <div className="mt-8 flex flex-col items-center gap-2">
        <p className="text-sm font-medium text-foreground">
          {t("desktopStartup.elevation.title")}
        </p>
        <p className="text-xs text-muted-foreground">
          {t("desktopStartup.elevation.packages")}
        </p>
        <div className="mt-2 w-full max-w-xs rounded-lg bg-muted p-3 font-mono text-xs">
          {elevationPackages.map((pkg) => (
            <div key={pkg}>{pkg}</div>
          ))}
        </div>
        <div className="mt-4 flex gap-3">
          <Button variant="muted" size="hero" onClick={onRetryInstall}>
            {t("common.cancel")}
          </Button>
          <Button variant="dark" size="hero" onClick={onApproveElevation}>
            {t("desktopStartup.elevation.allow")}
          </Button>
        </div>
      </div>
    </>
  );
}

function StartingContent({ message }: { message: StartupMessage }) {
  const t = useT();
  const messageIndex = useRotatingMessageIndex();
  const displayMessage = t(startupWaitingMessage(message, messageIndex));

  return (
    <div className="flex h-full flex-col items-center">
      <div className="flex flex-1 items-center">
        <Logo />
      </div>
      <div className="mb-10 flex flex-col items-center gap-2">
        <Spinner className="size-6 text-primary" />
        <p className="text-sm text-muted-foreground">{displayMessage}</p>
      </div>
    </div>
  );
}

function StoppedContent({ onStartServer }: { onStartServer: () => void }) {
  const t = useT();
  return (
    <>
      <Logo />
      <div className="mt-8 flex flex-col items-center gap-2">
        <p className="text-sm font-medium text-foreground">{t("desktopStartup.serverStopped")}</p>
        <div className="mt-4">
          <Button variant="dark" size="hero" onClick={onStartServer}>
            {t("desktopStartup.startServer")}
          </Button>
        </div>
      </div>
    </>
  );
}

function ErrorContent({
  error,
  onRetry,
  onCopyDiagnostics,
}: {
  error: string | null;
  onRetry: () => void;
  onCopyDiagnostics: () => Promise<CopySupportDiagnosticsResult>;
}) {
  const t = useT();
  return (
    <>
      <Logo />
      <div className="mt-8 flex flex-col items-center gap-2">
        <p className="text-sm font-medium text-destructive">{t("desktopStartup.somethingWrong")}</p>
        {error && (
          <p className="max-w-md text-center text-xs text-muted-foreground">{error}</p>
        )}
        <DiagnosticsCopyActions onCopyDiagnostics={onCopyDiagnostics}>
          <Button variant="dark" size="hero" onClick={onRetry}>
            {t("desktopStartup.retry")}
          </Button>
        </DiagnosticsCopyActions>
      </div>
    </>
  );
}

// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
export function StartupScreen({
  status,
  logs,
  error,
  diskFull,
  currentStepIndex,
  progressDetail,
  startupMessage,
  elevationPackages,
  upgradingToFull = false,
  onInstall,
  onRetry,
  onRetryInstall,
  onApproveElevation,
  onStartServer,
  onCopyDiagnostics,
}: StartupScreenProps) {
  function renderContent() {
    switch (status) {
      case "checking":
        return <CheckingContent />;
      case "not-installed":
        return <NotInstalledContent onInstall={onInstall} />;
      case "installing":
        return (
          <InstallingContent
            logs={logs}
            currentStepIndex={currentStepIndex}
            progressDetail={progressDetail}
          />
        );
      case "install-error":
        return (
          <InstallErrorContent
            error={error}
            diskFull={diskFull}
            onRetryInstall={onRetryInstall}
            onCopyDiagnostics={onCopyDiagnostics}
          />
        );
      case "repairing":
        return (
          <RepairingContent
            logs={logs}
            progressDetail={progressDetail}
            upgradingToFull={upgradingToFull}
          />
        );
      case "repair-error":
        return (
          <RepairErrorContent
            error={error}
            upgradingToFull={upgradingToFull}
            onRetry={onRetry}
            onCopyDiagnostics={onCopyDiagnostics}
          />
        );
      case "needs-elevation":
        return (
          <NeedsElevationContent
            elevationPackages={elevationPackages}
            onApproveElevation={onApproveElevation}
            onRetryInstall={onRetryInstall}
          />
        );
      case "starting":
        return <StartingContent key={startupMessage} message={startupMessage} />;
      case "running":
        return null;
      case "stopped":
        return <StoppedContent onStartServer={onStartServer} />;
      case "error":
        return (
          <ErrorContent
            error={error}
            onRetry={onRetry}
            onCopyDiagnostics={onCopyDiagnostics}
          />
        );
    }
  }

  return (
    <StartupSurface>
      <AnimatePresence mode="wait">
        <motion.div
          key={status}
          className="flex h-full w-full flex-col items-center justify-center text-center"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          transition={{ duration: 0.2, ease: EASE_OUT_QUART }}
        >
          {renderContent()}
        </motion.div>
      </AnimatePresence>
    </StartupSurface>
  );
}

/** The chrome both full-window screens sit in, so they agree on insets and scrolling. */
function StartupSurface({ children }: { children: ReactNode }) {
  return (
    <div className="box-border flex h-full w-full flex-col items-center overflow-y-auto bg-background pb-6 pt-[var(--studio-startup-top-inset,0px)]">
      <div className="flex min-h-0 flex-1 w-full max-w-md items-center justify-center px-6">
        {children}
      </div>
    </div>
  );
}

/**
 * Shown from quit request until exit. An overlay, not a replacement, so a declined quit returns
 * the live tree; Z_LAYER.STARTUP_SCREEN clears the titlebar and floating panels.
 */
export function ClosingScreen() {
  useDocumentFlag("data-blocking-screen-open", true);
  const blockingScreenRef = useSurfaceRef<HTMLDivElement>(MODAL_SURFACE);
  return (
    // pointer-events-auto: Radix parks pointer-events:none on <body> while a modal is open, which
    // would make this overlay click-through onto the hidden dialog.
    <div
      ref={blockingScreenRef}
      data-blocking-screen=""
      className="pointer-events-auto modal-pe-live fixed inset-0 z-[9999]"
    >
      <StartupSurface>
        <div className="flex h-full w-full flex-col items-center justify-center text-center">
          <ClosingContent />
        </div>
      </StartupSurface>
    </div>
  );
}