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.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: tell the browser about the bootstrap shutdown deadline (#10104)
Daniel Han166a4a961c96
diff --git a/studio/backend/auth/bootstrap_timeout.py b/studio/backend/auth/bootstrap_timeout.pyindex 97a8086f048..2653c6e9857 100644--- a/studio/backend/auth/bootstrap_timeout.py+++ b/studio/backend/auth/bootstrap_timeout.py@@ -18,10 +18,34 @@ key rather than the admin password, and never Colab). Configurable viaimport osimport sysimport threading+import time+from typing import OptionalBOOTSTRAP_TIMEOUT_ENV_VAR = "UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT"DEFAULT_BOOTSTRAP_TIMEOUT_SECONDS = 3600+# Monotonic expiry, or None when nothing is armed. Read back over HTTP because the+# stderr warning is lost on the launches that arm it (--secure, external bind).+_deadline_at: Optional[float] = None+++def record_bootstrap_deadline(timeout_seconds: int) -> None:+ global _deadline_at+ _deadline_at = time.monotonic() + timeout_seconds if timeout_seconds > 0 else None+++def clear_bootstrap_deadline() -> None:+ global _deadline_at+ _deadline_at = None+++def bootstrap_deadline_remaining_seconds() -> Optional[int]:+ """Seconds until shutdown, or None when this launch is not time-boxed.+ Floors at 0: a caller can land between expiry and the shutdown completing."""+ if _deadline_at is None:+ return None+ return max(0, int(round(_deadline_at - time.monotonic())))+def bootstrap_timeout_seconds(env = None) -> int:"""Resolve the deadline in seconds. ``0`` (or invalid/negative) disables it.@@ -134,6 +158,7 @@ def arm_bootstrap_timeout(logger = None,) -> "threading.Timer":"""Start a daemon timer that enforces the deadline. Returns the Timer."""+ record_bootstrap_deadline(timeout_seconds)timer = threading.Timer(timeout_seconds,enforce_bootstrap_password_deadline,diff --git a/studio/backend/models/auth.py b/studio/backend/models/auth.pyindex 52e01ea0720..9eabc6d4ee8 100644--- a/studio/backend/models/auth.py+++ b/studio/backend/models/auth.py@@ -41,6 +41,13 @@ class AuthStatusResponse(BaseModel):...,description = "True if the seeded admin must still change the default password",)+ bootstrap_deadline_seconds: Optional[int] = Field(+ None,+ description = (+ "Seconds until this instance shuts down for leaving the default password "+ "unchanged, or null when the launch is not time-boxed."+ ),+ )class DesktopInitialPasswordRequest(BaseModel):diff --git a/studio/backend/routes/auth.py b/studio/backend/routes/auth.pyindex 33e2052f687..e8f463bfbb9 100644--- a/studio/backend/routes/auth.py+++ b/studio/backend/routes/auth.py@@ -440,12 +440,21 @@ def identity(nonce: str, request: Request) -> dict:@router.get("/status", response_model = AuthStatusResponse)def auth_status() -> AuthStatusResponse:"""Auth initialization state; ``default_username`` is exposed for first-boot UI prefill only."""+ from auth.bootstrap_timeout import bootstrap_deadline_remaining_seconds++ requires_change = (+ storage.requires_password_change(storage.DEFAULT_ADMIN_USERNAME)+ if storage.is_initialized()+ else True+ )+ # Only while the default password stands: that is what the deadline fires on.return AuthStatusResponse(initialized = storage.is_initialized(),default_username = storage.DEFAULT_ADMIN_USERNAME,- requires_password_change = storage.requires_password_change(storage.DEFAULT_ADMIN_USERNAME)- if storage.is_initialized()- else True,+ requires_password_change = requires_change,+ bootstrap_deadline_seconds = (+ bootstrap_deadline_remaining_seconds() if requires_change else None+ ),)diff --git a/studio/backend/tests/test_auth_status_bootstrap_deadline.py b/studio/backend/tests/test_auth_status_bootstrap_deadline.pynew file mode 100644index 00000000000..316d8b65309--- /dev/null+++ b/studio/backend/tests/test_auth_status_bootstrap_deadline.py@@ -0,0 +1,111 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The shutdown deadline has to reach the browser: it arms only for an exposed web+UI (`--secure`, external bind), and those launches run detached or tunneled, where+nothing reads stderr."""++import time++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++from auth.bootstrap_timeout import (+ clear_bootstrap_deadline,+ record_bootstrap_deadline,+)+from routes import auth as auth_routes+++def client():+ app = FastAPI()+ app.include_router(auth_routes.router, prefix = "/api/auth")+ with TestClient(app) as test_client:+ yield test_client++[email protected](autouse = True)+def _no_leaked_deadline():+ clear_bootstrap_deadline()+ yield+ clear_bootstrap_deadline()+++def _status(client):+ response = client.get("/api/auth/status")+ assert response.status_code == 200+ return response.json()+++def _password_state(monkeypatch, *, requires_change: bool):+ """Pin what the route reads. ``is_initialized`` goes with it: the route answers+ True for an uninitialized instance without consulting the other call, and a fresh+ checkout (CI) has no users."""+ monkeypatch.setattr(auth_routes.storage, "is_initialized", lambda: True)+ monkeypatch.setattr(+ auth_routes.storage, "requires_password_change", lambda _username: requires_change+ )+++class TestTheFieldIsPresent:+ def test_absent_deadline_is_null_not_missing(self, client):+ """A client that always reads the key must not find undefined there."""+ body = _status(client)+ assert "bootstrap_deadline_seconds" in body+ assert body["bootstrap_deadline_seconds"] is None++ def test_an_armed_deadline_is_reported(self, client, monkeypatch):+ _password_state(monkeypatch, requires_change = True)+ record_bootstrap_deadline(3600)+ remaining = _status(client)["bootstrap_deadline_seconds"]+ assert remaining is not None and 3590 <= remaining <= 3600++ def test_it_counts_down_between_calls(self, client, monkeypatch):+ _password_state(monkeypatch, requires_change = True)+ record_bootstrap_deadline(3600)+ first = _status(client)["bootstrap_deadline_seconds"]+ import auth.bootstrap_timeout as bt++ bt._deadline_at = bt._deadline_at - 120+ second = _status(client)["bootstrap_deadline_seconds"]+ assert second < first+++class TestItIsNotReportedWhenItCannotFire:+ """A countdown after the password changed would promise a shutdown the handler declines."""++ def test_a_changed_password_reports_no_deadline(self, client, monkeypatch):+ record_bootstrap_deadline(3600)+ _password_state(monkeypatch, requires_change = False)+ body = _status(client)+ assert body["requires_password_change"] is False+ assert body["bootstrap_deadline_seconds"] is None++ def test_the_timer_being_armed_is_not_enough_on_its_own(self, client, monkeypatch):+ """Arming is never undone on a password change, so the timer alone cannot answer this."""+ record_bootstrap_deadline(60)+ _password_state(monkeypatch, requires_change = False)+ assert _status(client)["bootstrap_deadline_seconds"] is None+ _password_state(monkeypatch, requires_change = True)+ assert _status(client)["bootstrap_deadline_seconds"] is not None+++class TestTheNumberIsUsable:+ def test_an_expired_deadline_reads_zero_not_negative(self, client, monkeypatch):+ """A negative would print as "shuts down in -12 minutes"."""+ _password_state(monkeypatch, requires_change = True)+ record_bootstrap_deadline(1)+ import auth.bootstrap_timeout as bt++ bt._deadline_at = time.monotonic() - 5+ assert _status(client)["bootstrap_deadline_seconds"] == 0++ def test_the_endpoint_stays_anonymous(self, client, monkeypatch):+ """The deadline is implied by requires_password_change, already returned here."""+ _password_state(monkeypatch, requires_change = True)+ record_bootstrap_deadline(3600)+ response = client.get("/api/auth/status")+ assert response.status_code == 200+ assert response.json()["bootstrap_deadline_seconds"] is not Nonediff --git a/studio/backend/tests/test_bootstrap_timeout.py b/studio/backend/tests/test_bootstrap_timeout.pyindex 58d4829215c..d9d09cf8739 100644--- a/studio/backend/tests/test_bootstrap_timeout.py+++ b/studio/backend/tests/test_bootstrap_timeout.py@@ -8,13 +8,18 @@ handler (shut down iff the seeded admin password is still unchanged). Thethreading.Timer itself is not exercised; the handler is invoked directly."""+import timefrom types import SimpleNamespacefrom auth.bootstrap_timeout import (DEFAULT_BOOTSTRAP_TIMEOUT_SECONDS,_format_duration,+ arm_bootstrap_timeout,+ bootstrap_deadline_remaining_seconds,bootstrap_timeout_seconds,+ clear_bootstrap_deadline,enforce_bootstrap_password_deadline,+ record_bootstrap_deadline,should_arm_bootstrap_timeout,)@@ -183,3 +188,52 @@ def test_shutdown_message_uses_formatted_duration():)assert any("60 minutes" in m for m in logged)assert not any("minute(s)" in m for m in logged)+++def test_no_deadline_reported_when_nothing_armed():+ clear_bootstrap_deadline()+ assert bootstrap_deadline_remaining_seconds() is None+++def test_recorded_deadline_counts_down():+ record_bootstrap_deadline(3600)+ try:+ remaining = bootstrap_deadline_remaining_seconds()+ assert remaining is not None+ # Allow for the clock moving between the two calls.+ assert 3595 <= remaining <= 3600+ finally:+ clear_bootstrap_deadline()+++def test_a_disabled_timeout_records_no_deadline():+ """None means not time-boxed, which is a different answer from an expired 0."""+ record_bootstrap_deadline(0)+ assert bootstrap_deadline_remaining_seconds() is None+++def test_an_expired_deadline_floors_at_zero_rather_than_going_negative():+ """The timer and this clock are read separately, so a caller can land in the gap."""+ record_bootstrap_deadline(1)+ try:+ import auth.bootstrap_timeout as bt+ bt._deadline_at = time.monotonic() - 30+ assert bootstrap_deadline_remaining_seconds() == 0+ finally:+ clear_bootstrap_deadline()+++def test_arming_publishes_the_deadline():+ """Arming is the only thing that starts the clock, so it must be what records it."""+ clear_bootstrap_deadline()+ timer = arm_bootstrap_timeout(+ _fake_storage(requires_change = True),+ lambda: None,+ timeout_seconds = 1800,+ )+ try:+ remaining = bootstrap_deadline_remaining_seconds()+ assert remaining is not None and 1795 <= remaining <= 1800+ finally:+ timer.cancel()+ clear_bootstrap_deadline()diff --git a/studio/frontend/src/features/auth/bootstrap-deadline.ts b/studio/frontend/src/features/auth/bootstrap-deadline.tsnew file mode 100644index 00000000000..19ac5dbb368--- /dev/null+++ b/studio/frontend/src/features/auth/bootstrap-deadline.ts@@ -0,0 +1,34 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/** Split out of auth-form.tsx so the tests can reach it: the runner is+ * `node --experimental-strip-types`, which does not transform JSX, so nothing+ * importable from a .tsx file is unit-testable. */++/** Absolute expiry in epoch ms, or null when the launch is not time-boxed.+ * Absolute rather than a stored countdown: a backgrounded tab stops firing timers+ * and must still render the right figure when it wakes. */+export function deadlineFromStatus(+ seconds: number | null | undefined,+ now: number,+): number | null {+ if (typeof seconds !== "number" || !Number.isFinite(seconds)) {+ return null;+ }+ return now + seconds * 1000;+}++/** Coarse on purpose: the deadline is an hour, so per-second ticks are noise. */+export function formatCountdown(remainingMs: number): string {+ const totalSeconds = Math.max(0, Math.round(remainingMs / 1000));+ if (totalSeconds < 60) {+ return `${totalSeconds} second${totalSeconds === 1 ? "" : "s"}`;+ }+ const minutes = Math.round(totalSeconds / 60);+ return `${minutes} minute${minutes === 1 ? "" : "s"}`;+}++/** A stale tab must not sit on "shuts down in 0 seconds" once the deadline passes. */+export function hasExpired(remainingMs: number): boolean {+ return remainingMs <= 0;+}diff --git a/studio/frontend/src/features/auth/components/auth-form.tsx b/studio/frontend/src/features/auth/components/auth-form.tsxindex 4495cfadaa2..fb5aed4bb66 100644--- a/studio/frontend/src/features/auth/components/auth-form.tsx+++ b/studio/frontend/src/features/auth/components/auth-form.tsx@@ -12,6 +12,11 @@ import { useEffect, useRef, useState } from "react";import type { ReactElement } from "react";import type { SyntheticEvent } from "react";import { refreshSession } from "../api";+import {+ deadlineFromStatus,+ formatCountdown,+ hasExpired,+} from "../bootstrap-deadline";// Bootstrap credentials injected into index.html by the backend (only present// while default admin must_change_password is true)@@ -37,6 +42,7 @@ type AuthMode = "login" | "change-password";type AuthStatusResponse = {initialized: boolean;requires_password_change: boolean;+ bootstrap_deadline_seconds?: number | null;};type TokenResponse = {@@ -88,8 +94,18 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {const [initialized, setInitialized] = useState<boolean | null>(null);const [requiresPasswordChange, setRequiresPasswordChange] = useState(false);const [error, setError] = useState<string | null>(null);+ const [deadlineAt, setDeadlineAt] = useState<number | null>(null);+ const [nowMs, setNowMs] = useState<number>(() => Date.now());const reloadReadySent = useRef(false);+ useEffect(() => {+ if (deadlineAt === null) {+ return;+ }+ const id = window.setInterval(() => setNowMs(Date.now()), 1000);+ return () => window.clearInterval(id);+ }, [deadlineAt]);+useEffect(() => {let canceled = false;@@ -104,6 +120,14 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {if (!canceled) {setInitialized(result.initialized);setRequiresPasswordChange(result.requires_password_change);+ // One clock sample for both: nowMs is otherwise still the mount time+ // until the first tick, which adds the request duration to the figure+ // and renders a 0 from the server as "shuts down in 0 seconds".+ const sampledNow = Date.now();+ setNowMs(sampledNow);+ setDeadlineAt(+ deadlineFromStatus(result.bootstrap_deadline_seconds, sampledNow),+ );// Server truth wins; keep localStorage in sync both ways.if (result.requires_password_change !== mustChangePassword()) {@@ -330,6 +354,24 @@ export function AuthForm({ mode }: AuthFormProps): ReactElement | null {<h2 className="text-2xl font-semibold text-foreground">{title}</h2><p className="text-muted-foreground">{subtitle}</p></div>+ {/* Not a live region: it re-renders every second, so it would be read aloud on every tick. */}+ {deadlineAt !== null && (+ <p className="rounded-md border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-center text-sm text-amber-600">+ {hasExpired(deadlineAt - nowMs) ? (+ <>+ This instance is shutting down: it was reachable on the network+ and its default password was never changed.+ </>+ ) : (+ <>+ This instance is reachable on the network and still uses its+ default password, so it shuts down in{" "}+ {formatCountdown(deadlineAt - nowMs)}. Setting a password here+ keeps it running.+ </>+ )}+ </p>+ )}<form className="space-y-5" onSubmit={handleSubmit}>{isLoginMode && (<div className="space-y-2">diff --git a/studio/frontend/tests/auth-bootstrap-deadline.test.ts b/studio/frontend/tests/auth-bootstrap-deadline.test.tsnew file mode 100644index 00000000000..726cf72cdd2--- /dev/null+++ b/studio/frontend/tests/auth-bootstrap-deadline.test.ts@@ -0,0 +1,87 @@+// 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 assert from "node:assert/strict";+import { test } from "node:test";++import {+ deadlineFromStatus,+ formatCountdown,+ hasExpired,+} from "../src/features/auth/bootstrap-deadline.ts";++test("a server that does not send the field is not time-boxed", () => {+ // A pre-deadline backend omits the key; a countdown from undefined prints "NaN".+ assert.equal(deadlineFromStatus(undefined, 1_000_000), null);+ assert.equal(deadlineFromStatus(null, 1_000_000), null);+});++test("a loopback launch sends null and gets no countdown", () => {+ assert.equal(deadlineFromStatus(null, 0), null);+});++test("seconds are turned into an absolute expiry", () => {+ // Absolute, so a backgrounded tab whose timers stopped still renders correctly.+ assert.equal(deadlineFromStatus(3600, 1_000_000), 1_000_000 + 3_600_000);+});++test("zero seconds is a real deadline, not an absent one", () => {+ assert.equal(deadlineFromStatus(0, 500), 500);+});++test("a non-numeric or non-finite value is refused", () => {+ assert.equal(deadlineFromStatus(Number.NaN, 0), null);+ assert.equal(deadlineFromStatus(Number.POSITIVE_INFINITY, 0), null);+ assert.equal(deadlineFromStatus("3600" as unknown as number, 0), null);+});++test("under a minute reads in seconds", () => {+ assert.equal(formatCountdown(45_000), "45 seconds");+ assert.equal(formatCountdown(59_400), "59 seconds");+});++test("one second is singular", () => {+ assert.equal(formatCountdown(1000), "1 second");+});++test("a minute or more reads in minutes", () => {+ assert.equal(formatCountdown(60_000), "1 minute");+ assert.equal(formatCountdown(3_600_000), "60 minutes");+ assert.equal(formatCountdown(2_520_000), "42 minutes");+});++test("it never renders a negative", () => {+ // The tab keeps ticking past the deadline; "-12 minutes" is worse than nothing.+ assert.equal(formatCountdown(-1), "0 seconds");+ assert.equal(formatCountdown(-10_000_000), "0 seconds");+});++test("expiry is inclusive of zero", () => {+ assert.equal(hasExpired(1), false);+ assert.equal(hasExpired(0), true);+ assert.equal(hasExpired(-1), true);+});++test("the boundary between the two messages is one tick wide", () => {+ assert.equal(hasExpired(0), true);+ assert.equal(formatCountdown(0), "0 seconds");+ assert.ok(+ hasExpired(0),+ "0 must select the shutting-down copy, not the countdown",+ );+});++test("the deadline and the clock it is compared against must be one sample", () => {+ // A request that takes 30ms turns a server 0 back into a positive remainder,+ // which selects the countdown copy and prints "shuts down in 0 seconds".+ const mounted = 1_000_000;+ const responded = mounted + 30;+ const stale = deadlineFromStatus(0, responded);+ assert.ok(stale !== null);+ assert.equal(hasExpired(stale - mounted), false);+ assert.equal(formatCountdown(stale - mounted), "0 seconds");++ const sampled = deadlineFromStatus(0, responded);+ assert.ok(sampled !== null);+ assert.equal(hasExpired(sampled - responded), true);+});