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.

fix: add auth + UX improvements to shutdown button (#4642)

Wasim Yousef Said887b8cb1c277
diff --git a/studio/backend/main.py b/studio/backend/main.py
index 5e647f63120..65f5e7fe901 100644
--- a/studio/backend/main.py
+++ b/studio/backend/main.py
@@ -34,7 +34,7 @@ if os.getenv("ENVIRONMENT_TYPE", "production") == "production":
# warnings.filterwarnings("ignore", category=DeprecationWarning)
# warnings.filterwarnings("ignore", module="triton.*")
-from fastapi import FastAPI
+from fastapi import Depends, FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, HTMLResponse, Response
@@ -53,6 +53,7 @@ from routes import (
training_router,
)
from auth import storage
+from auth.authentication import get_current_subject
from utils.hardware import detect_hardware, get_device, DeviceType
import utils.hardware.hardware as _hw_module
@@ -184,6 +185,34 @@ async def health_check():
}
[email protected]("/api/shutdown")
+async def shutdown_server(
+ request: Request,
+ current_subject: str = Depends(get_current_subject),
+):
+ """Gracefully shut down the Unsloth Studio server.
+
+ Called by the frontend quit dialog so users can stop the server from the UI
+ without needing to use the CLI or kill the process manually.
+ """
+ import asyncio
+
+ async def _delayed_shutdown():
+ await asyncio.sleep(0.2) # Let the HTTP response return first
+ trigger = getattr(request.app.state, "trigger_shutdown", None)
+ if trigger is not None:
+ trigger()
+ else:
+ # Fallback when not launched via run_server() (e.g. direct uvicorn)
+ import signal
+ import os
+
+ os.kill(os.getpid(), signal.SIGTERM)
+
+ request.app.state._shutdown_task = asyncio.create_task(_delayed_shutdown())
+ return {"status": "shutting_down"}
+
+
@app.get("/api/system")
async def get_system_info():
"""Get system information"""
diff --git a/studio/backend/run.py b/studio/backend/run.py
index 87fcdc01da9..18babf6229b 100644
--- a/studio/backend/run.py
+++ b/studio/backend/run.py
@@ -337,6 +337,15 @@ def run_server(
atexit.register(_remove_pid_file)
+ # Expose a shutdown callable via app.state so the /api/shutdown endpoint
+ # can trigger graceful shutdown without circular imports.
+ def _trigger_shutdown():
+ _graceful_shutdown(_server)
+ if _shutdown_event is not None:
+ _shutdown_event.set()
+
+ app.state.trigger_shutdown = _trigger_shutdown
+
if not silent:
display_host = _resolve_external_ip() if host == "0.0.0.0" else host
print_studio_access_banner(
diff --git a/studio/frontend/src/components/navbar.tsx b/studio/frontend/src/components/navbar.tsx
index d90276a641c..5fece2b2b23 100644
--- a/studio/frontend/src/components/navbar.tsx
+++ b/studio/frontend/src/components/navbar.tsx
@@ -17,6 +17,7 @@ import {
import { cn } from "@/lib/utils";
import {
ArrowRight01Icon,
+ StopIcon,
Book03Icon,
BubbleChatIcon,
ChefHatIcon,
@@ -29,8 +30,9 @@ import { useTrainingRuntimeStore } from "@/features/training";
import { usePlatformStore } from "@/config/env";
import { Link, useRouterState } from "@tanstack/react-router";
import { motion } from "motion/react";
-import { useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { TOUR_OPEN_EVENT } from "@/features/tour";
+import { ShutdownDialog } from "@/components/shutdown-dialog";
const NAV_ITEMS = [
{ label: "Studio", href: "/studio", icon: ZapIcon, enabled: true },
@@ -50,9 +52,35 @@ export function Navbar() {
const pathname = useRouterState({ select: (s) => s.location.pathname });
const isTrainingRunning = useTrainingRuntimeStore((s) => s.isTrainingRunning);
const [mobileOpen, setMobileOpen] = useState(false);
+ const [shutdownOpen, setShutdownOpen] = useState(false);
const chatOnly = usePlatformStore((s) => s.isChatOnly());
+ // Warn before closing the tab only when training is running (data loss risk).
+ // We store the handler in a ref so removeUnloadHandler() can clean it up
+ // before the "Server stopped" page renders.
+ const unloadHandlerRef = useRef<((e: BeforeUnloadEvent) => void) | null>(null);
+
+ useEffect(() => {
+ const handler = (e: BeforeUnloadEvent) => {
+ if (!useTrainingRuntimeStore.getState().isTrainingRunning) return;
+ e.preventDefault();
+ e.returnValue = "";
+ };
+ unloadHandlerRef.current = handler;
+ window.addEventListener("beforeunload", handler);
+ return () => {
+ window.removeEventListener("beforeunload", handler);
+ };
+ }, []);
+
+ const removeUnloadHandler = () => {
+ if (unloadHandlerRef.current) {
+ window.removeEventListener("beforeunload", unloadHandlerRef.current);
+ unloadHandlerRef.current = null;
+ }
+ };
+
const tourId = getTourId(pathname);
const openTour = () => {
@@ -63,6 +91,7 @@ export function Navbar() {
};
return (
+ <>
<header className="relative top-0 z-40 h-16 w-full">
<div className="mx-auto grid h-full max-w-7xl grid-cols-[1fr_auto_1fr] items-center px-4 sm:px-6">
{/* Left: logo */}
@@ -206,6 +235,17 @@ export function Navbar() {
<HugeiconsIcon icon={CursorInfo02Icon} className="size-4" />
<span className="text-sm font-medium">Tour</span>
</button>
+
+ <button
+ type="button"
+ onClick={() => setShutdownOpen(true)}
+ className="flex h-9 items-center gap-1.5 rounded-md px-3 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
+ title="Shut down Unsloth Studio server"
+ aria-label="Shut down Unsloth Studio server"
+ >
+ <HugeiconsIcon icon={StopIcon} className="size-4" />
+ <span className="text-sm font-medium">Shutdown</span>
+ </button>
</div>
{/* Right: mobile */}
@@ -292,6 +332,17 @@ export function Navbar() {
Start tour
</button>
) : null}
+ <button
+ type="button"
+ className="flex items-center gap-2 rounded-md border border-border px-3 py-2 text-left text-sm font-medium text-foreground hover:bg-accent"
+ onClick={() => {
+ setMobileOpen(false);
+ setShutdownOpen(true);
+ }}
+ >
+ <HugeiconsIcon icon={StopIcon} className="size-4" />
+ Quit Unsloth Studio
+ </button>
<div className="mt-2 flex items-center justify-between rounded-md border border-border px-3 py-2">
<span className="text-sm font-medium text-foreground">Theme</span>
<AnimatedThemeToggler
@@ -306,5 +357,12 @@ export function Navbar() {
</div>
</div>
</header>
+
+ <ShutdownDialog
+ open={shutdownOpen}
+ onOpenChange={setShutdownOpen}
+ onBeforeShutdown={removeUnloadHandler}
+ />
+ </>
);
}
diff --git a/studio/frontend/src/components/shutdown-dialog.tsx b/studio/frontend/src/components/shutdown-dialog.tsx
new file mode 100644
index 00000000000..dea738bf6bb
--- /dev/null
+++ b/studio/frontend/src/components/shutdown-dialog.tsx
@@ -0,0 +1,84 @@
+// 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 { authFetch } from "@/features/auth";
+import { toastError } from "@/shared/toast";
+import { useState } from "react";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@/components/ui/alert-dialog";
+
+interface ShutdownDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ /** Called right before the shutdown API request so callers can remove the
+ * beforeunload listener — otherwise the "Server stopped" page would still
+ * trigger a "Leave site?" prompt when the user tries to close it. */
+ onBeforeShutdown?: () => void;
+}
+
+export function ShutdownDialog({
+ open,
+ onOpenChange,
+ onBeforeShutdown,
+}: ShutdownDialogProps) {
+ const [stopping, setStopping] = useState(false);
+
+ const handleStop = async () => {
+ setStopping(true);
+ let accepted = false;
+ try {
+ const res = await authFetch("/api/shutdown", { method: "POST" });
+ accepted = res.ok;
+ if (!accepted) {
+ toastError("Failed to shut down server");
+ setStopping(false);
+ return;
+ }
+ } catch {
+ // Network error — shutdown request never reached the server
+ toastError("Could not reach server");
+ setStopping(false);
+ return;
+ }
+
+ onBeforeShutdown?.();
+ document.body.innerHTML = `
+ <div style="display:flex;flex-direction:column;align-items:center;justify-content:center;height:100vh;font-family:sans-serif;gap:12px">
+ <p style="font-size:1.1rem;font-weight:600;margin:0">Unsloth Studio has stopped.</p>
+ <p style="font-size:0.9rem;color:#888;margin:0">You can now close this tab.</p>
+ </div>`;
+ };
+
+ return (
+ <AlertDialog open={open} onOpenChange={onOpenChange}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Stop Unsloth Studio?</AlertDialogTitle>
+ <AlertDialogDescription>
+ This will shut down the server. Any active training or inference
+ jobs will be terminated. You can restart it any time from the
+ desktop shortcut.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Cancel</AlertDialogCancel>
+ <AlertDialogAction
+ onClick={handleStop}
+ disabled={stopping}
+ variant="destructive"
+ >
+ {stopping ? "Stopping…" : "Stop server"}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}