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.

Studio: update in the background and restart when ready (#9890)

Nilaye1653bcd1da8
diff --git a/scripts/build_whisper_cpp.sh b/scripts/build_whisper_cpp.sh
index a194e16cb12..62f612eeff7 100755
--- a/scripts/build_whisper_cpp.sh
+++ b/scripts/build_whisper_cpp.sh
@@ -19,7 +19,7 @@ set -eu
WHISPER_CPP_SOURCE="${WHISPER_CPP_SOURCE:-https://github.com/ggml-org/whisper.cpp}"
WHISPER_CPP_TAG="${WHISPER_CPP_TAG:-v1.9.1}"
-STUDIO_HOME="${UNSLOTH_STUDIO_HOME:-${STUDIO_HOME:-}}"
+STUDIO_HOME="${UNSLOTH_STUDIO_HOME:-${STUDIO_HOME:-${UNSLOTH_HOME:-}}}"
CUSTOM_STUDIO_HOME=false
if [ -n "$STUDIO_HOME" ]; then
CUSTOM_STUDIO_HOME=true
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsx
index 8972020a104..d51a639a925 100644
--- a/studio/frontend/src/app/provider.tsx
+++ b/studio/frontend/src/app/provider.tsx
@@ -431,6 +431,8 @@ function TauriUpdateLayer({
<UpdateBanner
status={update.status}
info={update.info}
+ preparation={update.preparation}
+ logs={update.logs}
dismissed={update.dismissed}
lastFailure={update.lastFailure}
isExternalServer={isExternalServer}
diff --git a/studio/frontend/src/components/tauri/update-banner.tsx b/studio/frontend/src/components/tauri/update-banner.tsx
index e623a4d4575..3366697d1b0 100644
--- a/studio/frontend/src/components/tauri/update-banner.tsx
+++ b/studio/frontend/src/components/tauri/update-banner.tsx
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { Button } from "@/components/ui/button";
+import { Spinner } from "@/components/ui/spinner";
import { ReleaseNotesPanel } from "@/components/update/release-notes-panel";
import type {
DesktopUpdatePolicyMode,
@@ -10,14 +11,22 @@ import type {
UpdateStatus,
} from "@/hooks/use-tauri-update";
import type { CopySupportDiagnosticsResult } from "@/lib/tauri-diagnostics";
+import {
+ INITIAL_PREPARATION,
+ type UpdatePreparation,
+ preparationShortLabel,
+ restartPlan,
+} from "@/lib/update-preparation";
import { cn } from "@/lib/utils";
-import { CircleAlert, Download } from "lucide-react";
+import { ChevronDown, CircleAlert, Download } from "lucide-react";
import { AnimatePresence, motion } from "motion/react";
import { useState } from "react";
interface UpdateBannerProps {
status: UpdateStatus;
info: UpdateInfo | null;
+ preparation?: UpdatePreparation;
+ logs?: string[];
dismissed: boolean;
lastFailure: RetainedUpdateFailure | null;
isExternalServer?: boolean;
@@ -43,6 +52,8 @@ function formatVersion(version: string | null | undefined): string {
export function UpdateBanner({
status,
info,
+ preparation = INITIAL_PREPARATION,
+ logs = [],
dismissed,
lastFailure,
isExternalServer = false,
@@ -59,7 +70,13 @@ export function UpdateBanner({
const [manualMessage, setManualMessage] = useState<string | null>(null);
// Version whose notes are expanded; a new offer collapses the panel.
const [notesVersion, setNotesVersion] = useState<string | null>(null);
+ const [logsOpen, setLogsOpen] = useState(false);
const showFailure = Boolean(lastFailure) && !dismissed;
+ const isPreparing = status === "preparing";
+ const isReady = status === "ready";
+ const fastRestart = isReady && restartPlan(preparation) === "fast";
+ const showCompact =
+ (isPreparing || isReady) && !dismissed && !showFailure && Boolean(info);
const showAvailable = status === "available" && !dismissed && !showFailure;
const show = showFailure || (showAvailable && Boolean(info));
const isManualLinuxPackage = updatePolicyMode === "manual_linux_package";
@@ -98,8 +115,95 @@ export function UpdateBanner({
return (
<AnimatePresence>
+ {showCompact && (
+ <motion.div
+ key="compact"
+ initial={{ opacity: 0, y: 12, scale: 0.96 }}
+ animate={{ opacity: 1, y: 0, scale: 1 }}
+ exit={{ opacity: 0, y: 8, scale: 0.97 }}
+ transition={{ duration: 0.35, ease: EASE_OUT_QUART }}
+ className={cn(
+ "flex flex-col items-end gap-2",
+ positioned
+ ? "fixed bottom-4 right-4 z-[9999]"
+ : "pointer-events-auto shrink-0",
+ )}
+ data-overlay-dismissible="true"
+ data-testid="tauri-update-pill"
+ >
+ {logsOpen && logs.length > 0 && (
+ <div
+ className="hover-scrollbar max-h-44 w-[min(calc(100vw-2rem),448px)] overflow-y-auto overscroll-contain rounded-2xl bg-white p-3 font-mono text-ui-10 text-muted-foreground shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:bg-card dark:shadow-[0_8px_28px_-6px_rgba(0,0,0,0.28)]"
+ data-testid="tauri-update-pill-logs"
+ >
+ {logs.slice(-60).map((line, index) => (
+ <div key={index} className="whitespace-pre-wrap break-all">
+ {line || " "}
+ </div>
+ ))}
+ </div>
+ )}
+ <div className="flex items-center gap-3 rounded-full bg-white py-2 pl-4 pr-2 shadow-[0_2px_8px_-2px_rgba(0,0,0,0.16)] dark:bg-card dark:shadow-[0_8px_28px_-6px_rgba(0,0,0,0.28)]">
+ {isReady ? (
+ <Download aria-hidden="true" className="size-4 shrink-0 text-foreground" strokeWidth={1.75} />
+ ) : (
+ <Spinner className="text-foreground" label="Preparing update" />
+ )}
+ <p className="min-w-0 truncate text-ui-13 text-foreground">
+ <span className="font-medium">
+ {isReady
+ ? fastRestart
+ ? "Update ready"
+ : "App update downloaded"
+ : "Preparing update"}
+ </span>
+ <span className="text-muted-foreground">
+ {" · "}
+ {isReady ? latestVersion : preparationShortLabel(preparation)}
+ </span>
+ </p>
+ {isReady && (
+ <Button
+ size="sm"
+ className="h-auto whitespace-nowrap rounded-full px-3 py-1.5 text-ui-12"
+ onClick={onInstall}
+ disabled={installDisabled}
+ data-testid="tauri-update-install"
+ >
+ {fastRestart ? "Restart" : "Finish update"}
+ </Button>
+ )}
+ {logs.length > 0 && (
+ <button
+ type="button"
+ onClick={() => setLogsOpen((open) => !open)}
+ className="flex size-6 shrink-0 items-center justify-center rounded-full text-muted-foreground/60 transition-colors hover:bg-muted hover:text-foreground"
+ aria-label={logsOpen ? "Hide update log" : "Show update log"}
+ aria-expanded={logsOpen}
+ data-testid="tauri-update-pill-logs-toggle"
+ >
+ <ChevronDown
+ aria-hidden="true"
+ className={cn("size-4 transition-transform", logsOpen && "rotate-180")}
+ />
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={onDismiss}
+ className="flex size-6 shrink-0 items-center justify-center rounded-full text-muted-foreground/60 transition-colors hover:bg-muted hover:text-foreground"
+ aria-label="Dismiss app update notification"
+ >
+ <svg aria-hidden="true" width="12" height="12" viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <path d="M11 3L3 11M3 3l8 8" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
+ </svg>
+ </button>
+ </div>
+ </motion.div>
+ )}
{show && (
<motion.div
+ key="card"
initial={{ opacity: 0, y: 12, scale: 0.96 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: 8, scale: 0.97 }}
@@ -185,7 +289,7 @@ export function UpdateBanner({
? "Open the GitHub release page to install the Linux package"
: isExternalServer
? "Run `unsloth studio update` from your terminal"
- : "A new app update is available"}
+ : "Prepares in the background. You keep working and restart when it is ready"}
</p>
</div>
</div>
@@ -276,6 +380,7 @@ export function UpdateBanner({
className="-mr-1 h-auto whitespace-nowrap rounded-full px-3 py-2 text-ui-13"
onClick={onInstall}
disabled={installDisabled}
+ data-testid="tauri-update-install"
>
{isManualLinuxPackage ? "Open release page" : "Update"}
</Button>
diff --git a/studio/frontend/src/features/settings/components/desktop-update-control.tsx b/studio/frontend/src/features/settings/components/desktop-update-control.tsx
index 46f42362282..dbf2ac6293f 100644
--- a/studio/frontend/src/features/settings/components/desktop-update-control.tsx
+++ b/studio/frontend/src/features/settings/components/desktop-update-control.tsx
@@ -4,6 +4,7 @@
import { Button } from "@/components/ui/button";
import { useTauriUpdateController } from "@/hooks/tauri-update-context";
import { useT } from "@/i18n";
+import { restartPlan } from "@/lib/update-preparation";
import type { ReactElement } from "react";
import { SettingsRow } from "./settings-row";
@@ -32,12 +33,15 @@ export function DesktopUpdateControl(): ReactElement | null {
if (!update) return null;
const checking = update.status === "checking";
+ const preparing = update.status === "preparing";
+ const ready = update.status === "ready";
+ const fastRestart = ready && restartPlan(update.preparation) === "fast";
// A running install owns the update screen; no second "Update now".
const inFlight =
update.status === "updating-backend" ||
update.status === "downloading" ||
update.status === "installing";
- const busy = checking || inFlight;
+ const busy = checking || inFlight || preparing;
const available = update.info !== null && !checking;
const checkFailed = update.checkError !== null && !available;
@@ -54,7 +58,13 @@ export function DesktopUpdateControl(): ReactElement | null {
? t("settings.about.update.desktopExternalServer")
: update.updatePolicyMode === "manual_linux_package"
? t("settings.about.update.desktopManualInstall")
- : t("settings.about.update.desktopAvailableDescription");
+ : fastRestart
+ ? t("settings.about.update.desktopReadyToRestartDescription")
+ : ready
+ ? t("settings.about.update.desktopReadyToInstallDescription")
+ : preparing
+ ? t("settings.about.update.desktopPreparingDescription")
+ : t("settings.about.update.desktopAvailableDescription");
} else if (checkFailed) {
label = t("settings.about.update.desktopCheckFailed");
// Keep the raw reason: failures can come from the network, HTTP response,
@@ -71,7 +81,13 @@ export function DesktopUpdateControl(): ReactElement | null {
const action = available
? update.updatePolicyMode === "manual_linux_package"
? t("settings.about.update.openReleasePage")
- : t("settings.about.update.updateNow")
+ : fastRestart
+ ? t("settings.about.update.restartToUpdate")
+ : ready
+ ? t("settings.about.update.finishUpdate")
+ : preparing
+ ? t("settings.about.update.preparing")
+ : t("settings.about.update.updateNow")
: checkFailed
? t("settings.about.update.retryCheck")
: update.hasChecked
diff --git a/studio/frontend/src/hooks/use-tauri-update.ts b/studio/frontend/src/hooks/use-tauri-update.ts
index b5c3d88955a..23050c71985 100644
--- a/studio/frontend/src/hooks/use-tauri-update.ts
+++ b/studio/frontend/src/hooks/use-tauri-update.ts
@@ -2,18 +2,45 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useEffect, useRef, useState } from "react";
-import { isTauri } from "@/lib/api-base";
+import { isTrainingStartPending, useTrainingRuntimeStore } from "@/features/training";
+import { apiUrl, isTauri } from "@/lib/api-base";
import {
copySupportDiagnostics,
type CopySupportDiagnosticsResult,
} from "@/lib/tauri-diagnostics";
-import { checkDesktopUpdate } from "@/lib/tauri-updater";
+import {
+ adoptStagedUpdate,
+ cancelStagedUpdate,
+ checkDesktopUpdate,
+ desktopUpdateBundleStatus,
+ discardStagedUpdate,
+ downloadDesktopUpdate,
+ installDesktopUpdate,
+ stagedUpdateStatus,
+ startStagedUpdate,
+ waitForDesktopUpdateDownload,
+ type DesktopUpdateMetadata,
+} from "@/lib/tauri-updater";
import { toast } from "@/lib/toast";
+import {
+ INITIAL_PREPARATION,
+ backendIdle,
+ desktopDownloadDecision,
+ preparationStatus,
+ restartPlan,
+ sameUpdateVersion,
+ settleWithin,
+ stagingDecision,
+ waitForBackendIdle,
+ type UpdatePreparation,
+} from "@/lib/update-preparation";
export type UpdateStatus =
| "idle"
| "checking"
| "available"
+ | "preparing"
+ | "ready"
| "updating-backend"
| "downloading"
| "installing"
@@ -71,6 +98,12 @@ const DEFAULT_UPDATE_POLICY: DesktopUpdatePolicy = {
releaseTagPrefix: "v",
};
+const PREPARATION_STATUSES: ReadonlySet<UpdateStatus> = new Set([
+ "available",
+ "preparing",
+ "ready",
+]);
+
// Desktop quit never fires beforeunload, and only the renderer sees the shell installer.
function publishShellUpdateActive(active: boolean): void {
if (!isTauri) return;
@@ -98,8 +131,21 @@ function manualReleasePageUrl(
return `${policy.releasePageBaseUrl}${policy.releaseTagPrefix}${normalized}`;
}
+async function fetchHealth(): Promise<{ inference_active?: boolean } | null> {
+ return settleWithin(async (signal) => {
+ const res = await fetch(apiUrl("/api/health"), { signal });
+ if (!res.ok) return null;
+ return (await res.json()) as { inference_active?: boolean };
+ }, null);
+}
+
+function wait(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms));
+}
+
export function useTauriUpdate(isExternalServer = false) {
const [status, setStatus] = useState<UpdateStatus>("idle");
+ const statusRef = useRef<UpdateStatus>("idle");
const [info, setInfo] = useState<UpdateInfo | null>(null);
const infoRef = useRef<UpdateInfo | null>(null);
const [hasChecked, setHasChecked] = useState(false);
@@ -114,7 +160,10 @@ export function useTauriUpdate(isExternalServer = false) {
const [error, setError] = useState<string | null>(null);
const [lastFailure, setLastFailure] = useState<RetainedUpdateFailure | null>(null);
const [updatePolicy, setUpdatePolicy] = useState<DesktopUpdatePolicy>(DEFAULT_UPDATE_POLICY);
- const updateRef = useRef<Awaited<ReturnType<typeof checkDesktopUpdate>>>(null);
+ const [preparation, setPreparation] = useState<UpdatePreparation>(INITIAL_PREPARATION);
+ const preparationRef = useRef<UpdatePreparation>(INITIAL_PREPARATION);
+ const preparingVersionRef = useRef<string | null>(null);
+ const updateRef = useRef<DesktopUpdateMetadata | null>(null);
const checkedRef = useRef(false);
const startupScheduledRef = useRef(false);
const checkingRef = useRef(false);
@@ -139,6 +188,11 @@ export function useTauriUpdate(isExternalServer = false) {
return cleanupRearmedRef.current;
}
+ function updateStatus(next: UpdateStatus) {
+ statusRef.current = next;
+ setStatus(next);
+ }
+
function replaceInfo(nextInfo: UpdateInfo | null) {
infoRef.current = nextInfo;
setInfo(nextInfo);
@@ -153,7 +207,7 @@ export function useTauriUpdate(isExternalServer = false) {
setError(null);
setDismissed(false);
}
- setStatus("available");
+ updateStatus("available");
}
function replaceLogs(nextLogs: string[]) {
@@ -193,6 +247,24 @@ export function useTauriUpdate(isExternalServer = false) {
return failure;
}
+ function patchPreparation(patch: Partial<UpdatePreparation>) {
+ const next = { ...preparationRef.current, ...patch };
+ preparationRef.current = next;
+ setPreparation(next);
+ if (!PREPARATION_STATUSES.has(statusRef.current)) return;
+ const derived = preparationStatus(next);
+ if (derived === "ready" && statusRef.current !== "ready") {
+ setDismissed(false);
+ }
+ updateStatus(derived);
+ }
+
+ function resetPreparation() {
+ preparingVersionRef.current = null;
+ preparationRef.current = INITIAL_PREPARATION;
+ setPreparation(INITIAL_PREPARATION);
+ }
+
/** `resolved` is false when the policy is a fail-safe guess, not the real answer. */
async function resolveUpdatePolicy(): Promise<{
policy: DesktopUpdatePolicy;
@@ -248,7 +320,7 @@ export function useTauriUpdate(isExternalServer = false) {
checkedRef.current = true;
checkingRef.current = true;
setCheckError(null);
- setStatus("checking");
+ updateStatus("checking");
try {
const { policy, resolved } = await resolveUpdatePolicy();
@@ -260,8 +332,9 @@ export function useTauriUpdate(isExternalServer = false) {
// latest.json has no deb/rpm key, so the in-app updater would offer an
// AppImage this install cannot apply. Stop instead.
updateRef.current = null;
+ await clearPreparedBackendUpdate();
replaceInfo(null);
- setStatus("idle");
+ updateStatus("idle");
return;
}
// Guessed policy, no manual offer: macOS, Windows and AppImage land here
@@ -280,18 +353,26 @@ export function useTauriUpdate(isExternalServer = false) {
});
} else {
updateRef.current = null;
+ await clearPreparedBackendUpdate();
replaceInfo(null);
- setStatus("idle");
+ resetPreparation();
+ updateStatus("idle");
}
} catch (e) {
console.error("Update check failed:", e);
setCheckError(String(e));
- setStatus(infoRef.current ? "available" : "idle");
+ updateStatus(infoRef.current ? preparationStatus(preparationRef.current) : "idle");
} finally {
checkingRef.current = false;
setHasChecked(true);
}
}
+
+ async function clearPreparedBackendUpdate() {
+ const staged = await stagedUpdateStatus();
+ if (staged.staging) await cancelStagedUpdate();
+ await discardStagedUpdate();
+ }
// Startup owns one delayed check; this ref keeps a per-render function out of
// the empty dep list. The closure reads only refs/setState, so it cannot stale.
const initialCheckRef = useRef(checkForUpdate);
@@ -307,6 +388,140 @@ export function useTauriUpdate(isExternalServer = false) {
return () => clearTimeout(timer);
}, []);
+ async function prepareUpdate(version: string, policy: DesktopUpdatePolicy) {
+ if (!isTauri || policy.mode !== "in_app" || isExternalServer) return;
+ if (preparingVersionRef.current === version) {
+ if (preparationRef.current.shell !== "failed") return;
+ patchPreparation({ shell: "pending", shellProgress: 0 });
+ await prepareShell(version);
+ return;
+ }
+ preparingVersionRef.current = version;
+ preparationRef.current = INITIAL_PREPARATION;
+ setPreparation(INITIAL_PREPARATION);
+ patchPreparation({});
+
+ await Promise.allSettled([prepareShell(version), prepareBackend(version)]);
+ }
+
+ async function ensureBundleDownloaded(): Promise<void> {
+ setUpdatePhase("shell_download");
+ updateStatus("downloading");
+ setUpdateProgress(0);
+ const version = updateRef.current?.version;
+ if (!version) throw new Error("No desktop update has been checked.");
+ for (;;) {
+ const decision = desktopDownloadDecision(await desktopUpdateBundleStatus(), version);
+ if (decision === "ready") break;
+ if (decision === "wait") {
+ await waitForDesktopUpdateDownload(version, setUpdateProgress, () => false);
+ } else {
+ await downloadDesktopUpdate(version, setUpdateProgress);
+ }
+ }
+ patchPreparation({ shell: "done", shellProgress: 100 });
+ }
+
+ async function prepareShell(version: string) {
+ try {
+ for (;;) {
+ const bundle = await desktopUpdateBundleStatus();
+ const decision = desktopDownloadDecision(bundle, version);
+ if (decision === "ready") {
+ patchPreparation({ shell: "done", shellProgress: 100 });
+ return;
+ }
+ patchPreparation({ shell: "downloading" });
+ if (decision === "wait") {
+ await waitForDesktopUpdateDownload(
+ version,
+ (percent) => {
+ if (preparingVersionRef.current !== version) return;
+ patchPreparation({ shellProgress: percent });
+ },
+ () => preparingVersionRef.current !== version,
+ );
+ if (preparingVersionRef.current !== version) return;
+ continue;
+ }
+ await downloadDesktopUpdate(version, (percent) => {
+ if (preparingVersionRef.current !== version) return;
+ patchPreparation({ shellProgress: percent });
+ });
+ if (preparingVersionRef.current !== version) return;
+ }
+ } catch (e) {
+ console.warn("Background app download failed:", e);
+ if (preparingVersionRef.current !== version) return;
+ patchPreparation({ shell: "failed" });
+ }
+ }
+
+ async function prepareBackend(version: string) {
+ try {
+ const staged = await stagedUpdateStatus();
+ const decision = stagingDecision({
+ inApp: true,
+ isExternalServer,
+ offeredVersion: version,
+ staged,
+ });
+ if (decision === "already-ready") {
+ patchPreparation({ backend: "ready" });
+ return;
+ }
+ if (decision === "skip") {
+ patchPreparation({ backend: "skipped" });
+ return;
+ }
+ if (decision === "adopt" || decision === "wait") {
+ patchPreparation({ backend: "staging" });
+ const settled = await adoptStagedUpdate(
+ appendLog,
+ () => preparingVersionRef.current !== version,
+ );
+ if (preparingVersionRef.current !== version) return;
+ if (decision === "wait" || !sameUpdateVersion(settled.shellVersion, version)) {
+ await prepareBackend(version);
+ return;
+ }
+ patchPreparation({ backend: settled.state === "ready" ? "ready" : "failed" });
+ return;
+ }
+ patchPreparation({ backend: "waiting" });
+ const outcome = await waitForBackendIdle({
+ cancelled: () => preparingVersionRef.current !== version,
+ probe: async () =>
+ backendIdle(
+ await fetchHealth(),
+ isTrainingStartPending(useTrainingRuntimeStore.getState()),
+ ),
+ sleep: wait,
+ now: () => Date.now(),
+ });
+ if (outcome === "cancelled") return;
+ if (outcome === "timeout") {
+ // "skipped" still settles the offer into ready, and restartPlan falls back
+ // to the classic update because the backend was never staged.
+ patchPreparation({ backend: "skipped" });
+ return;
+ }
+ patchPreparation({ backend: "staging" });
+ await startStagedUpdate(appendLog);
+ if (preparingVersionRef.current !== version) return;
+ const settled = await stagedUpdateStatus();
+ if (settled.state !== "ready" || !sameUpdateVersion(settled.shellVersion, version)) {
+ await prepareBackend(version);
+ return;
+ }
+ patchPreparation({ backend: "ready" });
+ } catch (e) {
+ console.warn("Background backend preparation failed:", e);
+ if (preparingVersionRef.current !== version) return;
+ patchPreparation({ backend: "failed" });
+ }
+ }
+
async function installUpdate() {
if (updatingRef.current) return;
updatingRef.current = true;
@@ -334,76 +549,81 @@ export function useTauriUpdate(isExternalServer = false) {
const update = updateRef.current;
if (!update) return;
+ if (statusRef.current === "available") {
+ void prepareUpdate(update.version, policy);
+ return;
+ }
- setUpdatePhase("backend");
- setStatus("updating-backend");
- replaceLogs([]);
- setUpdateProgress(0);
- setError(null);
- setCheckError(null);
- setLastFailure(null);
- setDismissed(false);
-
- const { listen } = await import("@tauri-apps/api/event");
const { invoke } = await import("@tauri-apps/api/core");
-
- const unlistenProgress = await listen<string>(
- "update-progress",
- (e) => {
- appendLog(e.payload);
- },
- );
- cleanups.push(unlistenProgress);
-
- const backendResult = await new Promise<"complete" | string>(
- (resolve) => {
- listen<void>("update-complete", () => resolve("complete")).then(
- (u) => cleanups.push(u),
- );
- listen<string>("update-failed", (e) =>
- resolve(e.payload),
- ).then((u) => cleanups.push(u));
-
- invoke("start_backend_update").catch((e) => resolve(String(e)));
- },
- );
-
- if (backendResult !== "complete") {
- retainFailure(backendResult, "backend");
- setError(backendResult);
- setStatus("error");
- return;
+ const bundleReady = (await desktopUpdateBundleStatus()).downloaded;
+ const plan = bundleReady ? restartPlan(preparationRef.current) : "classic";
+ const staging = preparationRef.current.backend === "staging";
+ preparingVersionRef.current = null;
+ if (staging) {
+ await cancelStagedUpdate().catch(() => {});
}
- setUpdatePhase("shell_download");
- setStatus("downloading");
- setUpdateProgress(0);
+ if (plan === "fast") {
+ setUpdatePhase("shell_install");
+ updateStatus("installing");
+ setError(null);
+ // Swallowing this leaves the old backend alive: its pid record then defers
+ // the staged activation at the next launch, so the new shell would come up
+ // against the old backend while reporting a finished update.
+ try {
+ await invoke("stop_server");
+ } catch (stopError) {
+ throw new Error(`Could not stop the backend before restarting: ${stopError}`);
+ }
+ } else {
+ setUpdatePhase("backend");
+ updateStatus("updating-backend");
+ replaceLogs([]);
+ setUpdateProgress(0);
+ setError(null);
+ setCheckError(null);
+ setLastFailure(null);
+ setDismissed(false);
+
+ const { listen } = await import("@tauri-apps/api/event");
+ const unlistenProgress = await listen<string>(
+ "update-progress",
+ (e) => {
+ appendLog(e.payload);
+ },
+ );
+ cleanups.push(unlistenProgress);
+
+ const backendResult = await new Promise<"complete" | string>(
+ (resolve) => {
+ listen<void>("update-complete", () => resolve("complete")).then(
+ (u) => cleanups.push(u),
+ );
+ listen<string>("update-failed", (e) =>
+ resolve(e.payload),
+ ).then((u) => cleanups.push(u));
+
+ invoke("start_backend_update").catch((e) => resolve(String(e)));
+ },
+ );
+
+ if (backendResult !== "complete") {
+ retainFailure(backendResult, "backend");
+ setError(backendResult);
+ updateStatus("error");
+ return;
+ }
+
+ await ensureBundleDownloaded();
+ setUpdatePhase("shell_install");
+ updateStatus("installing");
+ }
- let downloaded = 0;
- let contentLength = 0;
// `update::is_update_running` is already false here, and quitting mid-install
// leaves a half-updated app.
publishShellUpdateActive(true);
try {
- await update.downloadAndInstall((event) => {
- switch (event.event) {
- case "Started":
- contentLength = event.data.contentLength ?? 0;
- break;
- case "Progress":
- downloaded += event.data.chunkLength;
- if (contentLength > 0) {
- setUpdateProgress(
- Math.round((downloaded / contentLength) * 100),
- );
- }
- break;
- case "Finished":
- setUpdatePhase("shell_install");
- setStatus("installing");
- break;
- }
- });
+ await installDesktopUpdate();
} catch (installError) {
// Failed or cancelled: we keep running, so the cleanup the pre-exit hook
// stood down has to come back.
@@ -454,18 +674,18 @@ export function useTauriUpdate(isExternalServer = false) {
"Backend was updated. Copy diagnostics from the update banner if you need support.",
});
setError(null);
- setStatus("idle");
+ updateStatus("idle");
setDismissed(false);
setUpdatePhase("recovered_after_shell_failure");
} catch {
retainFailure(msg, phaseRef.current ?? "shell_install");
setError(msg);
- setStatus("error");
+ updateStatus("error");
}
} else {
retainFailure(msg, phaseRef.current ?? "backend");
setError(msg);
- setStatus("error");
+ updateStatus("error");
}
} finally {
updatingRef.current = false;
@@ -496,7 +716,7 @@ export function useTauriUpdate(isExternalServer = false) {
setError(
"Crash cleanup could not be re-armed. Restart Unsloth before continuing.",
);
- setStatus("error");
+ updateStatus("error");
return false;
}
@@ -514,14 +734,14 @@ export function useTauriUpdate(isExternalServer = false) {
} else {
setDismissed(true);
}
- setStatus("idle");
+ updateStatus("idle");
setError(null);
replaceLogs([]);
} catch (e) {
const msg = String(e);
retainFailure(msg, phaseRef.current ?? "backend");
setError(msg);
- setStatus("error");
+ updateStatus("error");
}
}
@@ -560,6 +780,7 @@ export function useTauriUpdate(isExternalServer = false) {
error,
phase,
lastFailure,
+ preparation,
isExternalServer,
updatePolicyMode: updatePolicy.mode,
manualReleaseUrl,
diff --git a/studio/frontend/src/i18n/locales/ar.ts b/studio/frontend/src/i18n/locales/ar.ts
index bb593fe4a4f..02cd6374f4f 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1668,7 +1668,7 @@ export const ar = {
desktopCheckingDescription: "يستغرق ذلك عادةً بضع ثوانٍ.",
desktopAvailable: "يتوفر إصدار جديد من تطبيق سطح المكتب: {version}",
desktopAvailableDescription:
- "حدّث الآن، وسيُعاد تشغيل تطبيق سطح المكتب عند اكتمال التحديث.",
+ "حدّث الآن ليُجهَّز التحديث في الخلفية. يمكنك متابعة عملك وإعادة التشغيل عندما يصبح جاهزًا.",
desktopExternalServer:
"شغّل الأمر `unsloth studio update` في الطرفية التي شغّلت الخادم.",
desktopManualInstall:
@@ -1677,11 +1677,20 @@ export const ar = {
desktopCheckFailedDescription: "تحقق من اتصالك ثم حاول مرة أخرى.",
desktopCurrent: "تطبيق سطح المكتب محدّث",
desktopCurrentDescription: "سيواصل Unsloth التحقق تلقائيًا.",
+ desktopPreparingDescription:
+ "يجري تجهيز التحديث في الخلفية. يمكنك متابعة عملك.",
+ desktopReadyToRestartDescription:
+ "كل شيء جاهز. أعد التشغيل لإكمال تثبيت التحديث.",
+ desktopReadyToInstallDescription:
+ "تم تنزيل تحديث التطبيق. أكمل تحديث الواجهة الخلفية لتثبيته.",
checkForUpdates: "التحقق من وجود تحديثات",
checkAgain: "التحقق مرة أخرى",
retryCheck: "إعادة المحاولة",
checking: "جارٍ التحقق...",
+ preparing: "جارٍ التجهيز...",
updateNow: "التحديث الآن",
+ restartToUpdate: "إعادة التشغيل للتحديث",
+ finishUpdate: "إكمال التحديث",
openReleasePage: "فتح صفحة الإصدار",
unknownInstall:
"تعذّر اكتشاف طريقة تثبيت Unsloth. لعمليات تثبيت المثبّت أو PyPI، استخدم الأوامر أعلاه.",
diff --git a/studio/frontend/src/i18n/locales/de.ts b/studio/frontend/src/i18n/locales/de.ts
index 198393dba88..a31da84298d 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1715,7 +1715,7 @@ export const de = {
"Dies dauert in der Regel einige Sekunden.",
desktopAvailable: "Version {version} der Desktop-App ist verfügbar",
desktopAvailableDescription:
- "Aktualisieren Sie jetzt. Die Desktop-App wird nach Abschluss des Updates neu gestartet.",
+ "Aktualisieren Sie jetzt, um das Update im Hintergrund vorzubereiten. Sie können weiterarbeiten und neu starten, sobald es bereit ist.",
desktopExternalServer:
"Führen Sie `unsloth studio update` in dem Terminal aus, über das Sie Ihren Server gestartet haben.",
desktopManualInstall:
@@ -1726,11 +1726,20 @@ export const de = {
desktopCurrent: "Die Desktop-App ist auf dem neuesten Stand",
desktopCurrentDescription:
"Unsloth sucht weiterhin automatisch nach Updates.",
+ desktopPreparingDescription:
+ "Das Update wird im Hintergrund vorbereitet. Sie können weiterarbeiten.",
+ desktopReadyToRestartDescription:
+ "Alles ist bereit. Starten Sie neu, um die Installation abzuschließen.",
+ desktopReadyToInstallDescription:
+ "Das App-Update wurde heruntergeladen. Schließen Sie das Backend-Update ab, um es zu installieren.",
checkForUpdates: "Nach Updates suchen",
checkAgain: "Erneut suchen",
retryCheck: "Erneut versuchen",
checking: "Wird geprüft...",
+ preparing: "Wird vorbereitet...",
updateNow: "Jetzt aktualisieren",
+ restartToUpdate: "Zum Aktualisieren neu starten",
+ finishUpdate: "Update abschließen",
openReleasePage: "Release-Seite öffnen",
unknownInstall:
"Es konnte nicht erkannt werden, wie Unsloth installiert wurde. Verwenden Sie für Installer- oder PyPI-Installationen die obigen Befehle.",
diff --git a/studio/frontend/src/i18n/locales/en.ts b/studio/frontend/src/i18n/locales/en.ts
index e66c6c42682..b7e1d657ae2 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -1659,7 +1659,7 @@ export const en = {
desktopCheckingDescription: "This usually takes a few seconds.",
desktopAvailable: "Desktop app {version} is available",
desktopAvailableDescription:
- "Update now and the desktop app will restart when it finishes.",
+ "Update now to prepare it in the background. You keep working and restart when it is ready.",
desktopExternalServer:
"Run `unsloth studio update` from the terminal that started your server.",
desktopManualInstall:
@@ -1669,11 +1669,20 @@ export const en = {
desktopCurrent: "Desktop app is up to date",
desktopCurrentDescription:
"Unsloth will continue checking automatically.",
+ desktopPreparingDescription:
+ "The update is being prepared in the background. You can keep working.",
+ desktopReadyToRestartDescription:
+ "Everything is ready. Restart to finish installing the update.",
+ desktopReadyToInstallDescription:
+ "The app update is downloaded. Finish updating the backend to install it.",
checkForUpdates: "Check for updates",
checkAgain: "Check again",
retryCheck: "Try again",
checking: "Checking...",
+ preparing: "Preparing...",
updateNow: "Update now",
+ restartToUpdate: "Restart to update",
+ finishUpdate: "Finish update",
openReleasePage: "Open release page",
unknownInstall:
"Could not detect how Unsloth was installed. For installer or PyPI installs, use the commands above.",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 8a803ba8a29..9ae3d2baf90 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1707,7 +1707,7 @@ export const es = {
desktopAvailable:
"La versión {version} de la app de escritorio está disponible",
desktopAvailableDescription:
- "Actualiza ahora y la app de escritorio se reiniciará cuando termine.",
+ "Actualiza ahora para prepararla en segundo plano. Puedes seguir trabajando y reiniciar cuando esté lista.",
desktopExternalServer:
"Ejecuta `unsloth studio update` desde el terminal que inició el servidor.",
desktopManualInstall:
@@ -1718,11 +1718,20 @@ export const es = {
desktopCurrent: "La app de escritorio está actualizada",
desktopCurrentDescription:
"Unsloth seguirá buscando actualizaciones automáticamente.",
+ desktopPreparingDescription:
+ "La actualización se está preparando en segundo plano. Puedes seguir trabajando.",
+ desktopReadyToRestartDescription:
+ "Todo está listo. Reinicia para terminar de instalar la actualización.",
+ desktopReadyToInstallDescription:
+ "La actualización de la aplicación se descargó. Completa la actualización del backend para instalarla.",
checkForUpdates: "Buscar actualizaciones",
checkAgain: "Buscar de nuevo",
retryCheck: "Intentarlo de nuevo",
checking: "Buscando...",
+ preparing: "Preparando...",
updateNow: "Actualizar ahora",
+ restartToUpdate: "Reiniciar para actualizar",
+ finishUpdate: "Finalizar actualización",
openReleasePage: "Abrir la página de versiones",
unknownInstall:
"No se pudo detectar cómo se instaló Unsloth. Para instalaciones con el instalador o desde PyPI, usa los comandos anteriores.",
diff --git a/studio/frontend/src/i18n/locales/fr.ts b/studio/frontend/src/i18n/locales/fr.ts
index 9f2159c1b23..8677a2d843d 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1716,7 +1716,7 @@ export const fr = {
desktopAvailable:
"La version {version} de l’application de bureau est disponible",
desktopAvailableDescription:
- "Effectuez la mise à jour maintenant. L’application de bureau redémarrera une fois l’opération terminée.",
+ "Mettez à jour maintenant pour la préparer en arrière-plan. Vous continuez à travailler et redémarrez lorsqu’elle est prête.",
desktopExternalServer:
"Exécutez `unsloth studio update` dans le terminal depuis lequel vous avez lancé le serveur.",
desktopManualInstall:
@@ -1727,11 +1727,20 @@ export const fr = {
desktopCurrent: "L’application de bureau est à jour",
desktopCurrentDescription:
"Unsloth continuera à rechercher automatiquement les mises à jour.",
+ desktopPreparingDescription:
+ "La mise à jour est préparée en arrière-plan. Vous pouvez continuer à travailler.",
+ desktopReadyToRestartDescription:
+ "Tout est prêt. Redémarrez pour terminer l’installation de la mise à jour.",
+ desktopReadyToInstallDescription:
+ "La mise à jour de l’application a été téléchargée. Terminez la mise à jour du backend pour l’installer.",
checkForUpdates: "Rechercher les mises à jour",
checkAgain: "Rechercher à nouveau",
retryCheck: "Réessayer",
checking: "Vérification...",
+ preparing: "Préparation...",
updateNow: "Mettre à jour maintenant",
+ restartToUpdate: "Redémarrer pour mettre à jour",
+ finishUpdate: "Terminer la mise à jour",
openReleasePage: "Ouvrir la page des versions",
unknownInstall:
"Impossible de détecter le mode d'installation d'Unsloth. Pour les installations via installateur ou PyPI, utilisez les commandes ci-dessus.",
diff --git a/studio/frontend/src/i18n/locales/hi.ts b/studio/frontend/src/i18n/locales/hi.ts
index f30799ea1e6..86300226262 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1675,7 +1675,7 @@ export const hi = {
"इसमें आम तौर पर कुछ सेकंड लगते हैं।",
desktopAvailable: "डेस्कटॉप ऐप {version} उपलब्ध है",
desktopAvailableDescription:
- "अभी अपडेट करें। अपडेट पूरा होने पर डेस्कटॉप ऐप फिर से शुरू होगा।",
+ "अभी अपडेट करें, यह पृष्ठभूमि में तैयार होगा। आप काम करते रह सकते हैं और तैयार होने पर फिर से शुरू करें।",
desktopExternalServer:
"जिस टर्मिनल से सर्वर शुरू किया गया था, उसमें `unsloth studio update` चलाएँ।",
desktopManualInstall:
@@ -1685,11 +1685,20 @@ export const hi = {
"अपना कनेक्शन जाँचें और फिर से कोशिश करें।",
desktopCurrent: "डेस्कटॉप ऐप नवीनतम संस्करण पर है",
desktopCurrentDescription: "Unsloth अपने-आप जाँच करता रहेगा।",
+ desktopPreparingDescription:
+ "अपडेट पृष्ठभूमि में तैयार हो रहा है। आप काम करते रह सकते हैं।",
+ desktopReadyToRestartDescription:
+ "सब तैयार है। इंस्टॉल पूरा करने के लिए फिर से शुरू करें।",
+ desktopReadyToInstallDescription:
+ "ऐप अपडेट डाउनलोड हो गया है। इसे इंस्टॉल करने के लिए बैकएंड अपडेट पूरा करें।",
checkForUpdates: "अपडेट की जाँच करें",
checkAgain: "फिर से जाँचें",
retryCheck: "फिर से कोशिश करें",
checking: "जाँच हो रही है...",
+ preparing: "तैयार हो रहा है...",
updateNow: "अभी अपडेट करें",
+ restartToUpdate: "अपडेट के लिए फिर से शुरू करें",
+ finishUpdate: "अपडेट पूरा करें",
openReleasePage: "रिलीज़ पेज खोलें",
unknownInstall:
"यह पता नहीं लगाया जा सका कि Unsloth कैसे इंस्टॉल किया गया था। इंस्टॉलर या PyPI इंस्टॉल के लिए, ऊपर दिए गए कमांड का उपयोग करें।",
diff --git a/studio/frontend/src/i18n/locales/it.ts b/studio/frontend/src/i18n/locales/it.ts
index 612de7889f1..4001e1b88d5 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1682,7 +1682,7 @@ export const it = {
desktopAvailable:
"È disponibile la versione {version} dell'app desktop",
desktopAvailableDescription:
- "Aggiorna ora: al termine, l'app desktop verrà riavviata.",
+ "Aggiorna ora per prepararlo in background. Puoi continuare a lavorare e riavviare quando è pronto.",
desktopExternalServer:
"Esegui `unsloth studio update` nel terminale da cui hai avviato il server.",
desktopManualInstall:
@@ -1693,11 +1693,20 @@ export const it = {
desktopCurrent: "L'app desktop è aggiornata",
desktopCurrentDescription:
"Unsloth continuerà a verificare automaticamente la disponibilità di aggiornamenti.",
+ desktopPreparingDescription:
+ "L'aggiornamento viene preparato in background. Puoi continuare a lavorare.",
+ desktopReadyToRestartDescription:
+ "È tutto pronto. Riavvia per completare l'installazione dell'aggiornamento.",
+ desktopReadyToInstallDescription:
+ "L'aggiornamento dell'app è stato scaricato. Completa l'aggiornamento del backend per installarlo.",
checkForUpdates: "Verifica aggiornamenti",
checkAgain: "Verifica di nuovo",
retryCheck: "Riprova",
checking: "Verifica in corso...",
+ preparing: "Preparazione...",
updateNow: "Aggiorna ora",
+ restartToUpdate: "Riavvia per aggiornare",
+ finishUpdate: "Completa aggiornamento",
openReleasePage: "Apri la pagina della release",
unknownInstall:
"Impossibile rilevare come è stato installato Unsloth. Per installazioni tramite installer o PyPI, usa i comandi sopra.",
diff --git a/studio/frontend/src/i18n/locales/ja.ts b/studio/frontend/src/i18n/locales/ja.ts
index ac944073c4b..be6bd67e8f2 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1639,7 +1639,7 @@ export const ja = {
desktopCheckingDescription: "通常は数秒で完了します。",
desktopAvailable: "デスクトップアプリ {version} を利用できます",
desktopAvailableDescription:
- "今すぐアップデートします。完了するとデスクトップアプリが再起動します。",
+ "今すぐアップデートすると、バックグラウンドで準備されます。作業を続けたまま、準備ができたら再起動してください。",
desktopExternalServer:
"サーバーを起動したターミナルで `unsloth studio update` を実行してください。",
desktopManualInstall:
@@ -1650,11 +1650,19 @@ export const ja = {
desktopCurrent: "デスクトップアプリは最新です",
desktopCurrentDescription:
"Unsloth は今後も自動的にアップデートを確認します。",
+ desktopPreparingDescription: "アップデートをバックグラウンドで準備しています。作業を続けられます。",
+ desktopReadyToRestartDescription:
+ "準備が完了しました。再起動するとアップデートのインストールが完了します。",
+ desktopReadyToInstallDescription:
+ "アプリのアップデートをダウンロードしました。インストールするにはバックエンドのアップデートを完了してください。",
checkForUpdates: "アップデートを確認",
checkAgain: "もう一度確認",
retryCheck: "再試行",
checking: "確認中...",
+ preparing: "準備中...",
updateNow: "今すぐアップデート",
+ restartToUpdate: "再起動して更新",
+ finishUpdate: "アップデートを完了",
openReleasePage: "リリースページを開く",
unknownInstall: "Unsloth がどのようにインストールされたか検出できませんでした。インストーラーまたは PyPI インストールの場合は、上記のコマンドを使用してください。",
localCheckout:
diff --git a/studio/frontend/src/i18n/locales/ko.ts b/studio/frontend/src/i18n/locales/ko.ts
index 32eedbefebf..1439bd4618f 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1665,7 +1665,7 @@ export const ko = {
desktopCheckingDescription: "보통 몇 초 정도 걸립니다.",
desktopAvailable: "데스크톱 앱 {version} 버전을 사용할 수 있습니다",
desktopAvailableDescription:
- "지금 업데이트하면 완료 후 데스크톱 앱이 다시 시작됩니다.",
+ "지금 업데이트하면 백그라운드에서 준비됩니다. 계속 작업하다가 준비되면 다시 시작하세요.",
desktopExternalServer:
"서버를 시작한 터미널에서 `unsloth studio update`를 실행하세요.",
desktopManualInstall:
@@ -1675,11 +1675,17 @@ export const ko = {
"연결 상태를 확인한 후 다시 시도하세요.",
desktopCurrent: "데스크톱 앱이 최신 버전입니다",
desktopCurrentDescription: "Unsloth가 계속 자동으로 확인합니다.",
+ desktopPreparingDescription: "업데이트를 백그라운드에서 준비하고 있습니다. 계속 작업할 수 있습니다.",
+ desktopReadyToRestartDescription: "모두 준비되었습니다. 다시 시작하면 업데이트 설치가 완료됩니다.",
+ desktopReadyToInstallDescription: "앱 업데이트를 다운로드했습니다. 설치하려면 백엔드 업데이트를 완료하세요.",
checkForUpdates: "업데이트 확인",
checkAgain: "다시 확인",
retryCheck: "다시 시도",
checking: "확인 중...",
+ preparing: "준비 중...",
updateNow: "지금 업데이트",
+ restartToUpdate: "다시 시작하여 업데이트",
+ finishUpdate: "업데이트 완료",
openReleasePage: "릴리스 페이지 열기",
unknownInstall:
"Unsloth 설치 방식을 감지할 수 없습니다. 설치 프로그램 또는 PyPI 설치의 경우 위 명령을 사용하세요.",
diff --git a/studio/frontend/src/i18n/locales/pt-br.ts b/studio/frontend/src/i18n/locales/pt-br.ts
index a84bb69a1b3..220e0ffdc2a 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1690,7 +1690,7 @@ export const ptBR = {
desktopAvailable:
"A versão {version} do aplicativo de desktop está disponível",
desktopAvailableDescription:
- "Atualize agora. O aplicativo de desktop será reiniciado quando a atualização terminar.",
+ "Atualize agora para preparar em segundo plano. Você continua trabalhando e reinicia quando estiver pronto.",
desktopExternalServer:
"Execute `unsloth studio update` no terminal usado para iniciar o servidor.",
desktopManualInstall:
@@ -1701,11 +1701,20 @@ export const ptBR = {
desktopCurrent: "O aplicativo de desktop está atualizado",
desktopCurrentDescription:
"O Unsloth continuará verificando automaticamente.",
+ desktopPreparingDescription:
+ "A atualização está sendo preparada em segundo plano. Você pode continuar trabalhando.",
+ desktopReadyToRestartDescription:
+ "Tudo pronto. Reinicie para concluir a instalação da atualização.",
+ desktopReadyToInstallDescription:
+ "A atualização do aplicativo foi baixada. Conclua a atualização do backend para instalá-la.",
checkForUpdates: "Verificar se há atualizações",
checkAgain: "Verificar novamente",
retryCheck: "Tentar novamente",
checking: "Verificando...",
+ preparing: "Preparando...",
updateNow: "Atualizar agora",
+ restartToUpdate: "Reiniciar para atualizar",
+ finishUpdate: "Concluir atualização",
openReleasePage: "Abrir página de lançamentos",
unknownInstall:
"Não foi possível detectar como o Unsloth foi instalado. Para instalações via instalador ou PyPI, use os comandos acima.",
diff --git a/studio/frontend/src/i18n/locales/ru.ts b/studio/frontend/src/i18n/locales/ru.ts
index ad13b49a597..eb0b4fda471 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1687,7 +1687,7 @@ export const ru = {
desktopAvailable:
"Доступна версия {version} настольного приложения",
desktopAvailableDescription:
- "Установите обновление сейчас. После установки настольное приложение перезапустится.",
+ "Установите обновление сейчас, чтобы подготовить его в фоновом режиме. Вы можете продолжать работу и перезапустить приложение, когда всё будет готово.",
desktopExternalServer:
"Выполните `unsloth studio update` в терминале, из которого был запущен сервер.",
desktopManualInstall:
@@ -1699,11 +1699,20 @@ export const ru = {
"Установлена последняя версия настольного приложения",
desktopCurrentDescription:
"Unsloth продолжит автоматически проверять наличие обновлений.",
+ desktopPreparingDescription:
+ "Обновление готовится в фоновом режиме. Вы можете продолжать работу.",
+ desktopReadyToRestartDescription:
+ "Всё готово. Перезапустите приложение, чтобы завершить установку обновления.",
+ desktopReadyToInstallDescription:
+ "Обновление приложения загружено. Завершите обновление бэкенда, чтобы установить его.",
checkForUpdates: "Проверить наличие обновлений",
checkAgain: "Проверить снова",
retryCheck: "Повторить попытку",
checking: "Проверка…",
+ preparing: "Подготовка…",
updateNow: "Обновить сейчас",
+ restartToUpdate: "Перезапустить для обновления",
+ finishUpdate: "Завершить обновление",
openReleasePage: "Открыть страницу выпуска",
unknownInstall:
"Не удалось определить способ установки Unsloth. Для установки через установщик или PyPI используйте команды выше.",
diff --git a/studio/frontend/src/i18n/locales/zh-CN.ts b/studio/frontend/src/i18n/locales/zh-CN.ts
index 3057a12211f..851bcf2f540 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1627,7 +1627,7 @@ export const zhCN = {
desktopChecking: "正在检查更新",
desktopCheckingDescription: "通常只需几秒钟。",
desktopAvailable: "桌面应用 {version} 已可用",
- desktopAvailableDescription: "立即更新,完成后桌面应用将自动重启。",
+ desktopAvailableDescription: "立即更新,更新将在后台准备。你可以继续工作,准备好后再重启。",
desktopExternalServer:
"请在启动服务器的终端中运行 `unsloth studio update`。",
desktopManualInstall: "打开发布页面,安装最新的 Linux 软件包。",
@@ -1635,11 +1635,17 @@ export const zhCN = {
desktopCheckFailedDescription: "请检查网络连接后重试。",
desktopCurrent: "桌面应用已是最新版本",
desktopCurrentDescription: "Unsloth 会继续自动检查更新。",
+ desktopPreparingDescription: "更新正在后台准备中。你可以继续工作。",
+ desktopReadyToRestartDescription: "一切就绪。重启即可完成更新安装。",
+ desktopReadyToInstallDescription: "应用更新已下载。请完成后端更新以安装该版本。",
checkForUpdates: "检查更新",
checkAgain: "再次检查",
retryCheck: "重试",
checking: "正在检查...",
+ preparing: "正在准备...",
updateNow: "立即更新",
+ restartToUpdate: "重启以更新",
+ finishUpdate: "完成更新",
openReleasePage: "打开发布页面",
unknownInstall:
"Unsloth 无法检测安装方式。如果你使用一键安装器或 PyPI 安装,请使用上面的命令。",
diff --git a/studio/frontend/src/lib/tauri-updater.ts b/studio/frontend/src/lib/tauri-updater.ts
index d805201fdfd..5eaea5987f8 100644
--- a/studio/frontend/src/lib/tauri-updater.ts
+++ b/studio/frontend/src/lib/tauri-updater.ts
@@ -1,13 +1,139 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-export async function checkDesktopUpdate() {
- const [{ invoke }, { Update }] = await Promise.all([
+import {
+ downloadPercent,
+ sameUpdateVersion,
+ type DesktopUpdateBundleStatus,
+ type StagedUpdateStatus,
+} from "@/lib/update-preparation";
+
+export interface DesktopUpdateMetadata {
+ currentVersion: string;
+ version: string;
+ date?: string;
+ body?: string;
+ rawJson: Record<string, unknown>;
+}
+
+interface DesktopUpdateDownloadEvent {
+ version: string;
+ downloaded: number;
+ total: number | null;
+}
+
+export async function checkDesktopUpdate(): Promise<DesktopUpdateMetadata | null> {
+ const { invoke } = await import("@tauri-apps/api/core");
+ return invoke<DesktopUpdateMetadata | null>("check_desktop_update");
+}
+
+export async function desktopUpdateBundleStatus(): Promise<DesktopUpdateBundleStatus> {
+ const { invoke } = await import("@tauri-apps/api/core");
+ return invoke<DesktopUpdateBundleStatus>("desktop_update_bundle_status");
+}
+
+export async function downloadDesktopUpdate(
+ expectedVersion: string,
+ onProgress: (percent: number) => void,
+): Promise<void> {
+ const [{ invoke }, { listen }] = await Promise.all([
import("@tauri-apps/api/core"),
- import("@tauri-apps/plugin-updater"),
+ import("@tauri-apps/api/event"),
]);
- const metadata = await invoke<ConstructorParameters<typeof Update>[0] | null>(
- "check_desktop_update",
+ const unlisten = await listen<DesktopUpdateDownloadEvent>(
+ "desktop-update-download",
+ (event) => {
+ if (!sameUpdateVersion(event.payload.version, expectedVersion)) return;
+ onProgress(downloadPercent(event.payload.downloaded, event.payload.total));
+ },
+ );
+ try {
+ await invoke("download_desktop_update");
+ const status = await desktopUpdateBundleStatus();
+ if (!status.downloaded || !sameUpdateVersion(status.version, expectedVersion)) {
+ throw new Error(`Desktop update ${expectedVersion} was not downloaded.`);
+ }
+ onProgress(100);
+ } finally {
+ unlisten();
+ }
+}
+
+export async function waitForDesktopUpdateDownload(
+ expectedVersion: string,
+ onProgress: (percent: number) => void,
+ isCancelled: () => boolean,
+ pollMs = 500,
+): Promise<void> {
+ const { listen } = await import("@tauri-apps/api/event");
+ const unlisten = await listen<DesktopUpdateDownloadEvent>(
+ "desktop-update-download",
+ (event) => {
+ if (!sameUpdateVersion(event.payload.version, expectedVersion)) return;
+ onProgress(downloadPercent(event.payload.downloaded, event.payload.total));
+ },
);
- return metadata ? new Update(metadata) : null;
+ try {
+ while (!isCancelled()) {
+ const status = await desktopUpdateBundleStatus();
+ if (!status.downloading) return;
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
+ }
+ } finally {
+ unlisten();
+ }
+}
+
+export async function installDesktopUpdate(): Promise<void> {
+ const { invoke } = await import("@tauri-apps/api/core");
+ await invoke("install_desktop_update");
+}
+
+export async function stagedUpdateStatus(): Promise<StagedUpdateStatus> {
+ const { invoke } = await import("@tauri-apps/api/core");
+ return invoke<StagedUpdateStatus>("staged_update_status");
+}
+
+export async function startStagedUpdate(onLine: (line: string) => void): Promise<void> {
+ const [{ invoke }, { listen }] = await Promise.all([
+ import("@tauri-apps/api/core"),
+ import("@tauri-apps/api/event"),
+ ]);
+ const unlisten = await listen<string>("stage-progress", (event) => onLine(event.payload));
+ try {
+ await invoke("start_staged_update");
+ } finally {
+ unlisten();
+ }
+}
+
+/// Follow a staged run this webview did not start. Polls rather than waiting on
+/// stage-complete, because the run can finish between the status read that chose
+/// this path and any listener registered after it.
+export async function adoptStagedUpdate(
+ onLine: (line: string) => void,
+ isCancelled: () => boolean,
+ pollMs = 2_000,
+): Promise<StagedUpdateStatus> {
+ const { listen } = await import("@tauri-apps/api/event");
+ const unlisten = await listen<string>("stage-progress", (event) => onLine(event.payload));
+ try {
+ for (;;) {
+ const status = await stagedUpdateStatus();
+ if (!status.staging || isCancelled()) return status;
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
+ }
+ } finally {
+ unlisten();
+ }
+}
+
+export async function cancelStagedUpdate(): Promise<void> {
+ const { invoke } = await import("@tauri-apps/api/core");
+ await invoke("cancel_staged_update");
+}
+
+export async function discardStagedUpdate(): Promise<void> {
+ const { invoke } = await import("@tauri-apps/api/core");
+ await invoke("discard_staged_update");
}
diff --git a/studio/frontend/src/lib/update-preparation.ts b/studio/frontend/src/lib/update-preparation.ts
new file mode 100644
index 00000000000..51155b86a60
--- /dev/null
+++ b/studio/frontend/src/lib/update-preparation.ts
@@ -0,0 +1,180 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export type ShellPreparation = "pending" | "downloading" | "done" | "failed";
+
+export type BackendPreparation =
+ | "pending"
+ | "waiting"
+ | "staging"
+ | "ready"
+ | "failed"
+ | "skipped";
+
+export interface UpdatePreparation {
+ shell: ShellPreparation;
+ backend: BackendPreparation;
+ shellProgress: number;
+}
+
+export type PreparationStatus = "preparing" | "ready" | "available";
+
+export type RestartPlan = "fast" | "classic";
+
+export interface StagedUpdateStatus {
+ state: "none" | "partial" | "ready" | "failed";
+ backendVersion: string | null;
+ shellVersion: string | null;
+ /** A staged child is running now, so this stage is being written, not stale. */
+ staging?: boolean;
+ /** shell version captured when the running staged child started. */
+ stagingShellVersion?: string | null;
+}
+
+export interface DesktopUpdateBundleStatus {
+ version: string | null;
+ downloaded: boolean;
+ downloading: boolean;
+}
+
+export type DesktopDownloadDecision = "ready" | "wait" | "download";
+
+export type StagingDecision = "stage" | "already-ready" | "adopt" | "wait" | "skip";
+
+export const INITIAL_PREPARATION: UpdatePreparation = {
+ shell: "pending",
+ backend: "pending",
+ shellProgress: 0,
+};
+
+const LEADING_V = /^v/;
+
+export function sameUpdateVersion(left: string | null | undefined, right: string): boolean {
+ if (!left) return false;
+ return left.replace(LEADING_V, "") === right.replace(LEADING_V, "");
+}
+
+export function preparationStatus(preparation: UpdatePreparation): PreparationStatus {
+ if (preparation.shell === "failed") return "available";
+ if (preparation.shell !== "done") return "preparing";
+ switch (preparation.backend) {
+ case "ready":
+ case "failed":
+ case "skipped":
+ return "ready";
+ default:
+ return "preparing";
+ }
+}
+
+export function restartPlan(preparation: UpdatePreparation): RestartPlan {
+ return preparation.shell === "done" && preparation.backend === "ready"
+ ? "fast"
+ : "classic";
+}
+
+export function desktopDownloadDecision(
+ status: DesktopUpdateBundleStatus,
+ offeredVersion: string,
+): DesktopDownloadDecision {
+ if (status.downloaded && sameUpdateVersion(status.version, offeredVersion)) return "ready";
+ return status.downloading ? "wait" : "download";
+}
+
+export function stagingDecision(args: {
+ inApp: boolean;
+ isExternalServer: boolean;
+ offeredVersion: string;
+ staged: StagedUpdateStatus;
+}): StagingDecision {
+ if (!args.inApp || args.isExternalServer) return "skip";
+ const matches = sameUpdateVersion(args.staged.shellVersion, args.offeredVersion);
+ if (args.staged.state === "ready" && matches) return "already-ready";
+ if (args.staged.state === "failed" && matches) return "skip";
+ // A webview reload loses the hook's own record of a run it started, and the
+ // native side rejects a second one, so join the running one instead.
+ if (args.staged.staging) {
+ return sameUpdateVersion(args.staged.stagingShellVersion, args.offeredVersion)
+ ? "adopt"
+ : "wait";
+ }
+ return "stage";
+}
+
+export function backendIdle(
+ health: { inference_active?: boolean } | null,
+ trainingActive: boolean,
+): boolean {
+ if (trainingActive) return false;
+ return health !== null && health.inference_active !== true;
+}
+
+export function downloadPercent(downloaded: number, total: number | null): number {
+ if (!total || total <= 0) return 0;
+ return Math.min(100, Math.round((downloaded / total) * 100));
+}
+
+export function preparationShortLabel(preparation: UpdatePreparation): string {
+ if (preparation.shell === "downloading") return `downloading ${preparation.shellProgress}%`;
+ switch (preparation.backend) {
+ case "waiting":
+ return "waiting for idle";
+ case "staging":
+ return "setting up backend";
+ default:
+ return "starting";
+ }
+}
+
+export const IDLE_POLL_MS = 20_000;
+// A backend that is stopped, crashed, or will not start never reports idle, and
+// the update offer is the user's way out of exactly that. Waiting forever leaves
+// the pill with no action and the settings button disabled, so the wait is bounded
+// and the offer falls back to the classic update.
+export const IDLE_WAIT_MS = 5 * 60_000;
+
+export type IdleWaitOutcome = "idle" | "timeout" | "cancelled";
+
+export async function waitForBackendIdle(deps: {
+ cancelled: () => boolean;
+ probe: () => Promise<boolean>;
+ sleep: (ms: number) => Promise<void>;
+ now: () => number;
+ pollMs?: number;
+ timeoutMs?: number;
+}): Promise<IdleWaitOutcome> {
+ const pollMs = deps.pollMs ?? IDLE_POLL_MS;
+ const deadline = deps.now() + (deps.timeoutMs ?? IDLE_WAIT_MS);
+ while (!deps.cancelled()) {
+ if (await deps.probe()) return "idle";
+ if (deps.cancelled()) return "cancelled";
+ if (deps.now() >= deadline) return "timeout";
+ await deps.sleep(pollMs);
+ }
+ return "cancelled";
+}
+
+export const HEALTH_PROBE_TIMEOUT_MS = 10_000;
+
+/// Resolves with `fallback` when `run` has not settled in time, whether or not it
+/// honours the abort. A backend that accepts the connection and then answers
+/// nothing parks a bare fetch forever, and the idle wait below only reaches its
+/// deadline between probes, so an unbounded probe defeats that deadline entirely.
+export function settleWithin<T>(
+ run: (signal: AbortSignal) => Promise<T>,
+ fallback: T,
+ timeoutMs: number = HEALTH_PROBE_TIMEOUT_MS,
+): Promise<T> {
+ const controller = new AbortController();
+ return new Promise<T>((resolve) => {
+ const timer = setTimeout(() => {
+ controller.abort();
+ resolve(fallback);
+ }, timeoutMs);
+ const settle = (value: T) => {
+ clearTimeout(timer);
+ resolve(value);
+ };
+ run(controller.signal).then(settle, () => settle(fallback));
+ });
+}
diff --git a/studio/frontend/tests/update-preparation.test.ts b/studio/frontend/tests/update-preparation.test.ts
new file mode 100644
index 00000000000..de413b091cb
--- /dev/null
+++ b/studio/frontend/tests/update-preparation.test.ts
@@ -0,0 +1,272 @@
+// 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 {
+ INITIAL_PREPARATION,
+ backendIdle,
+ desktopDownloadDecision,
+ downloadPercent,
+ preparationStatus,
+ restartPlan,
+ settleWithin,
+ stagingDecision,
+ waitForBackendIdle,
+ type StagedUpdateStatus,
+ type UpdatePreparation,
+} from "../src/lib/update-preparation.ts";
+
+function prep(patch: Partial<UpdatePreparation>): UpdatePreparation {
+ return { ...INITIAL_PREPARATION, ...patch };
+}
+
+function staged(patch: Partial<StagedUpdateStatus>): StagedUpdateStatus {
+ return { state: "none", backendVersion: null, shellVersion: null, ...patch };
+}
+
+test("nothing is ready until the app bundle is downloaded", () => {
+ assert.equal(preparationStatus(INITIAL_PREPARATION), "preparing");
+ assert.equal(preparationStatus(prep({ backend: "ready" })), "preparing");
+ assert.equal(preparationStatus(prep({ shell: "downloading", backend: "ready" })), "preparing");
+});
+
+test("a downloaded bundle is ready once the backend has settled either way", () => {
+ assert.equal(preparationStatus(prep({ shell: "done", backend: "ready" })), "ready");
+ assert.equal(preparationStatus(prep({ shell: "done", backend: "failed" })), "ready");
+ assert.equal(preparationStatus(prep({ shell: "done", backend: "skipped" })), "ready");
+ assert.equal(preparationStatus(prep({ shell: "done", backend: "staging" })), "preparing");
+ assert.equal(preparationStatus(prep({ shell: "done", backend: "waiting" })), "preparing");
+});
+
+test("a failed bundle download falls back to the plain offer", () => {
+ assert.equal(preparationStatus(prep({ shell: "failed", backend: "ready" })), "available");
+});
+
+test("only a staged backend with a downloaded bundle restarts on the fast path", () => {
+ assert.equal(restartPlan(prep({ shell: "done", backend: "ready" })), "fast");
+ assert.equal(restartPlan(prep({ shell: "done", backend: "failed" })), "classic");
+ assert.equal(restartPlan(prep({ shell: "done", backend: "skipped" })), "classic");
+ assert.equal(restartPlan(prep({ shell: "downloading", backend: "ready" })), "classic");
+});
+
+test("staging is skipped outside the in-app updater and for external servers", () => {
+ const base = { inApp: true, isExternalServer: false, offeredVersion: "0.1.900-beta", staged: staged({}) };
+ assert.equal(stagingDecision({ ...base, inApp: false }), "skip");
+ assert.equal(stagingDecision({ ...base, isExternalServer: true }), "skip");
+ assert.equal(stagingDecision(base), "stage");
+});
+
+test("a stage already prepared for the offered version is reused", () => {
+ const ready = staged({ state: "ready", shellVersion: "0.1.900-beta" });
+ const args = { inApp: true, isExternalServer: false, offeredVersion: "v0.1.900-beta", staged: ready };
+ assert.equal(stagingDecision(args), "already-ready");
+ assert.equal(stagingDecision({ ...args, offeredVersion: "0.1.901-beta" }), "stage");
+});
+
+test("a version that rolled back is never staged again", () => {
+ const failed = staged({ state: "failed", shellVersion: "0.1.900-beta" });
+ const args = { inApp: true, isExternalServer: false, offeredVersion: "0.1.900-beta", staged: failed };
+ assert.equal(stagingDecision(args), "skip");
+ assert.equal(stagingDecision({ ...args, offeredVersion: "0.1.901-beta" }), "stage");
+});
+
+test("the backend is idle only when reachable, not generating and not training", () => {
+ assert.equal(backendIdle(null, false), false);
+ assert.equal(backendIdle({}, false), true);
+ assert.equal(backendIdle({ inference_active: true }, false), false);
+ assert.equal(backendIdle({}, true), false);
+});
+
+test("download progress clamps to a whole percentage", () => {
+ assert.equal(downloadPercent(0, null), 0);
+ assert.equal(downloadPercent(50, 200), 25);
+ assert.equal(downloadPercent(300, 200), 100);
+});
+
+test("a reloaded renderer waits for the native shell download", () => {
+ const status = {
+ version: "0.1.901",
+ downloaded: false,
+ downloading: true,
+ };
+ assert.equal(desktopDownloadDecision(status, "0.1.901"), "wait");
+ assert.equal(desktopDownloadDecision(status, "0.1.902"), "wait");
+ assert.equal(
+ desktopDownloadDecision({ ...status, downloading: false }, "0.1.901"),
+ "download",
+ );
+ assert.equal(
+ desktopDownloadDecision({ ...status, downloaded: true, downloading: false }, "v0.1.901"),
+ "ready",
+ );
+});
+
+function clock() {
+ let now = 0;
+ return {
+ now: () => now,
+ sleep: async (ms: number) => {
+ now += ms;
+ },
+ };
+}
+
+test("the idle wait stops at the first idle probe", async () => {
+ const c = clock();
+ let probes = 0;
+ const outcome = await waitForBackendIdle({
+ cancelled: () => false,
+ probe: async () => ++probes >= 3,
+ sleep: c.sleep,
+ now: c.now,
+ });
+ assert.equal(outcome, "idle");
+ assert.equal(probes, 3);
+});
+
+test("an unreachable backend gives up instead of waiting forever", async () => {
+ const c = clock();
+ let probes = 0;
+ const outcome = await waitForBackendIdle({
+ cancelled: () => false,
+ // What fetchHealth() returns when the backend is stopped or will not start.
+ probe: async () => {
+ probes += 1;
+ return false;
+ },
+ sleep: c.sleep,
+ now: c.now,
+ pollMs: 20_000,
+ timeoutMs: 60_000,
+ });
+ assert.equal(outcome, "timeout");
+ assert.equal(probes, 4);
+ // And the offer still settles, so the pill gets its Restart and the restart runs
+ // the classic update rather than leaving the user with no way to update at all.
+ assert.equal(preparationStatus(prep({ shell: "done", backend: "skipped" })), "ready");
+ assert.equal(restartPlan(prep({ shell: "done", backend: "skipped" })), "classic");
+});
+
+test("a newer offer cancels the wait", async () => {
+ const c = clock();
+ let probes = 0;
+ const outcome = await waitForBackendIdle({
+ cancelled: () => probes >= 2,
+ probe: async () => {
+ probes += 1;
+ return false;
+ },
+ sleep: c.sleep,
+ now: c.now,
+ });
+ assert.equal(outcome, "cancelled");
+});
+
+test("a probe that never answers still settles, and aborts what it started", async () => {
+ let aborted = false;
+ // The wedged backend: the connection is accepted, the response never comes.
+ const value = await settleWithin<string | null>(
+ (signal) =>
+ new Promise(() => {
+ signal.addEventListener("abort", () => {
+ aborted = true;
+ });
+ }),
+ null,
+ 20,
+ );
+ assert.equal(value, null);
+ assert.equal(aborted, true);
+});
+
+test("a probe that answers keeps its answer", async () => {
+ const value = await settleWithin(async () => "ok", null, 1_000);
+ assert.equal(value, "ok");
+});
+
+test("a probe that throws falls back", async () => {
+ const value = await settleWithin(async () => {
+ throw new Error("connection refused");
+ }, null, 1_000);
+ assert.equal(value, null);
+});
+
+test("an unanswerable backend still reaches the idle deadline", async () => {
+ // The end-to-end shape of the P1: bounded probes let the wait's own deadline fire.
+ let now = 0;
+ let probes = 0;
+ const outcome = await waitForBackendIdle({
+ cancelled: () => false,
+ probe: async () => {
+ probes += 1;
+ // Every probe burns its full timeout and answers "not idle".
+ now += 10_000;
+ return false;
+ },
+ sleep: async (ms: number) => {
+ now += ms;
+ },
+ now: () => now,
+ pollMs: 20_000,
+ timeoutMs: 60_000,
+ });
+ assert.equal(outcome, "timeout");
+ assert.ok(probes <= 4, `expected the deadline to stop the loop, ran ${probes} probes`);
+});
+
+test("only a running stage for the offered version is adopted", () => {
+ // The webview reloaded while start_staged_update was running: the hook lost its
+ // own record of it, and the native side rejects a second request.
+ assert.equal(
+ stagingDecision({
+ inApp: true,
+ isExternalServer: false,
+ offeredVersion: "0.1.901",
+ staged: staged({
+ state: "partial",
+ staging: true,
+ stagingShellVersion: "0.1.901",
+ }),
+ }),
+ "adopt",
+ );
+ assert.equal(
+ stagingDecision({
+ inApp: true,
+ isExternalServer: false,
+ offeredVersion: "0.1.902",
+ staged: staged({
+ state: "partial",
+ staging: true,
+ stagingShellVersion: "0.1.901",
+ }),
+ }),
+ "wait",
+ );
+ // A partial stage with nothing running is leftover, and is restaged.
+ assert.equal(
+ stagingDecision({
+ inApp: true,
+ isExternalServer: false,
+ offeredVersion: "0.1.901",
+ staged: staged({ state: "partial" }),
+ }),
+ "stage",
+ );
+ // A finished stage for this offer is still reused rather than adopted.
+ assert.equal(
+ stagingDecision({
+ inApp: true,
+ isExternalServer: false,
+ offeredVersion: "0.1.901",
+ staged: staged({
+ state: "ready",
+ shellVersion: "0.1.901",
+ staging: true,
+ stagingShellVersion: "0.1.901",
+ }),
+ }),
+ "already-ready",
+ );
+});
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index bb2dfc89cd0..aac61eb140a 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -249,6 +249,7 @@ function Add-ToUserPath {
[ValidateSet('Append','Prepend')]
[string]$Position = 'Append'
)
+ if (Get-Variable -Name StageRoot -ValueOnly -ErrorAction SilentlyContinue) { return $false }
try {
$regKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Environment')
try {
@@ -530,6 +531,9 @@ function Test-UnslothCmdShimFile {
# Shared default cache, or the custom Unsloth home's llama.cpp tree.
function Get-ManagedLlamaCppDir {
+ if ($StageRoot) {
+ return (Join-Path $StageRoot "llama.cpp")
+ }
if (-not (Test-StudioHomeIsCustom)) {
return (Join-Path $env:USERPROFILE ".unsloth\llama.cpp")
}
@@ -1544,6 +1548,7 @@ function Test-VCRedistInstalled {
# and Build Tools torch cannot import without it, and winget is absent on LTSC/Server images.
function Ensure-VCRedist {
if (Test-VCRedistInstalled) { step "vcredist" "present"; return }
+ if ($StageRoot) { step "vcredist" "missing; unchanged during staging" "Yellow"; return }
Write-StudioLine "Microsoft Visual C++ Redistributable (2015-2022) is missing; the prebuilt llama.cpp and PyTorch need it. Installing the runtime..." -ForegroundColor Yellow
if ($null -ne (Get-Command winget -ErrorAction SilentlyContinue)) {
try {
@@ -1930,7 +1935,9 @@ if ($_studioOverride) {
} else {
$StudioHome = Join-Path $env:USERPROFILE ".unsloth\studio"
}
-$VenvDir = Join-Path $StudioHome "unsloth_studio"
+$StageRoot = if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_STAGE_ROOT)) { $env:UNSLOTH_STUDIO_STAGE_ROOT.Trim() } else { $null }
+$RuntimeRoot = if ($StageRoot) { $StageRoot } else { $StudioHome }
+$VenvDir = Join-Path $RuntimeRoot "unsloth_studio"
$StudioOwnedMarker = ".unsloth-studio-owned"
# Mirrors install_manifest.NO_TORCH_MARKER; keep the two in step.
$NoTorchMarker = ".unsloth-no-torch"
@@ -1946,28 +1953,30 @@ if ($llamaPreflightFailure) {
}
# Back up User PATH under HKCU\Software\Unsloth before any modifications.
-try {
- $envKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false)
- if ($envKey) {
- try {
- $rawPath = $envKey.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
- } finally {
- $envKey.Close()
- }
- if ($rawPath) {
- $backupKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\Unsloth')
+if (-not $StageRoot) {
+ try {
+ $envKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $false)
+ if ($envKey) {
try {
- $existingBackup = $backupKey.GetValue('PathBackup', $null)
- if (-not $existingBackup) {
- $backupKey.SetValue('PathBackup', $rawPath, [Microsoft.Win32.RegistryValueKind]::ExpandString)
- }
+ $rawPath = $envKey.GetValue('Path', '', [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames)
} finally {
- $backupKey.Close()
+ $envKey.Close()
+ }
+ if ($rawPath) {
+ $backupKey = [Microsoft.Win32.Registry]::CurrentUser.CreateSubKey('Software\Unsloth')
+ try {
+ $existingBackup = $backupKey.GetValue('PathBackup', $null)
+ if (-not $existingBackup) {
+ $backupKey.SetValue('PathBackup', $rawPath, [Microsoft.Win32.RegistryValueKind]::ExpandString)
+ }
+ } finally {
+ $backupKey.Close()
+ }
}
}
+ } catch {
+ Write-StudioLine "[DEBUG] Could not back up User PATH: $($_.Exception.Message)" -ForegroundColor DarkGray
}
-} catch {
- Write-StudioLine "[DEBUG] Could not back up User PATH: $($_.Exception.Message)" -ForegroundColor DarkGray
}
# ==========================================================================
@@ -2794,6 +2803,8 @@ try {
if ($LongPathsEnabled) {
step "long paths" "enabled"
+} elseif ($StageRoot) {
+ step "long paths" "disabled; unchanged during staging" "Yellow"
} else {
Write-StudioLine "Windows Long Paths not enabled (required for Triton compilation and deep dependency paths)." -ForegroundColor Yellow
Write-StudioLine " Requesting admin access to fix..." -ForegroundColor Yellow
@@ -2857,14 +2868,19 @@ if (-not $HasGit) {
if ($_prForce -match '^\d+$' -and [int]$_prForce -gt 0) { $gitNeeded = $true }
if ($_llamaSrc -ne "https://github.com/ggml-org/llama.cpp") { $gitNeeded = $true }
}
- Write-StudioLine "Git not found -- attempting install via winget..." -ForegroundColor Yellow
- $HasWinget = $null -ne (Get-Command winget -ErrorAction SilentlyContinue)
- if ($HasWinget) {
- try {
- Invoke-SetupCommand { winget install Git.Git --source winget --accept-package-agreements --accept-source-agreements } | Out-Null
- Refresh-Environment
- $HasGit = $null -ne (Get-Command git -ErrorAction SilentlyContinue)
- } catch { }
+ if ($gitNeeded -and $StageRoot) {
+ Exit-SetupFailure "Background staging cannot install Git; retry with the foreground updater."
+ }
+ if ($gitNeeded -or -not $StageRoot) {
+ Write-StudioLine "Git not found -- attempting install via winget..." -ForegroundColor Yellow
+ $HasWinget = $null -ne (Get-Command winget -ErrorAction SilentlyContinue)
+ if ($HasWinget) {
+ try {
+ Invoke-SetupCommand { winget install Git.Git --source winget --accept-package-agreements --accept-source-agreements } | Out-Null
+ Refresh-Environment
+ $HasGit = $null -ne (Get-Command git -ErrorAction SilentlyContinue)
+ } catch { }
+ }
}
if (-not $HasGit) {
if ($gitNeeded) {
@@ -3278,32 +3294,35 @@ $NodeSource = $null
if (-not $IsPipInstall) {
# Put Node beside the Unsloth root. OXC can still need npm when the
# frontend build is skipped.
- if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_HOME)) { $NodeOverride = $env:UNSLOTH_STUDIO_HOME.Trim() }
- elseif (-not [string]::IsNullOrWhiteSpace($env:STUDIO_HOME)) { $NodeOverride = $env:STUDIO_HOME.Trim() }
- if ($NodeOverride) {
- if ($NodeOverride -eq "~") {
- $NodeOverride = $env:USERPROFILE
- } elseif ($NodeOverride -like "~/*" -or $NodeOverride -like "~\*") {
- $NodeOverride = (Join-Path $env:USERPROFILE $NodeOverride.Substring(1).TrimStart('/', '\'))
- }
- if (-not (Test-Path -LiteralPath $NodeOverride -PathType Container)) {
- Write-StudioLine "ERROR: UNSLOTH_STUDIO_HOME/STUDIO_HOME=$NodeOverride does not exist." -ForegroundColor Red
- Write-StudioLine " Run install.ps1 to create the install root before 'unsloth studio update'." -ForegroundColor Red
- Exit-SetupFailure "UNSLOTH_STUDIO_HOME/STUDIO_HOME=$NodeOverride does not exist"
- }
- $NodeParent = (Resolve-Path -LiteralPath $NodeOverride).Path
- # An override pointing at the legacy default maps to the legacy sibling
- # ~/.unsloth/node (what the runtime resolver and setup.sh use), not <root>/node.
- $_legacyStudio = Join-Path $env:USERPROFILE ".unsloth\studio"
- if (Test-Path -LiteralPath $_legacyStudio -PathType Container) {
- $_legacyStudio = (Resolve-Path -LiteralPath $_legacyStudio).Path
- }
- if ($NodeParent -eq $_legacyStudio) {
+ if ($StageRoot) {
+ $NodeParent = $StageRoot
+ } else {
+ if (-not [string]::IsNullOrWhiteSpace($env:UNSLOTH_STUDIO_HOME)) { $NodeOverride = $env:UNSLOTH_STUDIO_HOME.Trim() }
+ elseif (-not [string]::IsNullOrWhiteSpace($env:STUDIO_HOME)) { $NodeOverride = $env:STUDIO_HOME.Trim() }
+ if ($NodeOverride) {
+ if ($NodeOverride -eq "~") {
+ $NodeOverride = $env:USERPROFILE
+ } elseif ($NodeOverride -like "~/*" -or $NodeOverride -like "~\*") {
+ $NodeOverride = (Join-Path $env:USERPROFILE $NodeOverride.Substring(1).TrimStart('/', '\'))
+ }
+ if (-not (Test-Path -LiteralPath $NodeOverride -PathType Container)) {
+ Write-StudioLine "ERROR: UNSLOTH_STUDIO_HOME/STUDIO_HOME=$NodeOverride does not exist." -ForegroundColor Red
+ Write-StudioLine " Run install.ps1 to create the install root before 'unsloth studio update'." -ForegroundColor Red
+ Exit-SetupFailure "UNSLOTH_STUDIO_HOME/STUDIO_HOME=$NodeOverride does not exist"
+ }
+ $NodeParent = (Resolve-Path -LiteralPath $NodeOverride).Path
+ # legacy default overrides map to ~/.unsloth/node, matching runtime resolution.
+ $_legacyStudio = Join-Path $env:USERPROFILE ".unsloth\studio"
+ if (Test-Path -LiteralPath $_legacyStudio -PathType Container) {
+ $_legacyStudio = (Resolve-Path -LiteralPath $_legacyStudio).Path
+ }
+ if ($NodeParent -eq $_legacyStudio) {
+ $NodeParent = Join-Path $env:USERPROFILE ".unsloth"
+ $NodeOverride = $null
+ }
+ } else {
$NodeParent = Join-Path $env:USERPROFILE ".unsloth"
- $NodeOverride = $null
}
- } else {
- $NodeParent = Join-Path $env:USERPROFILE ".unsloth"
}
$NodeDir = Join-Path $NodeParent "node"
@@ -3858,7 +3877,7 @@ substep "Python found: $PythonCmd"
# cache clear stays here. Venv-gated: a writable-but-empty override still fails the
# venv check below, and clearing first would cost the cache for a run that then does
# nothing. Still before any install work.
-if (Test-Path -LiteralPath (Join-Path $VenvDir "Scripts\python.exe") -PathType Leaf) {
+if (-not $StageRoot -and (Test-Path -LiteralPath (Join-Path $VenvDir "Scripts\python.exe") -PathType Leaf)) {
Clear-WebViewCaches
}
@@ -4615,14 +4634,23 @@ function Install-UvFromPinnedRelease {
}
$ActivateScript = Join-Path $VenvDir "Scripts\Activate.ps1"
-. $ActivateScript
+function Enter-StudioVenv {
+ if ($StageRoot) {
+ $env:VIRTUAL_ENV = $VenvDir
+ $env:PATH = (Join-Path $VenvDir "Scripts") + ";" + $env:PATH
+ Remove-Item Env:PYTHONHOME -ErrorAction SilentlyContinue
+ return
+ }
+ . $ActivateScript
+}
+Enter-StudioVenv
Assert-VenvActivated -VenvDir $VenvDir
# Try to use uv (much faster than pip), fall back to pip if unavailable
$UseUv = $false
if (Get-Command uv -ErrorAction SilentlyContinue) {
$UseUv = $true
-} else {
+} elseif (-not $StageRoot) {
substep "installing uv package manager..."
try {
$script:UvPinnedInstalled = $false
@@ -4640,7 +4668,7 @@ if (Get-Command uv -ErrorAction SilentlyContinue) {
Refresh-Environment
# Re-activate venv since Refresh-Environment rebuilds PATH from
# registry and drops the venv's Scripts directory
- . $ActivateScript
+ Enter-StudioVenv
if (Get-Command uv -ErrorAction SilentlyContinue) { $UseUv = $true }
} catch { }
}
@@ -4958,14 +4986,16 @@ if ($script:UnslothVerbose) {
# Triton/inductor filenames are long and can hit Windows MAX_PATH (260). With long
# paths on, cache under Unsloth home; else use a short drive-root dir for headroom.
-if ($LongPathsEnabled) {
- $TorchCacheDir = Join-Path $StudioHome "TORCHINDUCTOR_CACHE_DIR"
+if ($StageRoot -or $LongPathsEnabled) {
+ $TorchCacheDir = Join-Path $RuntimeRoot "TORCHINDUCTOR_CACHE_DIR"
} else {
$TorchCacheDir = "C:\tc"
}
if (-not (Test-Path -LiteralPath $TorchCacheDir)) { [System.IO.Directory]::CreateDirectory($TorchCacheDir) | Out-Null }
$env:TORCHINDUCTOR_CACHE_DIR = $TorchCacheDir
-[Environment]::SetEnvironmentVariable('TORCHINDUCTOR_CACHE_DIR', $TorchCacheDir, 'User')
+if (-not $StageRoot) {
+ [Environment]::SetEnvironmentVariable('TORCHINDUCTOR_CACHE_DIR', $TorchCacheDir, 'User')
+}
substep "TORCHINDUCTOR_CACHE_DIR set to $TorchCacheDir (avoids MAX_PATH issues)"
# Explicit pin (URL or family) wins over GPU probing and suppresses the AMD reroute below;
@@ -5493,9 +5523,9 @@ if ($stackExit -ne 0) {
# Runs outside the deps fast-path gate so that upgrades from the legacy
# single .venv_t5 are always migrated to the tiered layout.
# T5 sidecar venvs live under the resolved $StudioHome so custom installs are self-contained.
-$VenvT5_530Dir = Join-Path $StudioHome ".venv_t5_530"
-$VenvT5_550Dir = Join-Path $StudioHome ".venv_t5_550"
-$VenvT5_510Dir = Join-Path $StudioHome ".venv_t5_510"
+$VenvT5_530Dir = Join-Path $RuntimeRoot ".venv_t5_530"
+$VenvT5_550Dir = Join-Path $RuntimeRoot ".venv_t5_550"
+$VenvT5_510Dir = Join-Path $RuntimeRoot ".venv_t5_510"
$VenvT5Legacy = Join-Path $StudioHome ".venv_t5"
function Test-TargetPackageVersion {
@@ -5520,8 +5550,13 @@ function Test-TargetPackageVersion {
$_NeedT5Install = $false
if (Test-Path -LiteralPath $VenvT5Legacy) {
- Assert-StudioOwnedOrAbsent -Path $VenvT5Legacy -Label "legacy transformers sidecar venv"
- Remove-Item -LiteralPath $VenvT5Legacy -Recurse -Force
+ # Legacy layout -- migrate. The tiered venvs a staged run builds land under the
+ # stage root and may never be activated, so removing the live legacy one here
+ # would strip the running install of its only sidecar. The live update does it.
+ if (-not $StageRoot) {
+ Assert-StudioOwnedOrAbsent -Path $VenvT5Legacy -Label "legacy transformers sidecar venv"
+ Remove-Item -LiteralPath $VenvT5Legacy -Recurse -Force
+ }
$_NeedT5Install = $true
}
if (-not (Test-Path -LiteralPath $VenvT5_530Dir)) { $_NeedT5Install = $true }
@@ -6149,6 +6184,10 @@ if ($env:WHISPER_SERVER_PATH -or $env:UNSLOTH_WHISPER_CPP_PATH) {
}
}
+if ($StageRoot -and $NeedLlamaSourceBuild) {
+ Exit-SetupFailure "Background staging cannot install system build tools for llama.cpp; retry with the foreground updater."
+}
+
# ==========================================================================
# PHASE 3.5: Install OpenSSL dev (for HTTPS support in llama-server)
# ==========================================================================
diff --git a/studio/setup.sh b/studio/setup.sh
index 8ab164efe13..ad7326d8c06 100755
--- a/studio/setup.sh
+++ b/studio/setup.sh
@@ -938,16 +938,18 @@ else
STUDIO_HOME="$HOME/.unsloth/studio"
fi
-VENV_DIR="$STUDIO_HOME/unsloth_studio"
-VENV_T5_530_DIR="$STUDIO_HOME/.venv_t5_530"
-VENV_T5_550_DIR="$STUDIO_HOME/.venv_t5_550"
-VENV_T5_510_DIR="$STUDIO_HOME/.venv_t5_510"
+STAGE_ROOT="${UNSLOTH_STUDIO_STAGE_ROOT:-}"
+RUNTIME_ROOT="${STAGE_ROOT:-$STUDIO_HOME}"
+VENV_DIR="$RUNTIME_ROOT/unsloth_studio"
+VENV_T5_530_DIR="$RUNTIME_ROOT/.venv_t5_530"
+VENV_T5_550_DIR="$RUNTIME_ROOT/.venv_t5_550"
+VENV_T5_510_DIR="$RUNTIME_ROOT/.venv_t5_510"
# The override is validated, so a typo can no longer cost the cache. Venv-gated because
# a writable-but-empty override still aborts at the venv check below, and clearing first
# would cost the cache for a run that then does nothing; a fresh install has neither venv
# nor cache. Still before any install work, while the old frontend is the one on disk.
-if [ -x "$VENV_DIR/bin/python" ]; then
+if [ -z "$STAGE_ROOT" ] && [ -x "$VENV_DIR/bin/python" ]; then
_clear_webview_caches
fi
@@ -1162,7 +1164,9 @@ decide_node_source() {
}
# Mirror the llama.cpp UNSLOTH_HOME derivation; the frontend build runs first.
-if [ "$_STUDIO_HOME_IS_CUSTOM" = true ]; then
+if [ -n "$STAGE_ROOT" ]; then
+ _NODE_PARENT="$RUNTIME_ROOT"
+elif [ "$_STUDIO_HOME_IS_CUSTOM" = true ]; then
_NODE_PARENT="$STUDIO_HOME"
else
_NODE_PARENT="$HOME/.unsloth"
@@ -1436,6 +1440,12 @@ if [ ! -x "$VENV_DIR/bin/python" ]; then
substep "curl -fsSL https://unsloth.ai/install.sh | sh"
setup_fail 1 "Virtual environment not found at $VENV_DIR"
fi
+elif [ -n "$STAGE_ROOT" ]; then
+ VIRTUAL_ENV="$VENV_DIR"
+ PATH="$VENV_DIR/bin:$PATH"
+ export VIRTUAL_ENV PATH
+ unset PYTHONHOME
+ hash -r 2>/dev/null || true
else
source "$VENV_DIR/bin/activate"
fi
@@ -1744,6 +1754,8 @@ _setup_persist_uv_path() {
USE_UV=false
if command -v uv &>/dev/null; then
USE_UV=true
+elif [ -n "$STAGE_ROOT" ]; then
+ step "uv" "using pip inside the staged environment"
elif {
_SETUP_UV_PINNED_OK=false
if _setup_install_uv_pinned; then
@@ -2012,9 +2024,13 @@ _target_has_pkg_version() {
}
_NEED_T5_INSTALL=false
if [ -d "$STUDIO_HOME/.venv_t5" ]; then
- # Legacy layout — migrate
- _assert_studio_owned_or_absent "$STUDIO_HOME/.venv_t5" "legacy transformers sidecar venv"
- rm -rf "$STUDIO_HOME/.venv_t5"
+ # Legacy layout — migrate. The tiered venvs a staged run builds land under the
+ # stage root and may never be activated, so removing the live legacy one here
+ # would strip the running install of its only sidecar. The live update does it.
+ if [ -z "$STAGE_ROOT" ]; then
+ _assert_studio_owned_or_absent "$STUDIO_HOME/.venv_t5" "legacy transformers sidecar venv"
+ rm -rf "$STUDIO_HOME/.venv_t5"
+ fi
_NEED_T5_INSTALL=true
fi
[ ! -d "$VENV_T5_530_DIR" ] && _NEED_T5_INSTALL=true
@@ -2460,7 +2476,9 @@ fi
# ── 7. Prefer prebuilt llama.cpp bundles before any source build path ──
# Nest llama.cpp under $STUDIO_HOME only for real env-overrides; legacy
# default keeps ~/.unsloth/llama.cpp so pre-PR builds are still discovered.
-if [ "$_STUDIO_HOME_IS_CUSTOM" = true ]; then
+if [ -n "$STAGE_ROOT" ]; then
+ UNSLOTH_HOME="$RUNTIME_ROOT"
+elif [ "$_STUDIO_HOME_IS_CUSTOM" = true ]; then
UNSLOTH_HOME="$STUDIO_HOME"
else
UNSLOTH_HOME="$HOME/.unsloth"
@@ -2823,6 +2841,10 @@ if [ "$_NEED_LLAMA_SOURCE_BUILD" = true ] && \
_NEED_LLAMA_SOURCE_BUILD=false
fi
+if [ -n "$STAGE_ROOT" ] && [ "$_NEED_LLAMA_SOURCE_BUILD" = true ]; then
+ setup_fail 1 "Background staging cannot install system build tools for llama.cpp; retry with the foreground updater."
+fi
+
# ── 8. WSL: pre-install GGUF build dependencies for fallback source builds ──
# On WSL, sudo requires a password and can't be entered during GGUF export
# (runs in a non-interactive subprocess). Install build deps here instead.
@@ -3480,7 +3502,8 @@ else
# a later setup run report "already matches" and skip repairing the
# prebuilt over the source binary. Drop it before building.
rm -f "$WHISPER_CPP_DIR/UNSLOTH_WHISPER_PREBUILT_INFO.json" 2>/dev/null || true
- if run_quiet_no_exit "whisper.cpp source build" sh "$_WHISPER_BUILD"; then
+ if run_quiet_no_exit "whisper.cpp source build" \
+ env UNSLOTH_HOME="$UNSLOTH_HOME" sh "$_WHISPER_BUILD"; then
_WHISPER_RECOVERED=true
step "whisper.cpp" "source build installed"
if [ "$_STUDIO_HOME_IS_CUSTOM" = true ] && [ -d "$WHISPER_CPP_DIR" ]; then
diff --git a/studio/src-tauri/src/commands.rs b/studio/src-tauri/src/commands.rs
index dedc0faba15..ee7206ecd2c 100644
--- a/studio/src-tauri/src/commands.rs
+++ b/studio/src-tauri/src/commands.rs
@@ -1,6 +1,8 @@
use crate::diagnostics::{self, DiagnosticsState};
use crate::install;
use crate::process::{self, BackendState, ShutdownFlag};
+use crate::desktop_updater;
+use crate::staged_update;
use crate::update;
use log::{error, info, warn};
use std::time::{Duration, Instant};
@@ -348,7 +350,12 @@ pub async fn start_server(
info!("start_server command called with port {}", port);
let diagnostics_state = diagnostics.inner().clone();
- let generation = process::start_backend(&app, &state, port, &shutdown, &diagnostics_state)?;
+ let generation = match process::start_backend(&app, &state, port, &shutdown, &diagnostics_state)
+ {
+ Ok(generation) => generation,
+ Err(_error) if process::request_staged_rollback_restart(&app, &state) => return Ok(()),
+ Err(error) => return Err(error),
+ };
// Spawn health watchdog for the owned backend — detects
// deadlocks and hangs that stdout-based crash detection misses.
@@ -383,7 +390,12 @@ pub async fn start_managed_server(
let started = Instant::now();
let diagnostics_state = diagnostics.inner().clone();
- let generation = process::start_backend(&app, &state, port, &shutdown, &diagnostics_state)?;
+ let generation = match process::start_backend(&app, &state, port, &shutdown, &diagnostics_state)
+ {
+ Ok(generation) => generation,
+ Err(_error) if process::request_staged_rollback_restart(&app, &state) => return Ok(()),
+ Err(error) => return Err(error),
+ };
info!(
"start_managed_server spawned generation={} in {}ms",
@@ -827,6 +839,81 @@ pub async fn start_backend_update(
.map_err(|e| format!("Update task panicked: {e}"))?
}
+#[tauri::command]
+pub async fn start_staged_update(
+ app: AppHandle,
+ update_state: tauri::State<'_, update::UpdateState>,
+ install_state: tauri::State<'_, install::InstallState>,
+ desktop_update: tauri::State<'_, desktop_updater::DesktopUpdateState>,
+ diagnostics: tauri::State<'_, DiagnosticsState>,
+) -> Result<(), String> {
+ info!("start_staged_update command called");
+
+ if install_state
+ .lock()
+ .map(|s| s.child.is_some())
+ .unwrap_or(false)
+ {
+ return Err("Cannot prepare an update while installation is in progress.".to_string());
+ }
+ if update::is_staged_update_running(&update_state) || update::is_update_running(&update_state) {
+ return Err("Update is already running.".to_string());
+ }
+
+ let shell_version = desktop_updater::pending_version(&desktop_update)?;
+ let backend_version = desktop_updater::pending_backend_version(&desktop_update)?;
+ let state = update_state.inner().clone();
+ let diagnostics_state = diagnostics.inner().clone();
+ tokio::task::spawn_blocking(move || {
+ update::run_staged_update(app, state, diagnostics_state, shell_version, backend_version)
+ })
+ .await
+ .map_err(|e| format!("Staged update task panicked: {e}"))?
+}
+
+#[tauri::command]
+pub fn cancel_staged_update(
+ update_state: tauri::State<'_, update::UpdateState>,
+ diagnostics: tauri::State<'_, DiagnosticsState>,
+) -> Result<(), String> {
+ let staged = update_state
+ .lock()
+ .map(|s| s.child.is_some() && s.staged)
+ .unwrap_or(false);
+ if !staged {
+ return Ok(());
+ }
+ update::record_update_intentional_stop(&update_state, &diagnostics);
+ update::stop_update(&update_state)?;
+ process::with_studio_runtime_launch_guard(|| {
+ staged_update::discard(&diagnostics::studio_dir());
+ Ok(())
+ })
+}
+
+#[tauri::command]
+pub fn staged_update_status(
+ update_state: tauri::State<'_, update::UpdateState>,
+) -> staged_update::StagedUpdateStatus {
+ let mut status = staged_update::status(&diagnostics::studio_dir());
+ status.staging = update::is_staged_update_running(&update_state);
+ status.staging_shell_version = update::staged_update_shell_version(&update_state);
+ status
+}
+
+#[tauri::command]
+pub fn discard_staged_update(
+ update_state: tauri::State<'_, update::UpdateState>,
+) -> Result<(), String> {
+ if update::is_update_running(&update_state) {
+ return Err("Update is already running.".to_string());
+ }
+ process::with_studio_runtime_launch_guard(|| {
+ staged_update::discard(&diagnostics::studio_dir());
+ Ok(())
+ })
+}
+
/// Repair a stale managed Unsloth install.
/// Whether a native path lease this app signs can actually be verified.
///
@@ -2190,7 +2277,10 @@ async fn health_watchdog(
"missing_validated_port",
);
error!("Health watchdog: backend never reported a validated port, killing and declaring dead");
- let _ = process::stop_backend(&state, &shutdown, Some(&diagnostics));
+ let stopped = process::stop_backend(&state, &shutdown, Some(&diagnostics));
+ if stopped.is_ok() && process::request_staged_rollback_restart(&app, &state) {
+ break;
+ }
let _ = app.emit("server-crashed", ());
break;
}
@@ -2313,7 +2403,10 @@ async fn health_watchdog(
} else {
error!("Health watchdog: backend unresponsive, killing and declaring dead");
// Kill the zombie process so retry can start fresh
- let _ = process::stop_backend(&state, &shutdown, Some(&diagnostics));
+ let stopped = process::stop_backend(&state, &shutdown, Some(&diagnostics));
+ if stopped.is_ok() && process::request_staged_rollback_restart(&app, &state) {
+ break;
+ }
}
let _ = app.emit("server-crashed", ());
break;
diff --git a/studio/src-tauri/src/desktop_backend_owner.rs b/studio/src-tauri/src/desktop_backend_owner.rs
index 4d7dfb296e9..25a06c3d61f 100644
--- a/studio/src-tauri/src/desktop_backend_owner.rs
+++ b/studio/src-tauri/src/desktop_backend_owner.rs
@@ -79,6 +79,7 @@ pub(crate) struct VerifiedOwnedBackend {
pub backend_pid: u32,
pub generation: u64,
pub readiness: OwnedBackendReadiness,
+ pub backend_version: Option<String>,
}
#[allow(dead_code)]
@@ -126,6 +127,7 @@ struct HealthDesktopOwner {
struct HealthResponse {
version: Option<String>,
native_path_leases_supported: Option<bool>,
+ torch_warm_in_progress: Option<bool>,
}
#[derive(Debug)]
@@ -825,37 +827,6 @@ fn ready_for_use_status(health: Option<&HealthResponse>) -> OwnedBackendReadines
}
}
-async fn health_ready_status(
- port: u16,
- access_token: Option<&str>,
-) -> Result<OwnedBackendReadiness, String> {
- match fetch_health(port, access_token).await {
- Ok(health) => {
- let authenticated_version = health
- .as_ref()
- .and_then(|health| health.version.as_deref())
- .filter(|version| !version.is_empty());
- if access_token.is_some() {
- let Some(version) = authenticated_version else {
- return Err("desktop_auth_health_unverified".to_string());
- };
- if let Some(reason) = crate::preflight::backend_version_stale_reason(Some(version))
- {
- return if reason == "desktop_backend_version_too_old" {
- Ok(OwnedBackendReadiness::Stale { reason })
- } else {
- Err(reason)
- };
- }
- return Ok(ready_for_use_status(health.as_ref()));
- }
- Ok(ready_for_use_status(health.as_ref()))
- }
- Err(reason) if access_token.is_some() => Err(reason),
- Err(reason) => Ok(OwnedBackendReadiness::Stale { reason }),
- }
-}
-
async fn fetch_liveness(
port: u16,
timeout: Duration,
@@ -966,8 +937,34 @@ async fn authenticated_health_ready_status(
port: u16,
secret: &str,
) -> Result<OwnedBackendReadiness, String> {
+ authenticated_health_ready(port, secret)
+ .await
+ .map(|(readiness, _, _)| readiness)
+}
+
+async fn authenticated_health_ready(
+ port: u16,
+ secret: &str,
+) -> Result<(OwnedBackendReadiness, String, bool), String> {
let access_token = desktop_secret_login(port, secret).await?;
- health_ready_status(port, Some(&access_token)).await
+ let health = fetch_health(port, Some(&access_token))
+ .await?
+ .ok_or_else(|| "desktop_auth_health_unverified".to_string())?;
+ let version = health
+ .version
+ .as_deref()
+ .filter(|version| !version.is_empty())
+ .ok_or_else(|| "desktop_auth_health_unverified".to_string())?;
+ if let Some(reason) = crate::preflight::backend_version_stale_reason(Some(version)) {
+ if reason != "desktop_backend_version_too_old" {
+ return Err(reason);
+ }
+ }
+ Ok((
+ ready_for_use_status(Some(&health)),
+ version.to_string(),
+ health.torch_warm_in_progress.unwrap_or(false),
+ ))
}
pub(crate) async fn probe_owned_backend_state(
@@ -991,6 +988,24 @@ pub(crate) async fn probe_owned_backend_state_with_timeout(
require_desktop_secret: bool,
timeout: Duration,
) -> OwnedBackendProbe {
+ probe_owned_backend_state_with_warmup(owner, port, require_desktop_secret, timeout)
+ .await
+ .0
+}
+
+pub(crate) async fn probe_owned_backend_state_for_staged_activation(
+ owner: BackendOwnerState,
+ port: Option<u16>,
+) -> (OwnedBackendProbe, bool) {
+ probe_owned_backend_state_with_warmup(owner, port, true, LOCAL_HTTP_TIMEOUT).await
+}
+
+async fn probe_owned_backend_state_with_warmup(
+ owner: BackendOwnerState,
+ port: Option<u16>,
+ require_desktop_secret: bool,
+ timeout: Duration,
+) -> (OwnedBackendProbe, bool) {
let ports: Vec<u16> = match port {
Some(port) => vec![port],
None => desktop_candidate_ports().collect(),
@@ -1016,58 +1031,73 @@ pub(crate) async fn probe_owned_backend_state_with_timeout(
continue;
}
if let Some(reason) = lifecycle_control_block_reason(&liveness) {
- return OwnedBackendProbe::Unmanageable { port, reason };
+ return (OwnedBackendProbe::Unmanageable { port, reason }, false);
}
if !desktop_login_route_compatible(port, timeout).await {
- return OwnedBackendProbe::Unmanageable {
- port,
- reason: "desktop_login_probe_failed".to_string(),
- };
+ return (
+ OwnedBackendProbe::Unmanageable {
+ port,
+ reason: "desktop_login_probe_failed".to_string(),
+ },
+ false,
+ );
}
- let readiness = if require_desktop_secret {
+ let (readiness, backend_version, torch_warm_in_progress) = if require_desktop_secret {
let secret = match read_desktop_secret() {
Ok(Some(secret)) => secret,
Ok(None) => {
- return OwnedBackendProbe::Unmanageable {
- port,
- reason: "desktop_auth_secret_missing".to_string(),
- }
+ return (
+ OwnedBackendProbe::Unmanageable {
+ port,
+ reason: "desktop_auth_secret_missing".to_string(),
+ },
+ false,
+ )
}
- Err(reason) => return OwnedBackendProbe::Unmanageable { port, reason },
+ Err(reason) => return (OwnedBackendProbe::Unmanageable { port, reason }, false),
};
- match authenticated_health_ready_status(port, &secret).await {
- Ok(readiness) => readiness,
- Err(reason) => return OwnedBackendProbe::Unmanageable { port, reason },
+ match authenticated_health_ready(port, &secret).await {
+ Ok((readiness, version, torch_warm_in_progress)) => {
+ (readiness, Some(version), torch_warm_in_progress)
+ }
+ Err(reason) => return (OwnedBackendProbe::Unmanageable { port, reason }, false),
}
} else {
// Spawned backends were launched from the already-probed managed
// install. Adopted backends pass `true` on their initial probe;
// later watchdog checks only need ownership and liveness.
- OwnedBackendReadiness::Ready
+ (OwnedBackendReadiness::Ready, None, false)
};
- verified.push((port, readiness));
+ verified.push((port, readiness, backend_version, torch_warm_in_progress));
}
if verified.len() != 1 {
- return OwnedBackendProbe::NotVerified {
- reason: if !verified.is_empty() {
- "owned_backend_ambiguous".to_string()
- } else if answered_with_a_different_owner {
- OWNED_BACKEND_OWNER_MISMATCH.to_string()
- } else {
- "owned_backend_not_found".to_string()
+ return (
+ OwnedBackendProbe::NotVerified {
+ reason: if !verified.is_empty() {
+ "owned_backend_ambiguous".to_string()
+ } else if answered_with_a_different_owner {
+ OWNED_BACKEND_OWNER_MISMATCH.to_string()
+ } else {
+ "owned_backend_not_found".to_string()
+ },
},
- };
+ false,
+ );
}
- let (port, readiness) = verified.remove(0);
- OwnedBackendProbe::Verified(VerifiedOwnedBackend {
- backend_pid: owner.backend_pid(),
- generation: owner.generation(),
- owner,
- port,
- readiness,
- })
+ let (port, readiness, backend_version, torch_warm_in_progress) = verified.remove(0);
+ (
+ OwnedBackendProbe::Verified(VerifiedOwnedBackend {
+ backend_pid: owner.backend_pid(),
+ generation: owner.generation(),
+ owner,
+ port,
+ readiness,
+ backend_version,
+ }),
+ torch_warm_in_progress,
+ )
}
#[allow(dead_code)]
@@ -1414,12 +1444,15 @@ mod tests {
])
.await;
- let readiness = authenticated_health_ready_status(port, "desktop-test-secret")
- .await
- .unwrap();
+ let (readiness, version, torch_warm_in_progress) =
+ authenticated_health_ready(port, "desktop-test-secret")
+ .await
+ .unwrap();
server.await.unwrap();
assert!(matches!(readiness, OwnedBackendReadiness::Ready));
+ assert_eq!(version, "2026.8.4");
+ assert!(!torch_warm_in_progress);
let seen = seen.lock().unwrap();
assert!(seen[0].contains(r#""secret":"desktop-test-secret""#));
assert!(seen[1]
@@ -1427,6 +1460,28 @@ mod tests {
.contains("authorization: bearer test-access-token"));
}
+ #[tokio::test]
+ async fn authenticated_health_reports_torch_warm_in_progress() {
+ let (port, _, server) = http_sequence_server(vec![
+ ("200 OK", r#"{"access_token":"test-access-token"}"#),
+ (
+ "200 OK",
+ r#"{"version":"2026.8.4","native_path_leases_supported":true,"torch_warm_in_progress":true}"#,
+ ),
+ ])
+ .await;
+
+ let (readiness, version, torch_warm_in_progress) =
+ authenticated_health_ready(port, "desktop-test-secret")
+ .await
+ .unwrap();
+ server.await.unwrap();
+
+ assert!(matches!(readiness, OwnedBackendReadiness::Ready));
+ assert_eq!(version, "2026.8.4");
+ assert!(torch_warm_in_progress);
+ }
+
#[tokio::test]
async fn authenticated_health_marks_missing_or_disabled_native_leases_stale() {
for health in [
diff --git a/studio/src-tauri/src/desktop_update_policy.rs b/studio/src-tauri/src/desktop_update_policy.rs
index 724ede196cf..be8e09bfc4c 100644
--- a/studio/src-tauri/src/desktop_update_policy.rs
+++ b/studio/src-tauri/src/desktop_update_policy.rs
@@ -173,7 +173,7 @@ fn normalize_version(version: &str) -> Option<String> {
}
}
-fn compare_versions(left: &str, right: &str) -> i8 {
+pub(crate) fn compare_versions(left: &str, right: &str) -> i8 {
let Some(left) = parse_version(left) else {
return 0;
};
diff --git a/studio/src-tauri/src/desktop_updater.rs b/studio/src-tauri/src/desktop_updater.rs
index 16d542a16d2..d82096ca9d9 100644
--- a/studio/src-tauri/src/desktop_updater.rs
+++ b/studio/src-tauri/src/desktop_updater.rs
@@ -1,11 +1,165 @@
-use serde::Serialize;
-use tauri::Manager;
-use tauri_plugin_updater::UpdaterExt;
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+use std::fs::{self, File};
+use std::io::Write;
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+use tauri::{AppHandle, Emitter, Manager};
+use tauri_plugin_updater::{Update, UpdaterExt};
+
+const DOWNLOAD_EVENT: &str = "desktop-update-download";
+const DOWNLOAD_EVENT_STEP: u64 = 512 * 1024;
+const BUNDLE_FILE: &str = ".desktop-update-bundle";
+const BUNDLE_METADATA_FILE: &str = ".desktop-update-bundle.json";
+
+/// The prepared bundle lives on disk, not in this struct.
+///
+/// Preparation finishes long before the user restarts, and the whole point of the
+/// flow is that they keep training or generating in the meantime. A platform
+/// installer held in memory for that entire window is resident memory taken from
+/// exactly the workloads the background update exists to avoid interrupting.
+#[derive(Default)]
+pub(crate) struct DesktopUpdate {
+ update: Option<Update>,
+ bundle: Option<PathBuf>,
+ downloading: bool,
+}
+
+fn bundle_path() -> PathBuf {
+ crate::diagnostics::studio_dir().join(BUNDLE_FILE)
+}
+
+fn bundle_metadata_path() -> PathBuf {
+ crate::diagnostics::studio_dir().join(BUNDLE_METADATA_FILE)
+}
+
+#[derive(Deserialize, Serialize)]
+struct PreparedBundle {
+ version: String,
+ size: u64,
+ sha256: String,
+}
+
+fn sha256(bytes: &[u8]) -> String {
+ crate::native_backend_lease::hex_bytes(&Sha256::digest(bytes))
+}
+
+fn sync_parent(path: &Path) {
+ #[cfg(unix)]
+ if let Some(parent) = path.parent() {
+ let _ = File::open(parent).and_then(|directory| directory.sync_all());
+ }
+}
+
+fn write_atomic(path: &Path, bytes: &[u8]) -> Result<(), String> {
+ let parent = path
+ .parent()
+ .ok_or_else(|| format!("{} has no parent directory", path.display()))?;
+ fs::create_dir_all(parent).map_err(|error| format!("{}: {error}", parent.display()))?;
+ let mut temporary = tempfile::Builder::new()
+ .prefix(".desktop-update-")
+ .tempfile_in(parent)
+ .map_err(|error| format!("{}: {error}", parent.display()))?;
+ temporary
+ .write_all(bytes)
+ .and_then(|()| temporary.as_file().sync_all())
+ .map_err(|error| format!("{}: {error}", path.display()))?;
+ temporary
+ .persist(path)
+ .map_err(|error| format!("{}: {}", path.display(), error.error))?;
+ sync_parent(path);
+ Ok(())
+}
+
+fn discard_prepared_bundle(bundle: &Path, metadata: &Path) {
+ let _ = fs::remove_file(bundle);
+ let _ = fs::remove_file(metadata);
+}
+
+fn persist_prepared_bundle(
+ bundle: &Path,
+ metadata: &Path,
+ version: &str,
+ bytes: &[u8],
+) -> Result<(), String> {
+ discard_prepared_bundle(bundle, metadata);
+ write_atomic(bundle, bytes)?;
+ let record = PreparedBundle {
+ version: version.to_string(),
+ size: bytes.len() as u64,
+ sha256: sha256(bytes),
+ };
+ let body = serde_json::to_vec_pretty(&record).map_err(|error| error.to_string())?;
+ if let Err(error) = write_atomic(metadata, &body) {
+ discard_prepared_bundle(bundle, metadata);
+ return Err(error);
+ }
+ Ok(())
+}
+
+fn read_prepared_bundle(
+ bundle: &Path,
+ metadata: &Path,
+ expected_version: &str,
+) -> Result<Vec<u8>, String> {
+ let record: PreparedBundle = serde_json::from_slice(
+ &fs::read(metadata).map_err(|error| format!("{}: {error}", metadata.display()))?,
+ )
+ .map_err(|error| format!("{}: {error}", metadata.display()))?;
+ if record.version != expected_version {
+ return Err(format!(
+ "prepared update {} does not match {}",
+ record.version, expected_version
+ ));
+ }
+ let bytes = fs::read(bundle).map_err(|error| format!("{}: {error}", bundle.display()))?;
+ if bytes.len() as u64 != record.size || sha256(&bytes) != record.sha256 {
+ return Err("prepared update failed its integrity check".to_string());
+ }
+ Ok(bytes)
+}
+
+fn rehydrate_prepared_bundle(expected_version: &str) -> Option<PathBuf> {
+ let bundle = bundle_path();
+ let metadata = bundle_metadata_path();
+ match read_prepared_bundle(&bundle, &metadata, expected_version) {
+ Ok(_) => Some(bundle),
+ Err(_) => {
+ discard_prepared_bundle(&bundle, &metadata);
+ None
+ }
+ }
+}
+
+pub(crate) type DesktopUpdateState = Arc<Mutex<DesktopUpdate>>;
+
+pub(crate) fn new_desktop_update_state() -> DesktopUpdateState {
+ Arc::new(Mutex::new(DesktopUpdate::default()))
+}
+
+pub(crate) fn pending_version(state: &DesktopUpdateState) -> Result<Option<String>, String> {
+ let guard = state.lock().map_err(|error| error.to_string())?;
+ Ok(guard.update.as_ref().map(|update| update.version.clone()))
+}
+
+/// `pypi_version` from latest.json: the backend this shell is built against.
+pub(crate) fn pending_backend_version(
+ state: &DesktopUpdateState,
+) -> Result<Option<String>, String> {
+ let guard = state.lock().map_err(|error| error.to_string())?;
+ Ok(guard.update.as_ref().and_then(|update| {
+ update
+ .raw_json
+ .get("pypi_version")
+ .and_then(|value| value.as_str())
+ .filter(|value| !value.is_empty())
+ .map(str::to_string)
+ }))
+}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct DesktopUpdateMetadata {
- rid: tauri::ResourceId,
current_version: String,
version: String,
date: Option<String>,
@@ -13,6 +167,22 @@ pub(crate) struct DesktopUpdateMetadata {
raw_json: serde_json::Value,
}
+#[derive(Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct DesktopUpdateDownload {
+ version: String,
+ downloaded: u64,
+ total: Option<u64>,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct DesktopUpdateBundleStatus {
+ version: Option<String>,
+ downloaded: bool,
+ downloading: bool,
+}
+
/// Re-arm crash cleanup when the installer never took over.
///
/// `on_before_exit` clears kill-on-close assuming the installer is about to
@@ -46,6 +216,7 @@ pub(crate) async fn desktop_update_cleanup_armed() -> Result<bool, String> {
#[tauri::command]
pub(crate) async fn check_desktop_update(
webview: tauri::Webview,
+ state: tauri::State<'_, DesktopUpdateState>,
) -> Result<Option<DesktopUpdateMetadata>, String> {
let app = webview.app_handle().clone();
let builder = webview.updater_builder().on_before_exit(move || {
@@ -63,7 +234,12 @@ pub(crate) async fn check_desktop_update(
});
let updater = builder.build().map_err(|error| error.to_string())?;
- let Some(update) = updater.check().await.map_err(|error| error.to_string())? else {
+ let update = updater.check().await.map_err(|error| error.to_string())?;
+ let mut guard = state.lock().map_err(|error| error.to_string())?;
+ let Some(update) = update else {
+ guard.update = None;
+ guard.bundle = None;
+ discard_prepared_bundle(&bundle_path(), &bundle_metadata_path());
return Ok(None);
};
@@ -78,8 +254,161 @@ pub(crate) async fn check_desktop_update(
date,
body: update.body.clone(),
raw_json: update.raw_json.clone(),
- rid: webview.resources_table().add(update),
};
-
+ if guard.update.as_ref().map(|u| u.version.as_str()) != Some(update.version.as_str()) {
+ guard.bundle = None;
+ }
+ guard.bundle = rehydrate_prepared_bundle(&update.version);
+ guard.update = Some(update);
Ok(Some(metadata))
}
+
+#[tauri::command]
+pub(crate) async fn download_desktop_update(
+ app: AppHandle,
+ state: tauri::State<'_, DesktopUpdateState>,
+) -> Result<(), String> {
+ let update = {
+ let mut guard = state.lock().map_err(|error| error.to_string())?;
+ let Some(update) = guard.update.clone() else {
+ return Err("No desktop update has been checked.".to_string());
+ };
+ if guard.bundle.is_some() {
+ return Ok(());
+ }
+ if guard.downloading {
+ return Err("Desktop update download is already running.".to_string());
+ }
+ guard.downloading = true;
+ update
+ };
+
+ let version = update.version.clone();
+ let mut downloaded: u64 = 0;
+ let mut last_emitted: u64 = 0;
+ let progress_app = app.clone();
+ let result = update
+ .download(
+ |chunk, total| {
+ downloaded += chunk as u64;
+ if downloaded - last_emitted >= DOWNLOAD_EVENT_STEP || Some(downloaded) == total {
+ last_emitted = downloaded;
+ let _ = progress_app.emit(
+ DOWNLOAD_EVENT,
+ DesktopUpdateDownload {
+ version: version.clone(),
+ downloaded,
+ total,
+ },
+ );
+ }
+ },
+ || {},
+ )
+ .await;
+
+ let mut guard = state.lock().map_err(|error| error.to_string())?;
+ guard.downloading = false;
+ match result {
+ Ok(bytes) => {
+ if guard.update.as_ref().map(|u| u.version.as_str()) != Some(update.version.as_str()) {
+ // A newer check landed mid-download; these bytes are already stale.
+ return Ok(());
+ }
+ let path = bundle_path();
+ persist_prepared_bundle(&path, &bundle_metadata_path(), &update.version, &bytes)?;
+ guard.bundle = Some(path);
+ Ok(())
+ }
+ Err(error) => Err(error.to_string()),
+ }
+}
+
+#[tauri::command]
+pub(crate) async fn install_desktop_update(
+ state: tauri::State<'_, DesktopUpdateState>,
+) -> Result<(), String> {
+ let (update, path) = {
+ let mut guard = state.lock().map_err(|error| error.to_string())?;
+ let Some(update) = guard.update.clone() else {
+ return Err("No desktop update has been checked.".to_string());
+ };
+ let Some(path) = guard.bundle.take() else {
+ return Err("Desktop update has not been downloaded.".to_string());
+ };
+ (update, path)
+ };
+ // Read back only for the install itself, so the bytes are resident for the
+ // seconds it takes rather than for the whole session.
+ let metadata = bundle_metadata_path();
+ let bundle = match read_prepared_bundle(&path, &metadata, &update.version) {
+ Ok(bundle) => bundle,
+ Err(error) => {
+ discard_prepared_bundle(&path, &metadata);
+ return Err(format!("Prepared update is invalid: {error}"));
+ }
+ };
+ if let Err(error) = update.install(&bundle) {
+ discard_prepared_bundle(&path, &metadata);
+ return Err(error.to_string());
+ }
+ discard_prepared_bundle(&path, &metadata);
+ Ok(())
+}
+
+#[tauri::command]
+pub(crate) fn desktop_update_bundle_status(
+ state: tauri::State<'_, DesktopUpdateState>,
+) -> Result<DesktopUpdateBundleStatus, String> {
+ let guard = state.lock().map_err(|error| error.to_string())?;
+ Ok(DesktopUpdateBundleStatus {
+ version: guard.update.as_ref().map(|u| u.version.clone()),
+ downloaded: guard.bundle.as_ref().is_some_and(|path| path.is_file()),
+ downloading: guard.downloading,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_prepared_bundle_survives_state_recreation() {
+ let directory = tempfile::tempdir().unwrap();
+ let bundle = directory.path().join(BUNDLE_FILE);
+ let metadata = directory.path().join(BUNDLE_METADATA_FILE);
+ let bytes = b"signed updater bundle";
+
+ persist_prepared_bundle(&bundle, &metadata, "0.1.901", bytes).unwrap();
+
+ assert_eq!(
+ read_prepared_bundle(&bundle, &metadata, "0.1.901").unwrap(),
+ bytes
+ );
+ }
+
+ #[test]
+ fn a_corrupt_prepared_bundle_is_rejected() {
+ let directory = tempfile::tempdir().unwrap();
+ let bundle = directory.path().join(BUNDLE_FILE);
+ let metadata = directory.path().join(BUNDLE_METADATA_FILE);
+ persist_prepared_bundle(&bundle, &metadata, "0.1.901", b"verified").unwrap();
+ fs::write(&bundle, b"corrupt!").unwrap();
+
+ let error = read_prepared_bundle(&bundle, &metadata, "0.1.901").unwrap_err();
+
+ assert!(error.contains("integrity"), "{error}");
+ }
+
+ #[test]
+ fn a_bundle_for_another_release_is_rejected() {
+ let directory = tempfile::tempdir().unwrap();
+ let bundle = directory.path().join(BUNDLE_FILE);
+ let metadata = directory.path().join(BUNDLE_METADATA_FILE);
+ persist_prepared_bundle(&bundle, &metadata, "0.1.901", b"verified").unwrap();
+
+ let error = read_prepared_bundle(&bundle, &metadata, "0.1.902").unwrap_err();
+
+ assert!(error.contains("does not match"), "{error}");
+ }
+}
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index 68ce357dea0..730e7bd6628 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -20,6 +20,7 @@ mod native_path_policy;
mod preflight;
mod process;
mod process_identity;
+mod staged_update;
mod update;
mod webview_permissions;
mod windows_job;
@@ -30,7 +31,7 @@ use process::new_backend_state;
use simplelog::{
CombinedLogger, Config, LevelFilter, SharedLogger, TermLogger, TerminalMode, WriteLogger,
};
-use std::ffi::OsStr;
+use std::ffi::{OsStr, OsString};
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
@@ -49,6 +50,9 @@ static TERMINATION_CLEANUP: Mutex<bool> = Mutex::new(false);
const IN_APP_RELAUNCH_MARKER_FILE: &str = "in-app-relaunch-v1";
+#[cfg(target_os = "macos")]
+const STAGED_ROLLBACK_RELAUNCH_FLAG: &str = "--staged-rollback-relaunch-wait";
+
const CLOSE_TO_TRAY_PREFERENCE_FILE: &str = "close-to-tray-v1";
/// The user's answer to "Run Unsloth at login", kept beside the OS entry rather than derived
@@ -1819,7 +1823,71 @@ fn webview_cache_plugin<R: tauri::Runtime>() -> tauri::plugin::TauriPlugin<R> {
.build()
}
+#[cfg(target_os = "macos")]
+fn staged_rollback_relaunch_args(args: &[OsString]) -> Option<(u32, &[OsString])> {
+ if args.first()?.as_os_str() != OsStr::new(STAGED_ROLLBACK_RELAUNCH_FLAG) {
+ return None;
+ }
+ let parent = args.get(1)?.to_str()?.parse().ok()?;
+ Some((parent, &args[2..]))
+}
+
+#[cfg(target_os = "macos")]
+fn detached_relaunch_command(binary: impl AsRef<OsStr>) -> std::process::Command {
+ use std::os::unix::process::CommandExt;
+
+ let mut command = std::process::Command::new(binary);
+ command
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .process_group(0);
+ command
+}
+
+#[cfg(target_os = "macos")]
+fn run_staged_rollback_relaunch_helper() -> bool {
+ let args: Vec<OsString> = std::env::args_os().skip(1).collect();
+ let Some((parent, original_args)) = staged_rollback_relaunch_args(&args) else {
+ return false;
+ };
+ for _ in 0..1200 {
+ if !desktop_backend_owner::pid_is_not_dead(parent) {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(50));
+ }
+ if desktop_backend_owner::pid_is_not_dead(parent) {
+ eprintln!("staged rollback relaunch timed out waiting for the previous app");
+ return true;
+ }
+ match std::env::current_exe()
+ .and_then(|binary| detached_relaunch_command(binary).args(original_args).spawn())
+ {
+ Ok(_) => {}
+ Err(error) => eprintln!("staged rollback relaunch failed: {error}"),
+ }
+ true
+}
+
+#[cfg(target_os = "macos")]
+pub(crate) fn schedule_staged_rollback_relaunch(app: &tauri::AppHandle) -> Result<(), String> {
+ let binary = tauri::process::current_binary(&app.env()).map_err(|error| error.to_string())?;
+ detached_relaunch_command(binary)
+ .arg(STAGED_ROLLBACK_RELAUNCH_FLAG)
+ .arg(std::process::id().to_string())
+ .args(std::env::args_os().skip(1))
+ .spawn()
+ .map(|_| ())
+ .map_err(|error| error.to_string())
+}
+
fn main() {
+ #[cfg(target_os = "macos")]
+ if run_staged_rollback_relaunch_helper() {
+ return;
+ }
+
// Must precede any Xlib call: GTK3 never calls XInitThreads and this
// process drives X from several threads. See x11_threads for the crash.
x11_threads::init_x11_threads();
@@ -1880,6 +1948,7 @@ fn main() {
.manage(new_backend_state())
.manage(process::new_shutdown_flag())
.manage(update::new_update_state())
+ .manage(desktop_updater::new_desktop_update_state())
.manage(new_close_to_tray_state())
.manage(native_file_dialogs::ChatImportRegistry::default())
.invoke_handler(tauri::generate_handler![
@@ -1899,6 +1968,10 @@ fn main() {
commands::open_logs_dir,
commands::open_models_dir,
commands::start_backend_update,
+ commands::start_staged_update,
+ commands::cancel_staged_update,
+ commands::staged_update_status,
+ commands::discard_staged_update,
commands::start_managed_repair,
commands::native_path_leases_usable,
commands::cancel_pending_elevation,
@@ -1907,6 +1980,9 @@ fn main() {
desktop_update_policy::check_desktop_manual_update,
desktop_update_policy::desktop_update_policy,
desktop_updater::check_desktop_update,
+ desktop_updater::download_desktop_update,
+ desktop_updater::install_desktop_update,
+ desktop_updater::desktop_update_bundle_status,
desktop_updater::desktop_update_cleanup_armed,
desktop_updater::resume_desktop_update_cleanup,
diagnostics::collect_support_diagnostics,
@@ -1953,6 +2029,15 @@ fn main() {
initialize_close_to_tray(app.handle());
reconcile_autostart_entry(app.handle());
+ if let Err(error) = process::with_studio_runtime_launch_guard(|| {
+ staged_update::reconcile_at_launch(
+ &diagnostics::studio_dir(),
+ &app.package_info().version.to_string(),
+ );
+ Ok(())
+ }) {
+ warn!("Staged update activation deferred: {error}");
+ }
// Recover legacy desktop installs before the first preflight.
if let Err(error) = desktop_backend_owner::ensure_installed_studio_root_id() {
warn!("Desktop backend ownership id unavailable: {error}");
@@ -2101,6 +2186,23 @@ mod tests {
assert!(!in_app_relaunch_marker_path(dir.path()).exists());
}
+ #[cfg(target_os = "macos")]
+ #[test]
+ fn staged_rollback_relaunch_helper_removes_its_private_arguments() {
+ let args = vec![
+ OsString::from(STAGED_ROLLBACK_RELAUNCH_FLAG),
+ OsString::from("123"),
+ OsString::from("--hidden"),
+ OsString::from("file.gguf"),
+ ];
+
+ let (parent, original) = staged_rollback_relaunch_args(&args).unwrap();
+
+ assert_eq!(parent, 123);
+ assert_eq!(original, &args[2..]);
+ assert!(staged_rollback_relaunch_args(&args[2..]).is_none());
+ }
+
#[test]
fn close_to_tray_preference_defaults_off_and_round_trips() {
let dir = tempfile::tempdir().unwrap();
diff --git a/studio/src-tauri/src/preflight.rs b/studio/src-tauri/src/preflight.rs
index c8dc2bd7427..13c3b223312 100644
--- a/studio/src-tauri/src/preflight.rs
+++ b/studio/src-tauri/src/preflight.rs
@@ -509,6 +509,7 @@ mod tests {
readiness: OwnedBackendReadiness::Stale {
reason: "backend_outdated".to_string(),
},
+ backend_version: None,
},
)
};
diff --git a/studio/src-tauri/src/preflight/pid_records.rs b/studio/src-tauri/src/preflight/pid_records.rs
index 8007a2c9a53..3f6f49d89fa 100644
--- a/studio/src-tauri/src/preflight/pid_records.rs
+++ b/studio/src-tauri/src/preflight/pid_records.rs
@@ -71,8 +71,8 @@ enum Recorded {
Opaque,
}
-/// The Python side uses the same one-second window in `_pid_is_studio_backend`.
-const START_TIME_TOLERANCE_SECS: f64 = 1.0;
+const START_TIME_TOLERANCE_SECS: f64 =
+ crate::process_identity::PID_START_TIME_TOLERANCE_SECS;
fn classify(pid: u32, recorded_start: Option<f64>, probe: &Probe) -> Recorded {
if !(probe.is_live)(pid) {
@@ -182,16 +182,8 @@ fn has_a_per_port_record(root: &Path, pid: u32) -> bool {
false
}
-/// Line two of a record, written by the server as `psutil` epoch seconds. A
-/// blank or absent line means the server could not determine it.
fn recorded_start_time(path: &Path) -> Option<f64> {
- std::fs::read_to_string(path)
- .ok()?
- .lines()
- .nth(1)?
- .trim()
- .parse()
- .ok()
+ crate::process_identity::recorded_pid_start_time(path)
}
#[cfg(test)]
diff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rs
index 0ae72d0554c..5694dda788a 100644
--- a/studio/src-tauri/src/process.rs
+++ b/studio/src-tauri/src/process.rs
@@ -340,8 +340,8 @@ mod appimage_environment_tests {
#[cfg(windows)]
const STUDIO_MANAGED_RUNTIME_MUTEX_PREFIX: &str = "Global\\UnslothStudioManagedEnvironment-";
-#[cfg(windows)]
pub(crate) const STUDIO_RUNTIME_GATE_HANDOFF_ENV: &str = "_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF";
+const STUDIO_RUNTIME_GATE_ACQUIRE_ENV: &str = "_UNSLOTH_STUDIO_RUNTIME_GATE_ACQUIRE";
#[cfg(windows)]
#[derive(Debug)]
@@ -359,6 +359,23 @@ impl Drop for StudioManagedRuntimeLaunchGuard {
}
}
+#[cfg(unix)]
+#[derive(Debug)]
+struct StudioManagedRuntimeLaunchGuard {
+ file: std::fs::File,
+}
+
+#[cfg(unix)]
+impl Drop for StudioManagedRuntimeLaunchGuard {
+ fn drop(&mut self) {
+ use std::os::fd::AsRawFd;
+
+ unsafe {
+ libc::flock(self.file.as_raw_fd(), libc::LOCK_UN);
+ }
+ }
+}
+
#[cfg(windows)]
fn acquire_named_studio_runtime_launch_guard(
name: &str,
@@ -496,11 +513,41 @@ fn acquire_studio_runtime_launch_guard() -> Result<StudioManagedRuntimeLaunchGua
acquire_named_studio_runtime_launch_guard(&name)
}
-/// Serialize creation of managed-environment children with install/repair.
-///
-/// The guard ends when the sync operation returns. The installer takes the same
-/// mutex then scans for managed processes, so holding it through child creation
-/// closes the race without carrying a thread-owned Win32 mutex across an await.
+#[cfg(unix)]
+fn acquire_file_studio_runtime_launch_guard(
+ home: &std::path::Path,
+) -> Result<StudioManagedRuntimeLaunchGuard, String> {
+ use std::os::fd::AsRawFd;
+
+ std::fs::create_dir_all(home)
+ .map_err(|error| format!("Could not create the Studio runtime lock directory: {error}"))?;
+ let path = home.join(".studio-runtime.lock");
+ let file = std::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .open(&path)
+ .map_err(|error| format!("Could not open the Studio runtime lock: {error}"))?;
+ let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
+ if result == 0 {
+ return Ok(StudioManagedRuntimeLaunchGuard { file });
+ }
+ let error = std::io::Error::last_os_error();
+ if error.kind() == std::io::ErrorKind::WouldBlock {
+ return Err(
+ "Unsloth installation is modifying the managed environment. Wait for it to finish, then start the backend again."
+ .to_string(),
+ );
+ }
+ Err(format!("Could not acquire the Studio runtime lock: {error}"))
+}
+
+#[cfg(unix)]
+fn acquire_studio_runtime_launch_guard() -> Result<StudioManagedRuntimeLaunchGuard, String> {
+ acquire_file_studio_runtime_launch_guard(&crate::diagnostics::studio_dir())
+}
+
+/// serialize managed-environment child creation with install and repair.
#[cfg(windows)]
fn with_named_studio_runtime_launch_guard<T>(
name: &str,
@@ -518,8 +565,38 @@ pub(crate) fn with_studio_runtime_launch_guard<T>(
let name = studio_runtime_mutex_name_for_sid(&current_windows_user_sid()?);
return with_named_studio_runtime_launch_guard(&name, operation);
}
- #[cfg(not(windows))]
- operation()
+ #[cfg(unix)]
+ {
+ let _runtime_launch_guard = acquire_studio_runtime_launch_guard()?;
+ return operation();
+ }
+ #[cfg(not(any(windows, unix)))]
+ {
+ operation()
+ }
+}
+
+#[cfg(all(test, unix))]
+mod posix_studio_runtime_launch_guard_tests {
+ use super::*;
+
+ #[test]
+ fn blocks_a_second_launcher_until_the_first_releases_the_file_lock() {
+ let home = tempfile::tempdir().unwrap();
+ let first = acquire_file_studio_runtime_launch_guard(home.path()).unwrap();
+ let path = home.path().to_path_buf();
+ let error = std::thread::spawn(move || {
+ acquire_file_studio_runtime_launch_guard(&path)
+ .err()
+ .expect("second launcher unexpectedly acquired the gate")
+ })
+ .join()
+ .unwrap();
+ assert!(error.contains("installation is modifying"));
+
+ drop(first);
+ acquire_file_studio_runtime_launch_guard(home.path()).unwrap();
+ }
}
#[cfg(windows)]
@@ -1343,7 +1420,9 @@ fn windows_site_packages_carries_the_cli(site_packages: &std::path::Path) -> boo
/// Returns the path to the unsloth binary inside the managed venv, if it exists.
/// Checks the new layout (~/.unsloth/studio/unsloth_studio/) first,
/// then falls back to the old layout (~/.unsloth/studio/.venv/) for compat.
-fn find_unsloth_binary_in_studio_dir(studio: &std::path::Path) -> Option<std::path::PathBuf> {
+pub(crate) fn find_unsloth_binary_in_studio_dir(
+ studio: &std::path::Path,
+) -> Option<std::path::PathBuf> {
// New layout (upstream scripts >= March 2026)
let new_base = studio.join("unsloth_studio");
// Old layout (bundled scripts, older upstream)
@@ -3120,7 +3199,6 @@ pub fn start_backend(
shutdown: &ShutdownFlag,
diagnostics_state: &DiagnosticsState,
) -> Result<u64, String> {
- #[cfg(windows)]
let _runtime_launch_guard = acquire_studio_runtime_launch_guard()?;
// A backend started while the job is disarmed is the orphan this guards
@@ -3234,8 +3312,8 @@ pub fn start_backend(
return Err(msg);
}
- #[cfg(windows)]
- cmd.env(STUDIO_RUNTIME_GATE_HANDOFF_ENV, "1");
+ cmd.env_remove(STUDIO_RUNTIME_GATE_HANDOFF_ENV);
+ cmd.env(STUDIO_RUNTIME_GATE_ACQUIRE_ENV, "1");
if let Some(native_state) = app.try_state::<crate::native_intents::NativeIntakeState>() {
cmd.env(
@@ -3383,6 +3461,7 @@ pub fn start_backend(
if let Some(stdout) = stdout {
let app_handle = app.clone();
let state_clone = Arc::clone(state);
+ let shutdown_clone = Arc::clone(shutdown);
let diagnostics_clone = diagnostics_state.clone();
let backend_log_clone = backend_log.clone();
std::thread::spawn(move || {
@@ -3390,6 +3469,7 @@ pub fn start_backend(
stdout,
&app_handle,
&state_clone,
+ &shutdown_clone,
&diagnostics_clone,
&backend_log_clone,
false,
@@ -3402,6 +3482,7 @@ pub fn start_backend(
if let Some(stderr) = stderr {
let app_handle = app.clone();
let state_clone = Arc::clone(state);
+ let shutdown_clone = Arc::clone(shutdown);
let diagnostics_clone = diagnostics_state.clone();
let backend_log_clone = backend_log.clone();
std::thread::spawn(move || {
@@ -3409,6 +3490,7 @@ pub fn start_backend(
stderr,
&app_handle,
&state_clone,
+ &shutdown_clone,
&diagnostics_clone,
&backend_log_clone,
true,
@@ -3421,6 +3503,40 @@ pub fn start_backend(
Ok(generation)
}
+pub(crate) fn request_staged_rollback_restart(app: &AppHandle, state: &BackendState) -> bool {
+ let home = diagnostics::studio_dir();
+ let recovered = match with_studio_runtime_launch_guard(|| {
+ if state
+ .lock()
+ .map(|process| process.has_owned_backend())
+ .unwrap_or(true)
+ {
+ return Ok(false);
+ }
+ crate::staged_update::recover_failed_activation(&home, || {})
+ }) {
+ Ok(recovered) => recovered,
+ Err(error) => {
+ error!("Staged backend rollback failed: {error}");
+ false
+ }
+ };
+ if !recovered {
+ return false;
+ }
+ #[cfg(target_os = "macos")]
+ match crate::schedule_staged_rollback_relaunch(app) {
+ Ok(()) => app.exit(0),
+ Err(error) => {
+ error!("Could not schedule staged rollback relaunch: {error}");
+ app.request_restart();
+ }
+ }
+ #[cfg(not(target_os = "macos"))]
+ app.request_restart();
+ true
+}
+
async fn generic_backend_health_ok(port: u16) -> bool {
let started = std::time::Instant::now();
let client = match crate::loopback_http::client(Duration::from_secs(2)) {
@@ -3512,9 +3628,57 @@ async fn generic_backend_health_ok(port: u16) -> bool {
const PORT_VALIDATION_RETRY_MIN: Duration = Duration::from_millis(250);
const PORT_VALIDATION_RETRY_MAX: Duration = Duration::from_secs(5);
+fn pending_backend_validation(
+ required: Option<&str>,
+ readiness: &crate::desktop_backend_owner::OwnedBackendReadiness,
+ observed: Option<&str>,
+ torch_warm_in_progress: bool,
+) -> (bool, bool) {
+ let Some(required) = required else {
+ return (true, false);
+ };
+ let accepted = !torch_warm_in_progress
+ && matches!(
+ readiness,
+ crate::desktop_backend_owner::OwnedBackendReadiness::Ready
+ )
+ && observed.is_some_and(|observed| {
+ crate::desktop_update_policy::compare_versions(observed, required) >= 0
+ });
+ (accepted, !accepted && !torch_warm_in_progress)
+}
+
+fn staged_probe_requires_immediate_rejection(reason: &str) -> bool {
+ matches!(
+ reason,
+ "desktop_protocol_incompatible"
+ | "desktop_auth_unsupported"
+ | "desktop_manageability_unsupported"
+ | "desktop_backend_ownership_unsupported"
+ | "desktop_auth_secret_missing"
+ | "desktop_auth_secret_rejected"
+ | "desktop_auth_token_rejected"
+ | "desktop_auth_token_response_invalid"
+ | "desktop_backend_version_invalid"
+ )
+}
+
+fn roll_back_rejected_staged_backend(
+ app: &AppHandle,
+ state: &BackendState,
+ shutdown: &ShutdownFlag,
+ diagnostics_state: &DiagnosticsState,
+) {
+ let stopped = stop_backend(state, shutdown, Some(diagnostics_state));
+ if stopped.is_err() || !request_staged_rollback_restart(app, state) {
+ let _ = app.emit("server-crashed", ());
+ }
+}
+
async fn validate_candidate_port(
app: AppHandle,
state: BackendState,
+ shutdown: ShutdownFlag,
diagnostics_state: DiagnosticsState,
session_id: String,
generation: u64,
@@ -3522,6 +3686,10 @@ async fn validate_candidate_port(
deadline: std::time::Instant,
) {
let started = std::time::Instant::now();
+ let pending = crate::staged_update::pending_versions(&diagnostics::studio_dir());
+ let pending_backend_version = pending
+ .as_ref()
+ .map(|versions| versions.backend_version.as_str());
let owner = {
let proc = match state.lock() {
Ok(proc) => proc,
@@ -3549,6 +3717,7 @@ async fn validate_candidate_port(
let mut delay = PORT_VALIDATION_RETRY_MIN;
let mut attempts = 0u32;
let mut verified_late = false;
+ let mut validated_backend_version = None;
let valid = loop {
// Before the probe, not just after a failed one: the announcement
// itself can arrive past the deadline on a very slow start, and the
@@ -3557,17 +3726,62 @@ async fn validate_candidate_port(
break false;
}
attempts += 1;
- let ok = if let Some(owner) = owner.clone() {
- matches!(
- crate::desktop_backend_owner::probe_owned_backend_state(owner, Some(port), false)
+ let (ok, reject_staged) = if let Some(owner) = owner.clone() {
+ let (probe, torch_warm_in_progress) = if pending_backend_version.is_some() {
+ crate::desktop_backend_owner::probe_owned_backend_state_for_staged_activation(
+ owner,
+ Some(port),
+ )
+ .await
+ } else {
+ (
+ crate::desktop_backend_owner::probe_owned_backend_state(
+ owner,
+ Some(port),
+ false,
+ )
.await,
+ false,
+ )
+ };
+ match probe {
crate::desktop_backend_owner::OwnedBackendProbe::Verified(
- crate::desktop_backend_owner::VerifiedOwnedBackend { port: verified_port, .. }
- ) if verified_port == port
- )
+ crate::desktop_backend_owner::VerifiedOwnedBackend {
+ port: verified_port,
+ readiness,
+ backend_version,
+ ..
+ },
+ ) => {
+ let owned_port = verified_port == port;
+ let (version_matches, reject_version) = pending_backend_validation(
+ pending_backend_version,
+ &readiness,
+ backend_version.as_deref(),
+ torch_warm_in_progress,
+ );
+ if owned_port && version_matches {
+ validated_backend_version = backend_version;
+ }
+ (owned_port && version_matches, owned_port && reject_version)
+ }
+ crate::desktop_backend_owner::OwnedBackendProbe::Unmanageable {
+ reason, ..
+ } if pending_backend_version.is_some() => {
+ (false, staged_probe_requires_immediate_rejection(&reason))
+ }
+ _ => (false, false),
+ }
+ } else if pending_backend_version.is_some() {
+ (false, true)
} else {
- generic_backend_health_ok(port).await
+ (generic_backend_health_ok(port).await, false)
};
+ if reject_staged {
+ warn!("Staged backend failed authenticated version validation");
+ roll_back_rejected_staged_backend(&app, &state, &shutdown, &diagnostics_state);
+ return;
+ }
if ok {
// A probe that started in time can still finish late. Emitting
// server-port after the watchdog's server-start-timeout strands the
@@ -3597,6 +3811,14 @@ async fn validate_candidate_port(
};
if !valid {
+ if pending_backend_version.is_some()
+ && crate::staged_update::pending_versions(&diagnostics::studio_dir()).is_some()
+ && std::time::Instant::now() >= deadline
+ {
+ warn!("Staged backend validation timed out");
+ roll_back_rejected_staged_backend(&app, &state, &shutdown, &diagnostics_state);
+ return;
+ }
if verified_late {
warn!(
"Backend port {} verified after the start deadline; not emitting",
@@ -3639,6 +3861,23 @@ async fn validate_candidate_port(
}
};
+ let activation_confirmed = if should_emit && pending_backend_version.is_some() {
+ validated_backend_version.as_deref().is_some_and(|version| {
+ crate::staged_update::confirm_activated(&diagnostics::studio_dir(), version)
+ })
+ } else {
+ true
+ };
+ if should_emit && !activation_confirmed {
+ if let Ok(mut proc) = state.lock() {
+ if proc.generation == generation && proc.port == Some(port) {
+ proc.port = None;
+ }
+ }
+ warn!("Staged backend confirmation changed during validation");
+ return;
+ }
+
info!(
"Validated backend port candidate {} valid={} emit={} in {}ms",
port,
@@ -3761,6 +4000,7 @@ fn read_output_stream<R: std::io::Read>(
stream: R,
app: &AppHandle,
state: &BackendState,
+ shutdown: &ShutdownFlag,
diagnostics_state: &DiagnosticsState,
backend_log: &BackendLog,
is_stderr: bool,
@@ -3831,12 +4071,14 @@ fn read_output_stream<R: std::io::Read>(
if let Some(port) = candidate_port {
let app_handle = app.clone();
let state_clone = Arc::clone(state);
+ let shutdown_clone = Arc::clone(shutdown);
let diagnostics_clone = diagnostics_state.clone();
let session_id = backend_log.session_id.clone();
tauri::async_runtime::spawn(async move {
validate_candidate_port(
app_handle,
state_clone,
+ shutdown_clone,
diagnostics_clone,
session_id,
generation,
@@ -3958,6 +4200,9 @@ fn read_output_stream<R: std::io::Read>(
);
}
if emit_crash {
+ if request_staged_rollback_restart(app, state) {
+ return;
+ }
error!("Backend process stdout closed unexpectedly (crash detected)");
let _ = app.emit("server-crashed", ());
}
@@ -5878,6 +6123,99 @@ mod managed_cli_working_dir_tests {
);
}
+ #[test]
+ fn pending_activation_requires_a_ready_backend_at_or_above_the_required_version() {
+ use crate::desktop_backend_owner::OwnedBackendReadiness;
+
+ assert_eq!(
+ pending_backend_validation(None, &OwnedBackendReadiness::Ready, None, false),
+ (true, false)
+ );
+ assert_eq!(
+ pending_backend_validation(
+ Some("2026.9.1"),
+ &OwnedBackendReadiness::Ready,
+ Some("2026.9.1"),
+ false
+ ),
+ (true, false)
+ );
+ assert_eq!(
+ pending_backend_validation(
+ Some("2026.9.1"),
+ &OwnedBackendReadiness::Ready,
+ Some("2026.8.4"),
+ false
+ ),
+ (false, true)
+ );
+ assert_eq!(
+ pending_backend_validation(
+ Some("2026.9.1"),
+ &OwnedBackendReadiness::Ready,
+ Some("2026.9.2"),
+ false
+ ),
+ (true, false)
+ );
+ assert_eq!(
+ pending_backend_validation(
+ Some("2026.9.1"),
+ &OwnedBackendReadiness::Stale {
+ reason: "desktop_backend_version_too_old".to_string()
+ },
+ Some("2026.9.1"),
+ false
+ ),
+ (false, true)
+ );
+ }
+
+ #[test]
+ fn pending_activation_waits_for_authenticated_backend_warmup() {
+ use crate::desktop_backend_owner::OwnedBackendReadiness;
+
+ assert_eq!(
+ pending_backend_validation(
+ Some("2026.9.1"),
+ &OwnedBackendReadiness::Ready,
+ Some("2026.9.1"),
+ true
+ ),
+ (false, false)
+ );
+ }
+
+ #[test]
+ fn pending_activation_retries_transient_authenticated_probe_failures() {
+ for reason in [
+ "desktop_login_probe_failed",
+ "desktop_auth_secret_probe_failed",
+ "desktop_auth_secret_probe_http_500 Internal Server Error",
+ "desktop_auth_health_unverified",
+ "error sending request for url",
+ ] {
+ assert!(!staged_probe_requires_immediate_rejection(reason));
+ }
+ }
+
+ #[test]
+ fn pending_activation_rejects_completed_incompatibility_evidence() {
+ for reason in [
+ "desktop_protocol_incompatible",
+ "desktop_auth_unsupported",
+ "desktop_manageability_unsupported",
+ "desktop_backend_ownership_unsupported",
+ "desktop_auth_secret_missing",
+ "desktop_auth_secret_rejected",
+ "desktop_auth_token_rejected",
+ "desktop_auth_token_response_invalid",
+ "desktop_backend_version_invalid",
+ ] {
+ assert!(staged_probe_requires_immediate_rejection(reason));
+ }
+ }
+
// The platform the bug was reported on, on the Windows leg of studio-tauri-smoke:
// a child must observe the chosen directory rather than the launcher's.
#[cfg(windows)]
diff --git a/studio/src-tauri/src/process_identity.rs b/studio/src-tauri/src/process_identity.rs
index d821e511732..3d179bf4282 100644
--- a/studio/src-tauri/src/process_identity.rs
+++ b/studio/src-tauri/src/process_identity.rs
@@ -350,6 +350,33 @@ pub(crate) fn process_start_time_secs(pid: u32) -> Option<f64> {
process_start_time_impl(pid)
}
+/// The Python side uses the same one-second window in `_pid_is_studio_backend`.
+pub(crate) const PID_START_TIME_TOLERANCE_SECS: f64 = 1.0;
+
+/// Line two of a `studio-{port}-{pid}.pid` record, written by the server as
+/// `psutil` epoch seconds. A blank or absent line means it could not say.
+pub(crate) fn recorded_pid_start_time(path: &Path) -> Option<f64> {
+ std::fs::read_to_string(path)
+ .ok()?
+ .lines()
+ .nth(1)?
+ .trim()
+ .parse()
+ .ok()
+}
+
+/// Whether the process wearing `pid` is the one the record described.
+///
+/// A recorded start time that disagrees is proof the pid was reused, which no
+/// amount of executable evidence can override. Records outlive crashes, so
+/// without this an unrelated process inheriting the pid reads as ours.
+pub(crate) fn pid_start_time_matches(pid: u32, recorded: Option<f64>) -> bool {
+ let (Some(recorded), Some(actual)) = (recorded, process_start_time_secs(pid)) else {
+ return true;
+ };
+ (actual - recorded).abs() <= PID_START_TIME_TOLERANCE_SECS
+}
+
#[cfg(target_os = "linux")]
fn process_start_time_impl(pid: u32) -> Option<f64> {
// Field 22 of /proc/{pid}/stat, in clock ticks since boot. Parsed from the
diff --git a/studio/src-tauri/src/staged_update.rs b/studio/src-tauri/src/staged_update.rs
new file mode 100644
index 00000000000..91e3338f8be
--- /dev/null
+++ b/studio/src-tauri/src/staged_update.rs
@@ -0,0 +1,1216 @@
+use crate::process_identity::ProcessOrigin;
+use log::{info, warn};
+use serde::{Deserialize, Serialize};
+use std::cmp::Ordering;
+use std::fs::{self, File};
+use std::io::Write;
+use std::path::{Path, PathBuf};
+
+pub(crate) const STAGE_DIR: &str = ".update-stage";
+const PREV_DIR: &str = ".update-prev";
+const FAILED_MARKER: &str = ".update-failed.json";
+const READY_MARKER: &str = "READY.json";
+const PENDING_MARKER: &str = "PENDING.json";
+const CONFIRMED_MARKER: &str = "CONFIRMED.json";
+const ROLLED_BACK_MARKER: &str = "ROLLED_BACK.json";
+const ROLLBACK_TRASH_PREFIX: &str = ".update-rollback-";
+const RUNTIME_ENTRIES: [&str; 4] = [
+ "unsloth_studio",
+ ".venv_t5_530",
+ ".venv_t5_550",
+ ".venv_t5_510",
+];
+const HELPER_RUNTIME_ENTRIES: [&str; 3] = ["node", "llama.cpp", "whisper.cpp"];
+
+fn all_runtime_entries() -> impl Iterator<Item = &'static str> {
+ RUNTIME_ENTRIES.into_iter().chain(HELPER_RUNTIME_ENTRIES)
+}
+
+fn live_entry(home: &Path, name: &str) -> PathBuf {
+ if HELPER_RUNTIME_ENTRIES.contains(&name) {
+ home.parent().unwrap_or(home).join(name)
+ } else {
+ home.join(name)
+ }
+}
+
+#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
+pub(crate) struct StagedVersions {
+ pub backend_version: String,
+ #[serde(default)]
+ pub shell_version: Option<String>,
+}
+
+#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
+struct ActivationJournal {
+ #[serde(flatten)]
+ versions: StagedVersions,
+ #[serde(default)]
+ previous_entries: Vec<String>,
+}
+
+#[derive(Clone, Debug, Serialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub(crate) struct StagedUpdateStatus {
+ pub state: &'static str,
+ pub backend_version: Option<String>,
+ pub shell_version: Option<String>,
+ /// A staged child is running now, so a partial stage is being written rather
+ /// than left over.
+ pub staging: bool,
+ pub staging_shell_version: Option<String>,
+}
+
+impl StagedUpdateStatus {
+ fn with(state: &'static str, versions: Option<StagedVersions>) -> Self {
+ Self {
+ state,
+ backend_version: versions.as_ref().map(|v| v.backend_version.clone()),
+ shell_version: versions.and_then(|v| v.shell_version),
+ staging: false,
+ staging_shell_version: None,
+ }
+ }
+}
+
+fn read_versions(path: &Path) -> Option<StagedVersions> {
+ serde_json::from_str(&fs::read_to_string(path).ok()?).ok()
+}
+
+fn write_versions(path: &Path, versions: &StagedVersions) -> Result<(), String> {
+ let body = serde_json::to_vec_pretty(versions).map_err(|e| e.to_string())?;
+ write_atomic(path, &body)
+}
+
+fn read_journal(path: &Path) -> Option<ActivationJournal> {
+ serde_json::from_str(&fs::read_to_string(path).ok()?).ok()
+}
+
+pub(crate) fn pending_versions(home: &Path) -> Option<StagedVersions> {
+ read_journal(&home.join(PREV_DIR).join(PENDING_MARKER)).map(|journal| journal.versions)
+}
+
+fn write_journal(path: &Path, journal: &ActivationJournal) -> Result<(), String> {
+ let body = serde_json::to_vec_pretty(journal).map_err(|e| e.to_string())?;
+ write_atomic(path, &body)
+}
+
+fn write_atomic(path: &Path, body: &[u8]) -> Result<(), String> {
+ let parent = path
+ .parent()
+ .ok_or_else(|| format!("{} has no parent", path.display()))?;
+ fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
+ let mut temporary = tempfile::Builder::new()
+ .prefix(".update-marker-")
+ .tempfile_in(parent)
+ .map_err(|e| format!("{}: {e}", parent.display()))?;
+ temporary
+ .write_all(body)
+ .and_then(|()| temporary.as_file().sync_all())
+ .map_err(|e| format!("{}: {e}", path.display()))?;
+ temporary
+ .persist(path)
+ .map_err(|e| format!("{}: {}", path.display(), e.error))?;
+ #[cfg(unix)]
+ let _ = File::open(parent).and_then(|directory| directory.sync_all());
+ Ok(())
+}
+
+pub(crate) fn status(home: &Path) -> StagedUpdateStatus {
+ let stage = home.join(STAGE_DIR);
+ if let Some(versions) = read_versions(&stage.join(READY_MARKER)) {
+ return StagedUpdateStatus::with("ready", Some(versions));
+ }
+ if stage.is_dir() {
+ return StagedUpdateStatus::with("partial", None);
+ }
+ if let Some(versions) = read_versions(&home.join(FAILED_MARKER)) {
+ return StagedUpdateStatus::with("failed", Some(versions));
+ }
+ StagedUpdateStatus::with("none", None)
+}
+
+pub(crate) fn discard(home: &Path) {
+ let _ = fs::remove_dir_all(home.join(STAGE_DIR));
+}
+
+pub(crate) fn reconcile_at_launch(home: &Path, shell_version: &str) {
+ remove_stale_trash(home);
+ if let Err(error) = roll_back_unconfirmed(home) {
+ // Activating now would delete .update-prev, and a rollback that failed part
+ // way may have left the unconfirmed runtime live: the next candidate would
+ // then be recorded against it with the last known-good copy already gone.
+ warn!("[staged-update] rollback failed, not activating: {error}");
+ return;
+ }
+ if let Err(error) = activate_ready(home, shell_version) {
+ warn!("[staged-update] activation failed: {error}");
+ }
+}
+
+fn remove_stale_trash(home: &Path) {
+ let Ok(entries) = fs::read_dir(home) else {
+ return;
+ };
+ let stale: Vec<PathBuf> = entries
+ .flatten()
+ .map(|entry| entry.path())
+ .filter(|path| {
+ path.file_name()
+ .and_then(|name| name.to_str())
+ .is_some_and(|name| name.starts_with(ROLLBACK_TRASH_PREFIX))
+ })
+ .collect();
+ if stale.is_empty() {
+ return;
+ }
+ std::thread::spawn(move || {
+ for path in stale {
+ let _ = fs::remove_dir_all(path);
+ }
+ });
+}
+
+pub(crate) fn confirm_activated(home: &Path, observed_backend_version: &str) -> bool {
+ let prev = home.join(PREV_DIR);
+ let Some(versions) = read_versions(&prev.join(PENDING_MARKER)) else {
+ return false;
+ };
+ if crate::desktop_update_policy::compare_versions(
+ observed_backend_version,
+ &versions.backend_version,
+ ) < 0
+ {
+ warn!(
+ "[staged-update] backend {} is older than staged runtime {}",
+ observed_backend_version, versions.backend_version
+ );
+ return false;
+ }
+ if let Err(error) = write_versions(&prev.join(CONFIRMED_MARKER), &versions) {
+ warn!("[staged-update] could not confirm activated runtime: {error}");
+ return false;
+ }
+ info!("[staged-update] backend healthy, dropping previous runtime");
+ std::thread::spawn(move || {
+ remove_confirmed_previous(&prev);
+ });
+ true
+}
+
+fn remove_confirmed_previous(prev: &Path) {
+ if let Ok(entries) = fs::read_dir(prev) {
+ for entry in entries.flatten() {
+ if entry.file_name() == CONFIRMED_MARKER {
+ continue;
+ }
+ let path = entry.path();
+ if path.is_dir() {
+ let _ = fs::remove_dir_all(path);
+ } else {
+ let _ = fs::remove_file(path);
+ }
+ }
+ }
+ let _ = fs::remove_file(prev.join(CONFIRMED_MARKER));
+ let _ = fs::remove_dir(prev);
+}
+
+fn roll_back_unconfirmed(home: &Path) -> Result<(), String> {
+ roll_back_unconfirmed_with(home, live_tree_in_use(home))
+}
+
+pub(crate) fn roll_back_failed_activation(
+ home: &Path,
+) -> Result<Option<StagedVersions>, String> {
+ let versions = pending_versions(home);
+ if versions.is_none() || live_tree_in_use(home) {
+ return Ok(None);
+ }
+ roll_back_unconfirmed_with(home, false)?;
+ Ok(versions)
+}
+
+pub(crate) fn recover_failed_activation(
+ home: &Path,
+ restart: impl FnOnce(),
+) -> Result<bool, String> {
+ if roll_back_failed_activation(home)?.is_none() {
+ return Ok(false);
+ }
+ restart();
+ Ok(true)
+}
+
+fn roll_back_unconfirmed_with(home: &Path, in_use: bool) -> Result<(), String> {
+ let prev = home.join(PREV_DIR);
+ if prev.join(CONFIRMED_MARKER).is_file() {
+ remove_confirmed_previous(&prev);
+ return Ok(());
+ }
+ let rolled_back = prev.join(ROLLED_BACK_MARKER);
+ if rolled_back.is_file() {
+ if let Some(versions) = read_versions(&rolled_back) {
+ let failed = home.join(FAILED_MARKER);
+ if !failed.is_file() {
+ write_versions(&failed, &versions)?;
+ }
+ }
+ let _ = fs::remove_dir_all(home.join(STAGE_DIR));
+ let _ = fs::remove_dir_all(&prev);
+ return Ok(());
+ }
+ let journal = read_journal(&prev.join(PENDING_MARKER));
+ let versions = journal.as_ref().map(|journal| journal.versions.clone());
+ let has_previous_runtime = all_runtime_entries().any(|name| prev.join(name).exists());
+ if versions.is_none() && !has_previous_runtime {
+ if prev.is_dir() {
+ let _ = fs::remove_dir_all(&prev);
+ }
+ return Ok(());
+ }
+ if in_use {
+ // Renaming the tree under a live process is unsafe, but a process that never
+ // reached validate_candidate_port is not healthy either. Confirming here
+ // would drop the only way back. Leave the marker: validate_candidate_port
+ // still confirms on a healthy port, and a later launch can still roll back.
+ info!("[staged-update] runtime still in use, deferring the rollback decision");
+ return Ok(());
+ }
+ let versions = versions.or_else(|| read_versions(&home.join(STAGE_DIR).join(READY_MARKER)));
+ let previous_entries = journal
+ .map(|journal| journal.previous_entries)
+ .filter(|entries| !entries.is_empty())
+ .unwrap_or_else(|| {
+ all_runtime_entries()
+ .filter(|name| prev.join(name).exists())
+ .map(str::to_string)
+ .collect()
+ });
+ info!("[staged-update] staged backend never became healthy, restoring previous runtime");
+ let trash = restore_previous_runtime(home, &prev, &previous_entries)?;
+ if let Some(versions) = versions.as_ref() {
+ let failed = home.join(FAILED_MARKER);
+ let _ = fs::remove_file(&failed);
+ write_versions(&failed, versions)?;
+ write_versions(&prev.join(ROLLED_BACK_MARKER), versions)?;
+ }
+ let _ = fs::remove_dir_all(home.join(STAGE_DIR));
+ let _ = fs::remove_dir_all(&prev);
+ std::thread::spawn(move || {
+ let _ = fs::remove_dir_all(trash);
+ });
+ Ok(())
+}
+
+#[cfg(unix)]
+fn finalize_stage_for_activation(stage: &Path) -> Result<(), String> {
+ let python = stage.join("unsloth_studio").join("bin").join("python");
+ let code = concat!(
+ "import sys; from pathlib import Path; ",
+ "from unsloth_cli._studio_stage import finalize_for_activation; ",
+ "finalize_for_activation(Path(sys.argv[1]))"
+ );
+ let output = std::process::Command::new(&python)
+ .args(["-I", "-c", code])
+ .arg(stage)
+ .current_dir(stage)
+ .env_remove("PYTHONHOME")
+ .env_remove("PYTHONPATH")
+ .env_remove("VIRTUAL_ENV")
+ .output()
+ .map_err(|error| format!("{}: {error}", python.display()))?;
+ if output.status.success() {
+ return Ok(());
+ }
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ Err(format!(
+ "{} exited with {}: {}",
+ python.display(),
+ output.status,
+ stderr.trim()
+ ))
+}
+
+#[cfg(windows)]
+fn finalize_stage_for_activation(_stage: &Path) -> Result<(), String> {
+ Ok(())
+}
+
+fn activate_ready(home: &Path, shell_version: &str) -> Result<(), String> {
+ let stage = home.join(STAGE_DIR);
+ if !stage.is_dir() {
+ return Ok(());
+ }
+ let Some(versions) = read_versions(&stage.join(READY_MARKER)) else {
+ info!("[staged-update] removing incomplete stage");
+ let _ = fs::remove_dir_all(&stage);
+ return Ok(());
+ };
+ if let Some(required) = versions.shell_version.as_deref() {
+ match shell_order(shell_version, required) {
+ Ordering::Less => {
+ info!("[staged-update] staged backend waits for app {required}");
+ return Ok(());
+ }
+ Ordering::Greater => {
+ info!("[staged-update] staged backend was built for app {required}, discarding");
+ let _ = fs::remove_dir_all(&stage);
+ return Ok(());
+ }
+ Ordering::Equal => {}
+ }
+ }
+ if live_tree_in_use(home) {
+ info!("[staged-update] runtime in use, keeping staged backend for the next launch");
+ return Ok(());
+ }
+ if let Err(error) = finalize_stage_for_activation(&stage) {
+ let failed = home.join(FAILED_MARKER);
+ let _ = fs::remove_file(&failed);
+ write_versions(&failed, &versions)?;
+ let _ = fs::remove_dir_all(&stage);
+ return Err(format!("staged runtime finalization failed: {error}"));
+ }
+ let prev = home.join(PREV_DIR);
+ let _ = fs::remove_dir_all(&prev);
+ fs::create_dir_all(&prev).map_err(|e| e.to_string())?;
+ let journal = ActivationJournal {
+ versions: versions.clone(),
+ previous_entries: all_runtime_entries()
+ .filter(|name| live_entry(home, name).exists())
+ .map(str::to_string)
+ .collect(),
+ };
+ write_journal(&prev.join(PENDING_MARKER), &journal)?;
+ if let Err(error) = swap_entries(home, &stage, &prev, false) {
+ let rollback = restore_previous_runtime(home, &prev, &journal.previous_entries);
+ if rollback.is_ok() {
+ let _ = fs::remove_file(prev.join(PENDING_MARKER));
+ let _ = fs::remove_dir_all(&prev);
+ }
+ return Err(match rollback {
+ Ok(trash) => {
+ let _ = fs::remove_dir_all(trash);
+ error
+ }
+ Err(rollback_error) => format!("{error}; rollback failed: {rollback_error}"),
+ });
+ }
+ let _ = fs::remove_file(home.join(FAILED_MARKER));
+ let _ = fs::remove_dir_all(&stage);
+ info!(
+ "[staged-update] activated backend {}",
+ versions.backend_version
+ );
+ Ok(())
+}
+
+/// A stage is only useful if it actually advanced to what this shell expects.
+///
+/// `unsloth studio update` upgrades best effort: against a stale mirror or an
+/// unreachable index it can succeed from cache without moving the cloned package,
+/// and the marker would then advertise a backend older than the shell needs. The
+/// restart would activate it and drop straight into preflight repair, or fail to
+/// start and roll back, instead of the fast update the pill promised.
+pub(crate) fn staged_backend_meets(home: &Path, required: &str) -> Result<(), String> {
+ let Some(actual) = status(home).backend_version else {
+ return Err("the staged update recorded no backend version".to_string());
+ };
+ if crate::desktop_update_policy::compare_versions(&actual, required) < 0 {
+ return Err(format!(
+ "staged backend {actual} is older than the {required} this app needs; \
+ the package index may be stale or unreachable"
+ ));
+ }
+ Ok(())
+}
+
+fn shell_order(current: &str, required: &str) -> Ordering {
+ match crate::desktop_update_policy::compare_versions(current, required) {
+ 1 => Ordering::Greater,
+ -1 => Ordering::Less,
+ _ => Ordering::Equal,
+ }
+}
+
+fn restore_previous_runtime(
+ home: &Path,
+ previous: &Path,
+ previous_entries: &[String],
+) -> Result<PathBuf, String> {
+ let stage = home.join(STAGE_DIR);
+ let suffix = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_nanos();
+ let trash = home.join(format!(
+ "{ROLLBACK_TRASH_PREFIX}{}-{suffix}",
+ std::process::id()
+ ));
+ fs::create_dir_all(&trash).map_err(|e| e.to_string())?;
+ let mut moved: Vec<(PathBuf, PathBuf)> = Vec::new();
+ let result = (|| {
+ for name in all_runtime_entries() {
+ let old = previous.join(name);
+ let staged = stage.join(name);
+ let live = live_entry(home, name);
+ if previous_entries.iter().any(|entry| entry == name) {
+ if old.exists() {
+ if live.exists() {
+ rename_tracked(&live, &trash.join(name), &mut moved)?;
+ }
+ rename_tracked(&old, &live, &mut moved)?;
+ }
+ } else if !staged.exists() && live.exists() {
+ rename_tracked(&live, &trash.join(name), &mut moved)?;
+ }
+ }
+ Ok(())
+ })();
+ if result.is_err() {
+ for (from, to) in moved.iter().rev() {
+ let _ = fs::rename(to, from);
+ }
+ }
+ result.map(|()| trash)
+}
+
+/// `evict_extra` moves a live entry the incoming tree does not have out of the way
+/// instead of leaving it. Rollback needs it: a legacy install with no tiered
+/// sidecars has nothing to put in `.update-prev` for them, so without this the
+/// failed update's sidecars stay live beside the restored backend, which then
+/// imports from an environment that was never confirmed. Activation must not do
+/// it -- there the live tree is the one being preserved.
+fn swap_entries(
+ home: &Path,
+ incoming: &Path,
+ outgoing: &Path,
+ evict_extra: bool,
+) -> Result<(), String> {
+ let mut moved: Vec<(PathBuf, PathBuf)> = Vec::new();
+ let result = (|| {
+ for name in all_runtime_entries() {
+ let staged = incoming.join(name);
+ let live = live_entry(home, name);
+ if !staged.exists() {
+ if evict_extra && live.exists() {
+ rename_tracked(&live, &outgoing.join(name), &mut moved)?;
+ }
+ continue;
+ }
+ if live.exists() {
+ rename_tracked(&live, &outgoing.join(name), &mut moved)?;
+ }
+ rename_tracked(&staged, &live, &mut moved)?;
+ }
+ Ok(())
+ })();
+ if result.is_err() {
+ for (from, to) in moved.iter().rev() {
+ let _ = fs::rename(to, from);
+ }
+ }
+ result
+}
+
+fn rename_tracked(
+ from: &Path,
+ to: &Path,
+ moved: &mut Vec<(PathBuf, PathBuf)>,
+) -> Result<(), String> {
+ fs::rename(from, to)
+ .map_err(|e| format!("{} -> {}: {e}", from.display(), to.display()))?;
+ moved.push((from.to_path_buf(), to.to_path_buf()));
+ Ok(())
+}
+
+/// Pids that claim to be a backend of this install.
+///
+/// Mirrors `live_sibling_backend` in studio/backend/run.py, which reads all three
+/// record kinds because a backend can be in a state where only one exists: a
+/// startup marker while it is still binding, a per-port record once it has bound,
+/// and a bare `studio.pid` for a pre-upgrade server or one whose per-port write
+/// failed. Markers matter most here: the backend keeps its marker after dropping
+/// its pid records until shutdown really finishes, and renaming the tree during
+/// either window would move it under a process still importing out of it.
+fn recorded_pids(home: &Path) -> Vec<u32> {
+ let mut pids = Vec::new();
+ let mut timed = Vec::new();
+ if let Ok(entries) = fs::read_dir(home) {
+ for entry in entries.flatten() {
+ let name = entry.file_name();
+ let Some(name) = name.to_str() else {
+ continue;
+ };
+ // Markers use the same body layout as a per-port record, so both carry
+ // the start time that settles a reused pid.
+ let pid = name
+ .strip_suffix(".marker")
+ .and_then(|rest| rest.strip_prefix("studio-starting-"))
+ .or_else(|| {
+ name.strip_suffix(".pid")
+ .and_then(|rest| rest.strip_prefix("studio-"))
+ .and_then(|rest| rest.rsplit('-').next())
+ })
+ .and_then(|pid| pid.parse::<u32>().ok());
+ let Some(pid) = pid else {
+ continue;
+ };
+ // Judged either way, so the untimed legacy record below must not
+ // resurrect a pid this evidence already rejected.
+ timed.push(pid);
+ if crate::process_identity::pid_start_time_matches(
+ pid,
+ crate::process_identity::recorded_pid_start_time(&entry.path()),
+ ) {
+ pids.push(pid);
+ }
+ }
+ }
+ if let Ok(body) = fs::read_to_string(home.join("studio.pid")) {
+ if let Some(pid) = body.lines().next().and_then(|l| l.trim().parse::<u32>().ok()) {
+ // It carries no start time, so on its own it would re-add a pid the
+ // timed records just proved was reused.
+ if !timed.contains(&pid) {
+ pids.push(pid);
+ }
+ }
+ }
+ pids.retain(|pid| *pid > 1);
+ pids.sort_unstable();
+ pids.dedup();
+ pids
+}
+
+fn live_tree_in_use(home: &Path) -> bool {
+ #[cfg(windows)]
+ {
+ if let Some(bin) = crate::process::find_unsloth_binary_in_studio_dir(home) {
+ if crate::process::ensure_managed_environment_is_idle(&bin).is_err() {
+ return true;
+ }
+ }
+ }
+ let interpreters = crate::process_identity::interpreters_of(home);
+ recorded_pids(home).into_iter().any(|pid| {
+ crate::desktop_backend_owner::pid_is_not_dead(pid)
+ && !crate::process_identity::is_zombie(pid)
+ && crate::process_identity::origin_of(pid, home, &interpreters)
+ != ProcessOrigin::Elsewhere
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn temp_home(name: &str) -> PathBuf {
+ let dir = std::env::temp_dir().join(format!(
+ "unsloth-staged-update-{name}-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ /// Three code paths drop a tree on a background thread, and Windows refuses to
+ /// remove a directory while another handle is still walking inside it, so a
+ /// teardown that races one of them fails with ERROR_ACCESS_DENIED rather than
+ /// telling anyone anything. Retry until the deleter is done.
+ fn cleanup(home: PathBuf) {
+ for _ in 0..100 {
+ if fs::remove_dir_all(&home).is_ok() || !home.exists() {
+ return;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
+ fs::remove_dir_all(&home).unwrap();
+ }
+
+ fn make_runtime(root: &Path, tag: &str) {
+ for name in RUNTIME_ENTRIES {
+ fs::create_dir_all(root.join(name)).unwrap();
+ fs::write(root.join(name).join("tag"), tag).unwrap();
+ }
+ }
+
+ fn tag(root: &Path, name: &str) -> String {
+ fs::read_to_string(root.join(name).join("tag")).unwrap_or_default()
+ }
+
+ fn stage_ready(home: &Path, versions: &StagedVersions) {
+ let stage = home.join(STAGE_DIR);
+ make_runtime(&stage, "new");
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+
+ let python = stage.join("unsloth_studio").join("bin").join("python");
+ fs::create_dir_all(python.parent().unwrap()).unwrap();
+ fs::write(&python, "#!/bin/sh\nexit 0\n").unwrap();
+ let mut permissions = fs::metadata(&python).unwrap().permissions();
+ permissions.set_mode(0o755);
+ fs::set_permissions(&python, permissions).unwrap();
+ }
+ write_versions(&stage.join(READY_MARKER), versions).unwrap();
+ }
+
+ fn versions(shell: Option<&str>) -> StagedVersions {
+ StagedVersions {
+ backend_version: "2026.9.1".into(),
+ shell_version: shell.map(str::to_string),
+ }
+ }
+
+ #[test]
+ fn ready_stage_replaces_the_runtime_and_keeps_the_previous_one_pending() {
+ let home = temp_home("activate");
+ make_runtime(&home, "old");
+ stage_ready(&home, &versions(Some("0.1.900-beta")));
+
+ reconcile_at_launch(&home, "0.1.900-beta");
+
+ assert_eq!(tag(&home, "unsloth_studio"), "new");
+ assert_eq!(tag(&home.join(PREV_DIR), "unsloth_studio"), "old");
+ assert!(home.join(PREV_DIR).join(PENDING_MARKER).is_file());
+ assert_eq!(pending_versions(&home), Some(versions(Some("0.1.900-beta"))));
+ assert!(!home.join(STAGE_DIR).exists());
+ assert_eq!(status(&home).state, "none");
+ cleanup(home);
+ }
+
+ #[test]
+ fn stage_built_for_a_newer_shell_waits() {
+ let home = temp_home("wait");
+ make_runtime(&home, "old");
+ stage_ready(&home, &versions(Some("0.1.901-beta")));
+
+ reconcile_at_launch(&home, "0.1.900-beta");
+
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
+ assert_eq!(status(&home).state, "ready");
+ cleanup(home);
+ }
+
+ #[test]
+ fn stage_built_for_an_older_shell_is_discarded() {
+ let home = temp_home("discard");
+ make_runtime(&home, "old");
+ stage_ready(&home, &versions(Some("0.1.899-beta")));
+
+ reconcile_at_launch(&home, "0.1.900-beta");
+
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
+ assert!(!home.join(STAGE_DIR).exists());
+ cleanup(home);
+ }
+
+ #[test]
+ fn incomplete_stage_is_removed() {
+ let home = temp_home("partial");
+ make_runtime(&home, "old");
+ make_runtime(&home.join(STAGE_DIR), "half");
+ assert_eq!(status(&home).state, "partial");
+
+ reconcile_at_launch(&home, "0.1.900-beta");
+
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
+ assert!(!home.join(STAGE_DIR).exists());
+ cleanup(home);
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn a_stage_that_cannot_finalize_never_replaces_the_live_runtime() {
+ let home = temp_home("finalize-failure");
+ make_runtime(&home, "old");
+ stage_ready(&home, &versions(Some("0.1.900-beta")));
+ let python = home
+ .join(STAGE_DIR)
+ .join("unsloth_studio")
+ .join("bin")
+ .join("python");
+ fs::write(&python, "#!/bin/sh\nexit 42\n").unwrap();
+
+ reconcile_at_launch(&home, "0.1.900-beta");
+
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
+ assert!(!home.join(STAGE_DIR).exists());
+ assert_eq!(status(&home).state, "failed");
+ cleanup(home);
+ }
+
+ #[test]
+ fn unconfirmed_activation_rolls_back_and_records_the_failure() {
+ let home = temp_home("rollback");
+ make_runtime(&home, "old");
+ stage_ready(&home, &versions(None));
+ reconcile_at_launch(&home, "0.1.900-beta");
+ assert_eq!(tag(&home, "unsloth_studio"), "new");
+
+ reconcile_at_launch(&home, "0.1.900-beta");
+
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
+ assert_eq!(tag(&home, ".venv_t5_530"), "old");
+ assert!(!home.join(PREV_DIR).exists());
+ let failed = status(&home);
+ assert_eq!(failed.state, "failed");
+ assert_eq!(failed.backend_version.as_deref(), Some("2026.9.1"));
+ cleanup(home);
+ }
+
+ #[test]
+ fn failed_activation_rolls_back_once_without_waiting_for_an_app_relaunch() {
+ let home = temp_home("same-launch-rollback");
+ make_runtime(&home, "old");
+ stage_ready(&home, &versions(None));
+ activate_ready(&home, "0.1.900-beta").unwrap();
+
+ let restarts = std::cell::Cell::new(0);
+ assert!(recover_failed_activation(&home, || restarts.set(restarts.get() + 1)).unwrap());
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
+ assert!(home.join(FAILED_MARKER).is_file());
+ assert!(!recover_failed_activation(&home, || restarts.set(restarts.get() + 1)).unwrap());
+ assert_eq!(restarts.get(), 1);
+ cleanup(home);
+ }
+
+ #[test]
+ fn failed_activation_waits_until_the_live_runtime_is_unused() {
+ let home = temp_home("same-launch-live");
+ make_runtime(&home, "old");
+ stage_ready(&home, &versions(None));
+ activate_ready(&home, "0.1.900-beta").unwrap();
+ let me = std::process::id();
+ fs::write(
+ home.join(format!("studio-starting-{me}.marker")),
+ format!("{me}\n"),
+ )
+ .unwrap();
+
+ let restarts = std::cell::Cell::new(0);
+ assert!(!recover_failed_activation(&home, || restarts.set(1)).unwrap());
+ assert_eq!(tag(&home, "unsloth_studio"), "new");
+ assert!(home.join(PREV_DIR).join(PENDING_MARKER).is_file());
+ assert_eq!(restarts.get(), 0);
+ cleanup(home);
+ }
+
+ #[test]
+ fn confirmation_drops_the_previous_runtime_and_the_next_launch_keeps_the_new_one() {
+ let home = temp_home("confirm");
+ make_runtime(&home, "old");
+ stage_ready(&home, &versions(None));
+ reconcile_at_launch(&home, "0.1.900-beta");
+
+ assert!(confirm_activated(&home, "2026.9.1"));
+ for _ in 0..50 {
+ if !home.join(PREV_DIR).exists() {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
+ reconcile_at_launch(&home, "0.1.900-beta");
+
+ assert_eq!(tag(&home, "unsloth_studio"), "new");
+ assert_eq!(status(&home).state, "none");
+ cleanup(home);
+ }
+
+ #[test]
+ fn an_older_backend_cannot_confirm_a_newer_activation() {
+ let home = temp_home("confirm-version");
+ make_runtime(&home, "old");
+ stage_ready(&home, &versions(None));
+ activate_ready(&home, "0.1.900-beta").unwrap();
+
+ assert!(!confirm_activated(&home, "2026.8.4"));
+ assert!(home.join(PREV_DIR).join(PENDING_MARKER).is_file());
+ assert_eq!(tag(&home.join(PREV_DIR), "unsloth_studio"), "old");
+ assert!(confirm_activated(&home, "2026.9.2"));
+ for _ in 0..50 {
+ if !home.join(PREV_DIR).exists() {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
+ cleanup(home);
+ }
+
+ #[test]
+ fn every_interrupted_activation_boundary_restores_the_old_runtime() {
+ for completed_renames in 0..=RUNTIME_ENTRIES.len() * 2 {
+ let home = temp_home(&format!("crash-{completed_renames}"));
+ make_runtime(&home, "old");
+ stage_ready(&home, &versions(None));
+ let stage = home.join(STAGE_DIR);
+ let prev = home.join(PREV_DIR);
+ fs::create_dir_all(&prev).unwrap();
+ let journal = ActivationJournal {
+ versions: versions(None),
+ previous_entries: RUNTIME_ENTRIES.iter().map(|name| (*name).to_string()).collect(),
+ };
+ write_journal(&prev.join(PENDING_MARKER), &journal).unwrap();
+
+ let mut completed = 0;
+ for name in RUNTIME_ENTRIES {
+ if completed == completed_renames {
+ break;
+ }
+ fs::rename(home.join(name), prev.join(name)).unwrap();
+ completed += 1;
+ if completed == completed_renames {
+ break;
+ }
+ fs::rename(stage.join(name), home.join(name)).unwrap();
+ completed += 1;
+ }
+
+ roll_back_unconfirmed_with(&home, false).unwrap();
+
+ for name in RUNTIME_ENTRIES {
+ assert_eq!(tag(&home, name), "old", "boundary {completed_renames}: {name}");
+ }
+ assert!(!prev.exists());
+ cleanup(home);
+ }
+ }
+
+ #[test]
+ fn repeating_an_interrupted_rollback_keeps_the_restored_runtime() {
+ let home = temp_home("rollback-retry");
+ make_runtime(&home, "old");
+ stage_ready(&home, &versions(None));
+ let stage = home.join(STAGE_DIR);
+ let prev = home.join(PREV_DIR);
+ fs::create_dir_all(&prev).unwrap();
+ let previous_entries: Vec<String> =
+ RUNTIME_ENTRIES.iter().map(|name| (*name).to_string()).collect();
+ write_journal(
+ &prev.join(PENDING_MARKER),
+ &ActivationJournal {
+ versions: versions(None),
+ previous_entries: previous_entries.clone(),
+ },
+ )
+ .unwrap();
+ swap_entries(&home, &stage, &prev, false).unwrap();
+
+ let first_trash = restore_previous_runtime(&home, &prev, &previous_entries).unwrap();
+ let second_trash = restore_previous_runtime(&home, &prev, &previous_entries).unwrap();
+
+ for name in RUNTIME_ENTRIES {
+ assert_eq!(tag(&home, name), "old", "{name}");
+ }
+ cleanup(first_trash);
+ cleanup(second_trash);
+ cleanup(home);
+ }
+
+ #[test]
+ fn an_interrupted_rollback_marker_recreates_the_failed_version() {
+ let home = temp_home("rollback-marker-recovery");
+ make_runtime(&home, "old");
+ let stage = home.join(STAGE_DIR);
+ make_runtime(&stage, "bad");
+ let prev = home.join(PREV_DIR);
+ fs::create_dir_all(&prev).unwrap();
+ write_versions(&prev.join(ROLLED_BACK_MARKER), &versions(None)).unwrap();
+
+ roll_back_unconfirmed_with(&home, false).unwrap();
+
+ assert_eq!(read_versions(&home.join(FAILED_MARKER)), Some(versions(None)));
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
+ assert!(!stage.exists());
+ assert!(!prev.exists());
+ cleanup(home);
+ }
+
+ #[test]
+ fn a_durable_confirmation_never_rolls_back_the_new_runtime() {
+ let home = temp_home("confirmed-crash");
+ make_runtime(&home, "old");
+ stage_ready(&home, &versions(None));
+ activate_ready(&home, "0.1.900-beta").unwrap();
+ let prev = home.join(PREV_DIR);
+ write_versions(&prev.join(CONFIRMED_MARKER), &versions(None)).unwrap();
+
+ roll_back_unconfirmed_with(&home, false).unwrap();
+
+ assert_eq!(tag(&home, "unsloth_studio"), "new");
+ assert!(!prev.exists());
+ cleanup(home);
+ }
+
+ #[test]
+ fn a_failed_swap_restores_every_entry_it_moved() {
+ let home = temp_home("swap-fail");
+ make_runtime(&home, "old");
+ let stage = home.join(STAGE_DIR);
+ make_runtime(&stage, "new");
+ let prev = home.join(PREV_DIR);
+ let blocker = prev.join(".venv_t5_510");
+ fs::create_dir_all(&blocker).unwrap();
+ fs::write(blocker.join("occupied"), "").unwrap();
+
+ let result = swap_entries(&home, &stage, &prev, false);
+
+ assert!(result.is_err());
+ for name in RUNTIME_ENTRIES {
+ assert_eq!(tag(&home, name), "old", "{name}");
+ assert!(!prev.join(name).join("tag").exists(), "{name}");
+ }
+ assert_eq!(tag(&stage, "unsloth_studio"), "new");
+ cleanup(home);
+ }
+
+ #[test]
+ fn swapping_back_restores_the_runtime_the_activation_replaced() {
+ let home = temp_home("swap-back");
+ make_runtime(&home, "old");
+ let stage = home.join(STAGE_DIR);
+ make_runtime(&stage, "new");
+ let prev = home.join(PREV_DIR);
+ fs::create_dir_all(&prev).unwrap();
+
+ swap_entries(&home, &stage, &prev, false).unwrap();
+ assert_eq!(tag(&home, "unsloth_studio"), "new");
+ // What the failed-marker branch runs: the previous runtime goes back and the
+ // staged one returns to the stage, so the next launch can try it again.
+ swap_entries(&home, &prev, &stage, false).unwrap();
+
+ for name in RUNTIME_ENTRIES {
+ assert_eq!(tag(&home, name), "old", "{name}");
+ assert_eq!(tag(&stage, name), "new", "{name}");
+ }
+ cleanup(home);
+ }
+
+ #[test]
+ fn rollback_takes_back_sidecars_the_failed_update_added() {
+ let home = temp_home("rollback-extra");
+ // A legacy install: the managed venv is there, the tiered sidecars are not.
+ fs::create_dir_all(home.join("unsloth_studio")).unwrap();
+ fs::write(home.join("unsloth_studio").join("tag"), "old").unwrap();
+ // The staged update builds all of them.
+ stage_ready(&home, &versions(None));
+ reconcile_at_launch(&home, "0.1.900-beta");
+ assert_eq!(tag(&home, "unsloth_studio"), "new");
+ assert_eq!(tag(&home, ".venv_t5_530"), "new");
+
+ // The new backend never became healthy.
+ reconcile_at_launch(&home, "0.1.900-beta");
+
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
+ for name in [".venv_t5_530", ".venv_t5_550", ".venv_t5_510"] {
+ // The restored backend must not find the unconfirmed update's sidecars.
+ assert!(!home.join(name).exists(), "{name}");
+ }
+ assert_eq!(status(&home).state, "failed");
+ cleanup(home);
+ }
+
+ #[test]
+ fn native_helpers_activate_and_roll_back_with_the_python_runtime() {
+ let container = temp_home("helpers");
+ let home = container.join("studio");
+ fs::create_dir_all(&home).unwrap();
+ make_runtime(&home, "old");
+ stage_ready(&home, &versions(None));
+ for name in HELPER_RUNTIME_ENTRIES {
+ fs::create_dir_all(container.join(name)).unwrap();
+ fs::write(container.join(name).join("tag"), "old").unwrap();
+ fs::create_dir_all(home.join(STAGE_DIR).join(name)).unwrap();
+ fs::write(home.join(STAGE_DIR).join(name).join("tag"), "new").unwrap();
+ }
+
+ activate_ready(&home, "0.1.900-beta").unwrap();
+
+ for name in HELPER_RUNTIME_ENTRIES {
+ assert_eq!(tag(&container, name), "new", "{name}");
+ assert_eq!(tag(&home.join(PREV_DIR), name), "old", "{name}");
+ }
+
+ roll_back_unconfirmed_with(&home, false).unwrap();
+
+ for name in HELPER_RUNTIME_ENTRIES {
+ assert_eq!(tag(&container, name), "old", "{name}");
+ }
+ cleanup(container);
+ }
+
+ #[test]
+ fn undoing_an_activation_takes_the_staged_only_sidecars_back() {
+ let home = temp_home("undo-extra");
+ // A legacy install: the managed venv, and no tiered sidecars to swap back.
+ fs::create_dir_all(home.join("unsloth_studio")).unwrap();
+ fs::write(home.join("unsloth_studio").join("tag"), "old").unwrap();
+ let stage = home.join(STAGE_DIR);
+ make_runtime(&stage, "new");
+ let prev = home.join(PREV_DIR);
+ fs::create_dir_all(&prev).unwrap();
+
+ swap_entries(&home, &stage, &prev, false).unwrap();
+ assert_eq!(tag(&home, ".venv_t5_530"), "new");
+
+ // What activate_ready runs when the pending marker cannot be written.
+ swap_entries(&home, &prev, &stage, true).unwrap();
+
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
+ for name in [".venv_t5_530", ".venv_t5_550", ".venv_t5_510"] {
+ // No marker is left to undo these later, so they cannot stay live.
+ assert!(!home.join(name).exists(), "{name}");
+ assert_eq!(tag(&stage, name), "new", "{name}");
+ }
+ cleanup(home);
+ }
+
+ #[test]
+ fn a_runtime_still_in_use_defers_instead_of_confirming() {
+ let home = temp_home("defer");
+ make_runtime(&home, "old");
+ stage_ready(&home, &versions(None));
+ reconcile_at_launch(&home, "0.1.900-beta");
+ assert_eq!(tag(&home, "unsloth_studio"), "new");
+ assert!(home.join(PREV_DIR).join(PENDING_MARKER).is_file());
+
+ // Force-closed after activation: a backend is alive on the new tree but it
+ // never reached validate_candidate_port, so nothing has vouched for it.
+ roll_back_unconfirmed_with(&home, true).unwrap();
+
+ // Neither confirmed nor rolled back -- the way back has to survive.
+ assert_eq!(tag(&home, "unsloth_studio"), "new");
+ assert!(home.join(PREV_DIR).join(PENDING_MARKER).is_file());
+
+ // Once nothing holds the tree, the rollback it was owed still happens.
+ roll_back_unconfirmed_with(&home, false).unwrap();
+
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
+ assert_eq!(status(&home).state, "failed");
+ cleanup(home);
+ }
+
+ #[test]
+ fn stale_rollback_trash_is_removed_at_launch() {
+ let home = temp_home("trash");
+ make_runtime(&home, "old");
+ let trash = home.join(format!("{ROLLBACK_TRASH_PREFIX}1"));
+ fs::create_dir_all(trash.join("unsloth_studio")).unwrap();
+
+ reconcile_at_launch(&home, "0.1.900-beta");
+ for _ in 0..50 {
+ if !trash.exists() {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
+
+ assert!(!trash.exists());
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
+ cleanup(home);
+ }
+
+ /// This process, whose real start time the guard can be measured against.
+ fn live_pid_or_skip(home: &Path) -> Option<u32> {
+ let me = std::process::id();
+ if crate::process_identity::process_start_time_secs(me).is_none() {
+ // The OS will not say, so the reuse guard cannot fire and neither can
+ // the assertion built on it.
+ fs::remove_dir_all(home).ok();
+ return None;
+ }
+ Some(me)
+ }
+
+ #[test]
+ fn a_startup_marker_counts_as_a_live_tree_record() {
+ let home = temp_home("markers");
+ let me = std::process::id();
+ // What a backend has while it is still binding, and what it keeps after
+ // dropping its pid records until shutdown finishes.
+ fs::write(
+ home.join(format!("studio-starting-{me}.marker")),
+ format!("{me}\n"),
+ )
+ .unwrap();
+
+ assert!(recorded_pids(&home).contains(&me));
+ cleanup(home);
+ }
+
+ #[test]
+ fn a_bare_record_cannot_resurrect_a_pid_the_timed_one_rejected() {
+ let home = temp_home("reused");
+ let Some(me) = live_pid_or_skip(&home) else {
+ return;
+ };
+ // A start time nowhere near this process's: the record describes something
+ // that is gone, and the pid has since been handed out again.
+ fs::write(
+ home.join(format!("studio-8888-{me}.pid")),
+ format!("{me}\n1.0\n"),
+ )
+ .unwrap();
+ fs::write(home.join("studio.pid"), format!("{me}\n")).unwrap();
+
+ assert!(!recorded_pids(&home).contains(&me));
+ cleanup(home);
+ }
+
+ #[test]
+ fn a_bare_record_with_no_timed_evidence_still_counts() {
+ let home = temp_home("bare");
+ let me = std::process::id();
+ // A pre-upgrade backend, or one whose per-port write failed.
+ fs::write(home.join("studio.pid"), format!("{me}\n")).unwrap();
+
+ assert!(recorded_pids(&home).contains(&me));
+ cleanup(home);
+ }
+
+ #[test]
+ fn a_stage_that_never_reached_the_pinned_backend_is_rejected() {
+ let home = temp_home("version-gate");
+ stage_ready(
+ &home,
+ &StagedVersions {
+ // What a stale mirror leaves behind: setup succeeded from cache and
+ // the cloned package never moved.
+ backend_version: "2026.9.1".into(),
+ shell_version: None,
+ },
+ );
+
+ let err = staged_backend_meets(&home, "2026.9.2").unwrap_err();
+ assert!(err.contains("2026.9.1"), "{err}");
+ assert!(err.contains("2026.9.2"), "{err}");
+ // Equal and newer both pass: the pin is a floor, not an exact match.
+ assert!(staged_backend_meets(&home, "2026.9.1").is_ok());
+ assert!(staged_backend_meets(&home, "2026.9.0").is_ok());
+ cleanup(home);
+ }
+
+ #[test]
+ fn status_reports_a_ready_stage() {
+ let home = temp_home("status");
+ stage_ready(&home, &versions(Some("0.1.900-beta")));
+ assert_eq!(
+ status(&home),
+ StagedUpdateStatus {
+ state: "ready",
+ backend_version: Some("2026.9.1".into()),
+ shell_version: Some("0.1.900-beta".into()),
+ staging: false,
+ staging_shell_version: None,
+ }
+ );
+ discard(&home);
+ assert_eq!(status(&home).state, "none");
+ cleanup(home);
+ }
+}
diff --git a/studio/src-tauri/src/update.rs b/studio/src-tauri/src/update.rs
index ae4b4425411..dfd943dc465 100644
--- a/studio/src-tauri/src/update.rs
+++ b/studio/src-tauri/src/update.rs
@@ -14,16 +14,94 @@ pub struct UpdateProcess {
pub child: Option<Box<dyn ChildWrapper + Send>>,
pub intentional_stop: bool,
pub current_attempt: Option<AttemptLog>,
+ pub staged: bool,
+ pub staged_shell_version: Option<String>,
}
pub type UpdateState = Arc<Mutex<UpdateProcess>>;
+/// report staged work owned by this app or a surviving cli process.
+pub(crate) fn is_staged_update_running(state: &UpdateState) -> bool {
+ let local = state
+ .lock()
+ .map(|s| s.child.is_some() && s.staged)
+ .unwrap_or(false);
+ local || staged_update_is_owned_elsewhere()
+}
+
+pub(crate) fn staged_update_is_owned_elsewhere() -> bool {
+ let home = crate::diagnostics::studio_dir();
+ staged_update_is_owned_elsewhere_at(&home, || {
+ crate::process::with_studio_runtime_launch_guard(|| Ok(()))
+ })
+}
+
+fn staged_update_is_owned_elsewhere_at(
+ home: &std::path::Path,
+ try_gate: impl FnOnce() -> Result<(), String>,
+) -> bool {
+ if !home.join(crate::staged_update::STAGE_DIR).is_dir() {
+ return false;
+ }
+ try_gate().is_err()
+}
+
+pub(crate) fn staged_update_shell_version(state: &UpdateState) -> Option<String> {
+ state.lock().ok().and_then(|update| {
+ (update.child.is_some() && update.staged)
+ .then(|| update.staged_shell_version.clone())
+ .flatten()
+ })
+}
+
pub fn new_update_state() -> UpdateState {
Arc::new(Mutex::new(UpdateProcess::default()))
}
+const UPDATE_ARGS: &[&str] = &["studio", "update"];
+const STAGE_ARGS: &[&str] = &["studio", "update", "--stage"];
+const SHELL_VERSION_ENV: &str = "UNSLOTH_TAURI_SHELL_VERSION";
+
+pub(crate) enum UpdateKind {
+ Backend,
+ Repair(String),
+ Staged {
+ shell_version: Option<String>,
+ backend_version: Option<String>,
+ },
+}
+
+impl UpdateKind {
+ fn args(&self) -> &'static [&'static str] {
+ match self {
+ UpdateKind::Staged { .. } => STAGE_ARGS,
+ _ => UPDATE_ARGS,
+ }
+ }
+
+ fn progress_event(&self) -> &'static str {
+ match self {
+ UpdateKind::Backend => "update-progress",
+ UpdateKind::Repair(_) => "repair-progress",
+ UpdateKind::Staged { .. } => "stage-progress",
+ }
+ }
+
+ fn terminal_events(&self) -> Option<(&'static str, &'static str)> {
+ match self {
+ UpdateKind::Backend => Some(("update-complete", "update-failed")),
+ UpdateKind::Repair(_) => None,
+ UpdateKind::Staged { .. } => Some(("stage-complete", "stage-failed")),
+ }
+ }
+
+ fn mutates_live_environment(&self) -> bool {
+ !matches!(self, UpdateKind::Staged { .. })
+ }
+}
+
// ── Spawn ──
-fn build_update_command(bin: &std::path::Path) -> Result<Command, String> {
+fn build_update_command(bin: &std::path::Path, args: &[&str]) -> Result<Command, String> {
// Only the Windows arm below mutates it.
#[cfg_attr(not(windows), allow(unused_mut))]
// Isolated, as this call site shipped. It is the one managed invocation nobody
@@ -32,7 +110,7 @@ fn build_update_command(bin: &std::path::Path) -> Result<Command, String> {
// here. Everything else inherits, because the console script does.
let mut cmd = crate::process::build_managed_cli_command_with(
bin,
- &["studio", "update"],
+ args,
crate::process::Isolation::Isolated,
)?;
// The only managed invocation that scrubs, and the only one that shipped doing it.
@@ -40,11 +118,8 @@ fn build_update_command(bin: &std::path::Path) -> Result<Command, String> {
// the failure is unrecoverable: a foreign PYTHONHOME stops the managed interpreter
// finding its own site-packages, and a PYTHONPATH pointing at another checkout
// makes `from unsloth_cli import app` update the wrong install.
- #[cfg(windows)]
- {
- cmd.env_remove("PYTHONHOME");
- cmd.env_remove("PYTHONPATH");
- }
+ cmd.env_remove("PYTHONHOME");
+ cmd.env_remove("PYTHONPATH");
Ok(cmd)
}
@@ -61,9 +136,30 @@ fn configure_tauri_update_environment(cmd: &mut Command) {
);
}
+fn configure_staged_update_environment(cmd: &mut Command) {
+ for name in [
+ "UNSLOTH_LOCAL_LLAMA_CPP_DIR",
+ "UNSLOTH_LLAMA_FORCE_COMPILE",
+ "UNSLOTH_LLAMA_FORCE_COMPILE_REF",
+ "UNSLOTH_LLAMA_PR",
+ "UNSLOTH_LLAMA_PR_FORCE",
+ ] {
+ cmd.env_remove(name);
+ }
+}
+
+fn configure_runtime_gate_environment(cmd: &mut Command, kind: &UpdateKind) {
+ if kind.mutates_live_environment() {
+ cmd.env(crate::process::STUDIO_RUNTIME_GATE_HANDOFF_ENV, "1");
+ } else {
+ cmd.env_remove(crate::process::STUDIO_RUNTIME_GATE_HANDOFF_ENV);
+ }
+}
+
fn spawn_update(
bin: &std::path::Path,
state: &UpdateState,
+ kind: &UpdateKind,
) -> Result<
(
Option<std::process::ChildStdout>,
@@ -76,9 +172,21 @@ fn spawn_update(
return Err("Update is already running.".to_string());
}
update.intentional_stop = false;
+ update.staged = matches!(kind, UpdateKind::Staged { .. });
+ update.staged_shell_version = match kind {
+ UpdateKind::Staged { shell_version, .. } => shell_version.clone(),
+ _ => None,
+ };
- let mut cmd = build_update_command(bin)?;
+ let mut cmd = build_update_command(bin, kind.args())?;
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
+ if let UpdateKind::Staged {
+ shell_version: Some(version),
+ ..
+ } = kind
+ {
+ cmd.env(SHELL_VERSION_ENV, version);
+ }
// A login-started desktop inherits C:\Windows\system32, which the CLI refuses
// to run from; the Windows branch above hits the same guard. Pin both.
@@ -98,8 +206,10 @@ fn spawn_update(
// Keep the update on the desktop-managed install and avoid rebuilding assets
// that are already compiled into the signed Tauri bundle.
configure_tauri_update_environment(&mut cmd);
- #[cfg(windows)]
- cmd.env(crate::process::STUDIO_RUNTIME_GATE_HANDOFF_ENV, "1");
+ if matches!(kind, UpdateKind::Staged { .. }) {
+ configure_staged_update_environment(&mut cmd);
+ }
+ configure_runtime_gate_environment(&mut cmd, kind);
// read_lossy_lines decodes as UTF-8, and here the child is Python itself,
// which otherwise encodes redirected streams with the locale code page.
@@ -226,11 +336,13 @@ fn wait_for_exit(state: &UpdateState) -> Result<(ExitStatus, bool), String> {
Some(child) => match child.try_wait() {
Ok(Some(status)) => {
update.child = None;
+ update.staged_shell_version = None;
return Ok((status, intentional));
}
Ok(None) => {}
Err(e) => {
update.child = None;
+ update.staged_shell_version = None;
return Err(format!("Error waiting for update: {}", e));
}
},
@@ -252,7 +364,7 @@ pub fn run_backend_update(
state: UpdateState,
diagnostics: DiagnosticsState,
) -> Result<(), String> {
- run_backend_update_with_terminal_events(app, state, diagnostics, true, None)
+ run_update(app, state, diagnostics, UpdateKind::Backend)
}
pub(crate) fn run_backend_update_for_repair(
@@ -261,19 +373,38 @@ pub(crate) fn run_backend_update_for_repair(
diagnostics: DiagnosticsState,
repair_group_id: String,
) -> Result<(), String> {
- run_backend_update_with_terminal_events(app, state, diagnostics, false, Some(repair_group_id))
+ run_update(app, state, diagnostics, UpdateKind::Repair(repair_group_id))
+}
+
+pub(crate) fn run_staged_update(
+ app: AppHandle,
+ state: UpdateState,
+ diagnostics: DiagnosticsState,
+ shell_version: Option<String>,
+ backend_version: Option<String>,
+) -> Result<(), String> {
+ run_update(
+ app,
+ state,
+ diagnostics,
+ UpdateKind::Staged {
+ shell_version,
+ backend_version,
+ },
+ )
}
-fn run_backend_update_with_terminal_events(
+fn run_update(
app: AppHandle,
state: UpdateState,
diagnostics: DiagnosticsState,
- terminal_events: bool,
- repair_group_id: Option<String>,
+ kind: UpdateKind,
) -> Result<(), String> {
- let attempt = match repair_group_id.as_deref() {
- Some(group_id) => diagnostics::begin_repair_child(&diagnostics, group_id, "update"),
- None => diagnostics::begin_update_attempt(&diagnostics),
+ let attempt = match &kind {
+ UpdateKind::Repair(group_id) => {
+ diagnostics::begin_repair_child(&diagnostics, group_id, "update")
+ }
+ _ => diagnostics::begin_update_attempt(&diagnostics),
};
if let Ok(mut update) = state.lock() {
update.current_attempt = Some(attempt.clone());
@@ -295,20 +426,13 @@ fn run_backend_update_with_terminal_events(
"meta",
&format!("Starting backend update via {:?}", bin),
);
- let progress_event = if terminal_events {
- "update-progress"
- } else {
- "repair-progress"
- };
+ let progress_event = kind.progress_event();
let _ = app.emit(progress_event, "Starting backend update...");
let explicit_error = Arc::new(Mutex::new(None));
- // Update mutates the managed environment for its whole lifetime. This function
- // is synchronous, so the thread-owned Win32 mutex never crosses an await.
- let result = crate::process::with_studio_runtime_launch_guard(|| {
- crate::process::ensure_managed_environment_is_idle(&bin)?;
+ let run_child = || {
let (stdout, stderr) =
- spawn_update(&bin, &state).map_err(|msg| format!("spawn_update: {msg}"))?;
+ spawn_update(&bin, &state, &kind).map_err(|msg| format!("spawn_update: {msg}"))?;
let threads = stream_output(
&app,
progress_event,
@@ -324,7 +448,16 @@ fn run_backend_update_with_terminal_events(
let _ = handle.join();
}
result
- });
+ };
+ // the staged cli owns the gate so it remains held after a hard desktop exit.
+ let result = if kind.mutates_live_environment() {
+ crate::process::with_studio_runtime_launch_guard(|| {
+ crate::process::ensure_managed_environment_is_idle(&bin)?;
+ run_child()
+ })
+ } else {
+ run_child()
+ };
// Read only after the guard returned, so both reader threads are joined.
let explicit_error = explicit_error.lock().ok().and_then(|error| error.clone());
@@ -338,9 +471,24 @@ fn run_backend_update_with_terminal_events(
None,
);
clear_current_attempt(&state);
+ if let UpdateKind::Staged {
+ backend_version: Some(required),
+ ..
+ } = &kind
+ {
+ let home = crate::diagnostics::studio_dir();
+ if let Err(msg) = crate::staged_update::staged_backend_meets(&home, required) {
+ crate::staged_update::discard(&home);
+ error!("[update] {msg}");
+ if let Some((_, failed)) = kind.terminal_events() {
+ let _ = app.emit(failed, &msg);
+ }
+ return Err(msg);
+ }
+ }
info!("[update] Backend update complete");
- if terminal_events {
- let _ = app.emit("update-complete", ());
+ if let Some((complete, _)) = kind.terminal_events() {
+ let _ = app.emit(complete, ());
}
Ok(())
}
@@ -368,8 +516,8 @@ fn run_backend_update_with_terminal_events(
);
clear_current_attempt(&state);
error!("[update] {}", msg);
- if terminal_events {
- let _ = app.emit("update-failed", &msg);
+ if let Some((_, failed)) = kind.terminal_events() {
+ let _ = app.emit(failed, &msg);
}
Err(msg)
}
@@ -377,8 +525,8 @@ fn run_backend_update_with_terminal_events(
diagnostics::finish_attempt(&diagnostics, &attempt, None, false, Some(msg.clone()));
clear_current_attempt(&state);
error!("[update] {}", msg);
- if terminal_events {
- let _ = app.emit("update-failed", &msg);
+ if let Some((_, failed)) = kind.terminal_events() {
+ let _ = app.emit(failed, &msg);
}
Err(msg)
}
@@ -416,6 +564,27 @@ pub fn record_update_intentional_stop(state: &UpdateState, diagnostics: &Diagnos
pub const UPDATE_STOPPED: &str = "Update stopped.";
+#[cfg(unix)]
+fn process_group_alive(process_group: i32) -> bool {
+ let result = unsafe { libc::kill(-process_group, 0) };
+ result == 0 || std::io::Error::last_os_error().raw_os_error() != Some(libc::ESRCH)
+}
+
+#[cfg(unix)]
+fn signal_process_group(process_group: i32, signal: i32) -> Result<(), String> {
+ let result = unsafe { libc::kill(-process_group, signal) };
+ if result == 0 {
+ return Ok(());
+ }
+ let error = std::io::Error::last_os_error();
+ if error.raw_os_error() == Some(libc::ESRCH) {
+ return Ok(());
+ }
+ Err(format!(
+ "Could not signal update process group {process_group}: {error}"
+ ))
+}
+
pub fn stop_update(state: &UpdateState) -> Result<(), String> {
let mut child = {
let mut update = match state.lock() {
@@ -426,6 +595,7 @@ pub fn stop_update(state: &UpdateState) -> Result<(), String> {
}
};
update.intentional_stop = true;
+ update.staged_shell_version = None;
update.child.take()
};
@@ -444,20 +614,44 @@ pub fn stop_update(state: &UpdateState) -> Result<(), String> {
let _ = child.wait();
return Ok(());
}
- unsafe {
- libc::kill(-(pid as i32), libc::SIGTERM);
- }
+ let process_group = pid as i32;
+ signal_process_group(process_group, libc::SIGTERM)?;
+ let mut leader_exited = false;
for _ in 0..50 {
- match child.try_wait() {
- Ok(Some(status)) => {
- info!("Update exited gracefully with status: {:?}", status);
- return Ok(());
+ if !leader_exited {
+ match child.try_wait() {
+ Ok(Some(status)) => {
+ leader_exited = true;
+ info!("Update leader exited with status: {:?}", status);
+ }
+ Ok(None) => {}
+ Err(error) => warn!("Could not poll update leader: {error}"),
+ }
+ }
+ if !process_group_alive(process_group) {
+ if !leader_exited {
+ let _ = child.wait();
}
- Ok(None) => std::thread::sleep(std::time::Duration::from_millis(100)),
- Err(_) => break,
+ info!("Update process group stopped gracefully");
+ return Ok(());
+ }
+ std::thread::sleep(std::time::Duration::from_millis(100));
+ }
+ warn!("Update process group did not exit gracefully, force killing");
+ signal_process_group(process_group, libc::SIGKILL)?;
+ if !leader_exited {
+ let _ = child.wait();
+ }
+ for _ in 0..50 {
+ if !process_group_alive(process_group) {
+ info!("Update process group force stopped");
+ return Ok(());
}
+ std::thread::sleep(std::time::Duration::from_millis(100));
}
- warn!("Update did not exit gracefully, force killing");
+ return Err(format!(
+ "Update process group {process_group} is still running after SIGKILL"
+ ));
}
#[cfg(windows)]
@@ -465,14 +659,6 @@ pub fn stop_update(state: &UpdateState) -> Result<(), String> {
crate::process::force_kill_process_tree(pid, child, "Update");
return Ok(());
}
-
- #[cfg(unix)]
- {
- let _ = child.kill();
- let _ = child.wait();
- info!("Update process group force stopped");
- Ok(())
- }
}
#[cfg(test)]
@@ -533,7 +719,7 @@ mod tests {
let bin = dir.join("unsloth.exe");
std::fs::write(&python, b"").unwrap();
- let cmd = build_update_command(&bin).unwrap();
+ let cmd = build_update_command(&bin, UPDATE_ARGS).unwrap();
assert_eq!(cmd.get_program(), python.as_os_str());
assert_ne!(cmd.get_program(), bin.as_os_str());
@@ -566,7 +752,7 @@ mod tests {
let bin = std::env::temp_dir()
.join("missing-managed-python")
.join("unsloth.exe");
- assert!(build_update_command(&bin)
+ assert!(build_update_command(&bin, UPDATE_ARGS)
.unwrap_err()
.contains("python.exe"));
}
@@ -574,9 +760,8 @@ mod tests {
// The Windows trampoline moved into process.rs; nothing about the POSIX
// Dropping -I made this load bearing rather than belt and braces: without -E the
// child now reads both. See build_update_command for what each one breaks.
- #[cfg(windows)]
#[test]
- fn windows_update_command_still_scrubs_the_python_search_path() {
+ fn update_command_scrubs_the_python_search_path() {
let dir = std::env::temp_dir().join(format!(
"unsloth-update-scrub-{}-{}",
std::process::id(),
@@ -591,7 +776,7 @@ mod tests {
std::fs::write(&python, "").unwrap();
std::fs::write(&bin, "").unwrap();
- let cmd = build_update_command(&bin).unwrap();
+ let cmd = build_update_command(&bin, UPDATE_ARGS).unwrap();
for name in ["PYTHONHOME", "PYTHONPATH"] {
assert!(
cmd.get_envs()
@@ -609,15 +794,145 @@ mod tests {
use std::ffi::OsString;
let bin = std::path::Path::new("/opt/unsloth/bin/unsloth");
- let cmd = build_update_command(bin).unwrap();
+ let cmd = build_update_command(bin, UPDATE_ARGS).unwrap();
assert_eq!(cmd.get_program(), bin.as_os_str());
assert_eq!(
cmd.get_args().map(OsString::from).collect::<Vec<_>>(),
vec![OsString::from("studio"), OsString::from("update")]
);
- // No PYTHONHOME/PYTHONPATH scrubbing off Windows: the console script is
- // not the interpreter, and callers that need it do it themselves.
- assert!(cmd.get_envs().next().is_none());
+ for name in ["PYTHONHOME", "PYTHONPATH"] {
+ assert!(cmd
+ .get_envs()
+ .any(|(key, value)| key == std::ffi::OsStr::new(name) && value.is_none()));
+ }
+ }
+
+ #[test]
+ fn staged_update_drops_source_build_overrides() {
+ use std::ffi::OsStr;
+
+ let mut cmd = Command::new("unused");
+ configure_staged_update_environment(&mut cmd);
+
+ for name in [
+ "UNSLOTH_LOCAL_LLAMA_CPP_DIR",
+ "UNSLOTH_LLAMA_FORCE_COMPILE",
+ "UNSLOTH_LLAMA_FORCE_COMPILE_REF",
+ "UNSLOTH_LLAMA_PR",
+ "UNSLOTH_LLAMA_PR_FORCE",
+ ] {
+ assert!(cmd
+ .get_envs()
+ .any(|(key, value)| key == OsStr::new(name) && value.is_none()));
+ }
+ }
+
+ #[test]
+ fn staged_update_child_acquires_its_own_runtime_gate() {
+ use std::ffi::OsStr;
+
+ let mut cmd = Command::new("unused");
+ configure_runtime_gate_environment(
+ &mut cmd,
+ &UpdateKind::Staged {
+ shell_version: None,
+ backend_version: None,
+ },
+ );
+
+ assert!(cmd.get_envs().any(|(key, value)| {
+ key == OsStr::new(crate::process::STUDIO_RUNTIME_GATE_HANDOFF_ENV) && value.is_none()
+ }));
+ }
+
+ #[test]
+ fn live_update_child_uses_the_parent_runtime_gate() {
+ use std::ffi::OsStr;
+
+ let mut cmd = Command::new("unused");
+ configure_runtime_gate_environment(&mut cmd, &UpdateKind::Backend);
+
+ assert!(cmd.get_envs().any(|(key, value)| {
+ key == OsStr::new(crate::process::STUDIO_RUNTIME_GATE_HANDOFF_ENV)
+ && value == Some(OsStr::new("1"))
+ }));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn surviving_stage_gate_blocks_reopen_until_the_owner_exits() {
+ use std::os::fd::AsRawFd;
+
+ let home = tempfile::tempdir().unwrap();
+ std::fs::create_dir(home.path().join(crate::staged_update::STAGE_DIR)).unwrap();
+ let gate_path = home.path().join(".studio-runtime.lock");
+ let owner = std::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .create(true)
+ .open(&gate_path)
+ .unwrap();
+ assert_eq!(unsafe { libc::flock(owner.as_raw_fd(), libc::LOCK_EX) }, 0);
+
+ let probe = || {
+ let candidate = std::fs::OpenOptions::new()
+ .read(true)
+ .write(true)
+ .open(&gate_path)
+ .map_err(|error| error.to_string())?;
+ let result =
+ unsafe { libc::flock(candidate.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
+ if result == 0 {
+ unsafe { libc::flock(candidate.as_raw_fd(), libc::LOCK_UN) };
+ Ok(())
+ } else {
+ Err(std::io::Error::last_os_error().to_string())
+ }
+ };
+
+ assert!(staged_update_is_owned_elsewhere_at(home.path(), probe));
+ drop(owner);
+ assert!(!staged_update_is_owned_elsewhere_at(home.path(), probe));
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn stop_update_kills_descendants_after_the_group_leader_exits() {
+ let dir = tempfile::tempdir().unwrap();
+ let child_pid_file = dir.path().join("child.pid");
+ let mut command = Command::new("/bin/sh");
+ command
+ .args([
+ "-c",
+ "trap 'exit 0' TERM; /bin/sh -c 'trap \"\" TERM; while :; do sleep 1; done' & echo $! > \"$1\"; while :; do sleep 1; done",
+ "update-test",
+ ])
+ .arg(&child_pid_file)
+ .stdout(Stdio::null())
+ .stderr(Stdio::null());
+ let mut wrapped = CommandWrap::from(command);
+ wrapped.wrap(ProcessGroup::leader());
+ let child = wrapped.spawn().unwrap();
+ let process_group = child.id() as i32;
+ let state = new_update_state();
+ state.lock().unwrap().child = Some(child);
+
+ for _ in 0..50 {
+ if child_pid_file.is_file() {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
+ let descendant = std::fs::read_to_string(&child_pid_file)
+ .unwrap()
+ .trim()
+ .parse::<i32>()
+ .unwrap();
+
+ stop_update(&state).unwrap();
+
+ assert!(!process_group_alive(process_group));
+ assert_eq!(unsafe { libc::kill(descendant, 0) }, -1);
}
}
diff --git a/tests/python/test_studio_runtime_gate.py b/tests/python/test_studio_runtime_gate.py
index 8e25a6faa96..60eca5a00c2 100644
--- a/tests/python/test_studio_runtime_gate.py
+++ b/tests/python/test_studio_runtime_gate.py
@@ -10,6 +10,7 @@ import os
import subprocess
import sys
import threading
+import time
from ctypes import wintypes
from pathlib import Path
from types import SimpleNamespace
@@ -61,9 +62,15 @@ def test_runtime_gate_handoff_is_one_shot(monkeypatch):
assert gate.consume_runtime_gate_handoff() is False
+def test_runtime_gate_acquire_is_one_shot(monkeypatch):
+ monkeypatch.setenv(gate._RUNTIME_GATE_ACQUIRE_ENV, "1")
+ assert gate.consume_runtime_gate_acquire() is True
+ assert gate.consume_runtime_gate_acquire() is False
+
+
def test_terminal_launch_boundaries_use_the_runtime_gate():
source = STUDIO_COMMAND.read_text(encoding = "utf-8")
- assert source.count("with _studio_runtime_launch_guard(") >= 4
+ assert source.count("with _studio_runtime_launch_guard(") >= 5
assert "runtime_gate_child_environment()" in source
assert "runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()" in source
@@ -95,6 +102,146 @@ def test_terminal_setup_holds_the_gate_through_environment_mutation():
assert consume < guard < idle_scan < launcher < setup
+def test_terminal_stage_holds_the_gate_through_the_clone():
+ source = STUDIO_COMMAND.read_text(encoding = "utf-8")
+ body = source[source.index("def _stage_update(") : source.index("class _WindowsLauncher")]
+ consume = body.index("_studio_runtime_gate.consume_runtime_gate_handoff()")
+ guard = body.index("with _studio_runtime_launch_guard(", consume)
+ stage = body.index("_studio_stage.stage(", guard)
+ assert consume < guard < stage
+
+
[email protected](os.name == "nt", reason = "POSIX orphan process semantics are required")
+def test_staging_cli_keeps_the_gate_after_its_parent_exits(tmp_path):
+ home = tmp_path / "studio"
+ ready = tmp_path / "ready"
+ release = tmp_path / "release"
+ worker_pid = tmp_path / "worker.pid"
+ log = tmp_path / "worker.log"
+ worker = r"""
+import sys
+import time
+from pathlib import Path
+from unsloth_cli.commands import studio
+
+home, ready, release = map(Path, sys.argv[1:4])
+studio.STUDIO_HOME = home
+
+def fake_stage(*args, **kwargs):
+ (home / ".update-stage").mkdir(parents=True, exist_ok=True)
+ ready.write_text("ready", encoding="utf-8")
+ while not release.exists():
+ time.sleep(0.02)
+ return {"backend_version": "test", "root": str(home / ".update-stage")}
+
+studio._studio_stage.stage = fake_stage
+studio._stage_update(local=False, package="unsloth", verbose=False, verify=True)
+"""
+ parent = r"""
+import os
+import subprocess
+import sys
+
+log = open(sys.argv[6], "w", encoding="utf-8")
+child = subprocess.Popen(
+ [sys.executable, "-c", sys.argv[1], *sys.argv[2:5]],
+ start_new_session=True,
+ stdout=log,
+ stderr=subprocess.STDOUT,
+)
+with open(sys.argv[5], "w", encoding="utf-8") as pid_file:
+ pid_file.write(str(child.pid))
+os._exit(0)
+"""
+ env = os.environ.copy()
+ env.pop(gate._RUNTIME_GATE_HANDOFF_ENV, None)
+ result = subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ parent,
+ worker,
+ str(home),
+ str(ready),
+ str(release),
+ str(worker_pid),
+ str(log),
+ ],
+ env = env,
+ check = False,
+ )
+ assert result.returncode == 0
+
+ try:
+ deadline = time.monotonic() + 10
+ while not ready.exists() and time.monotonic() < deadline:
+ time.sleep(0.02)
+ assert ready.exists(), log.read_text(encoding = "utf-8") if log.exists() else ""
+ assert worker_pid.is_file()
+ with pytest.raises(gate.StudioRuntimeGateBusy):
+ with gate.studio_runtime_launch_guard(home):
+ pass
+ finally:
+ release.touch()
+
+ deadline = time.monotonic() + 10
+ while time.monotonic() < deadline:
+ try:
+ with gate.studio_runtime_launch_guard(home):
+ break
+ except gate.StudioRuntimeGateBusy:
+ time.sleep(0.02)
+ else:
+ pytest.fail(log.read_text(encoding = "utf-8") if log.exists() else "gate stayed busy")
+
+
[email protected](os.name == "nt", reason = "POSIX flock is required")
+def test_posix_runtime_gate_blocks_another_process_and_recovers(tmp_path):
+ script = """
+import sys
+from pathlib import Path
+from unsloth_cli import _studio_runtime_gate as gate
+try:
+ with gate.studio_runtime_launch_guard(Path(sys.argv[1])):
+ pass
+except gate.StudioRuntimeGateBusy:
+ raise SystemExit(7)
+"""
+ with gate.studio_runtime_launch_guard(tmp_path) as acquired:
+ assert acquired is True
+ blocked = subprocess.run([sys.executable, "-c", script, str(tmp_path)], check = False)
+ assert blocked.returncode == 7
+
+ recovered = subprocess.run([sys.executable, "-c", script, str(tmp_path)], check = False)
+ assert recovered.returncode == 0
+
+
[email protected](os.name == "nt", reason = "POSIX flock is required")
+def test_posix_runtime_gate_waits_for_parent_handoff(tmp_path):
+ script = """
+import sys
+from pathlib import Path
+from unsloth_cli import _studio_runtime_gate as gate
+print("waiting", flush=True)
+with gate.studio_runtime_launch_guard(Path(sys.argv[1]), wait=True):
+ print("acquired", flush=True)
+"""
+ with gate.studio_runtime_launch_guard(tmp_path):
+ child = subprocess.Popen(
+ [sys.executable, "-c", script, str(tmp_path)],
+ stdout = subprocess.PIPE,
+ text = True,
+ )
+ assert child.stdout is not None
+ assert child.stdout.readline().strip() == "waiting"
+ with pytest.raises(subprocess.TimeoutExpired):
+ child.wait(timeout = 0.2)
+
+ stdout, _ = child.communicate(timeout = 5)
+ assert child.returncode == 0
+ assert stdout.strip() == "acquired"
+
+
def test_interrupted_windows_setup_kills_tree_before_return(monkeypatch):
from unsloth_cli.commands import studio as studio_command
diff --git a/tests/python/test_whisper_source_build_root.py b/tests/python/test_whisper_source_build_root.py
new file mode 100644
index 00000000000..8ffd8326902
--- /dev/null
+++ b/tests/python/test_whisper_source_build_root.py
@@ -0,0 +1,59 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+from __future__ import annotations
+
+import os
+import subprocess
+from pathlib import Path
+
+import pytest
+
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+BUILD_SCRIPT = REPO_ROOT / "scripts" / "build_whisper_cpp.sh"
+
+
[email protected](os.name == "nt", reason = "the source builder is POSIX-only")
+def test_source_build_uses_the_staged_managed_root(tmp_path):
+ tool_dir = tmp_path / "bin"
+ tool_dir.mkdir()
+ git = tool_dir / "git"
+ git.write_text(
+ "#!/bin/sh\n"
+ "for argument do destination=$argument; done\n"
+ 'mkdir -p "$destination/.git"\n',
+ encoding = "utf-8",
+ )
+ cmake = tool_dir / "cmake"
+ cmake.write_text(
+ "#!/bin/sh\n"
+ 'if [ "$1" = "-S" ]; then\n'
+ " while [ $# -gt 0 ]; do\n"
+ ' if [ "$1" = "-B" ]; then shift; build=$1; break; fi\n'
+ " shift\n"
+ " done\n"
+ ' mkdir -p "$build/bin"\n'
+ " printf '#!/bin/sh\\nexit 0\\n' > \"$build/bin/whisper-server\"\n"
+ ' chmod +x "$build/bin/whisper-server"\n'
+ "fi\n",
+ encoding = "utf-8",
+ )
+ git.chmod(0o755)
+ cmake.chmod(0o755)
+
+ live_home = tmp_path / "live-home"
+ stage_root = tmp_path / "stage"
+ env = {
+ **os.environ,
+ "HOME": str(live_home),
+ "PATH": f"{tool_dir}{os.pathsep}{os.environ['PATH']}",
+ "UNSLOTH_HOME": str(stage_root),
+ }
+ env.pop("UNSLOTH_STUDIO_HOME", None)
+ env.pop("STUDIO_HOME", None)
+
+ subprocess.run(["sh", str(BUILD_SCRIPT)], env = env, check = True, capture_output = True)
+
+ assert (stage_root / "whisper.cpp" / "build" / "bin" / "whisper-server").is_file()
+ assert not (live_home / ".unsloth" / "whisper.cpp").exists()
diff --git a/tests/python/test_windows_installer_concurrency_guard.py b/tests/python/test_windows_installer_concurrency_guard.py
index cd9d286f510..0f7c048b94d 100644
--- a/tests/python/test_windows_installer_concurrency_guard.py
+++ b/tests/python/test_windows_installer_concurrency_guard.py
@@ -23,6 +23,7 @@ PROCESS_RS = REPO_ROOT / "studio" / "src-tauri" / "src" / "process.rs"
PREFLIGHT_MANAGED_RS = REPO_ROOT / "studio" / "src-tauri" / "src" / "preflight" / "managed.rs"
DESKTOP_AUTH_RS = REPO_ROOT / "studio" / "src-tauri" / "src" / "desktop_auth.rs"
UPDATE_RS = REPO_ROOT / "studio" / "src-tauri" / "src" / "update.rs"
+MAIN_RS = REPO_ROOT / "studio" / "src-tauri" / "src" / "main.rs"
STUDIO_COMMAND = REPO_ROOT / "unsloth_cli" / "commands" / "studio.py"
POWERSHELLS = [shell for shell in ("pwsh", "powershell") if shutil.which(shell)]
@@ -918,10 +919,10 @@ def test_tauri_runtime_uses_the_same_gate_before_backend_spawn():
start = process_source.index("pub fn start_backend(")
guard = process_source.index("acquire_studio_runtime_launch_guard()?", start)
resolve = process_source.index("resolve_backend_binary()", guard)
- handoff = process_source.index("STUDIO_RUNTIME_GATE_HANDOFF_ENV", resolve)
- spawn = process_source.index("cmd.spawn()", handoff)
+ acquire = process_source.index("STUDIO_RUNTIME_GATE_ACQUIRE_ENV", resolve)
+ spawn = process_source.index("cmd.spawn()", acquire)
store = process_source.index("proc.owned = Some(", spawn)
- assert guard < resolve < handoff < spawn < store
+ assert guard < resolve < acquire < spawn < store
def test_every_tauri_managed_child_spawn_uses_the_runtime_gate():
@@ -952,28 +953,47 @@ def test_every_tauri_managed_child_spawn_uses_the_runtime_gate():
provision_wait = desktop_auth_source.index("child.wait_with_output()", provision_spawn)
assert provision_guard < provision_spawn < provision_wait
+ # run_child owns the whole child lifetime.
+ update_child_fn = update_source.index("let run_child = || {")
+ update_spawn = update_source.index("spawn_update(&bin, &state", update_child_fn)
+ update_wait = update_source.index("wait_for_exit(&state)", update_spawn)
+ # a live update inherits the parent gate through its whole lifetime.
update_call = update_source.index(
- "let result = crate::process::with_studio_runtime_launch_guard"
+ "crate::process::with_studio_runtime_launch_guard(",
+ update_wait,
+ )
+ exemption = update_source.index("fn mutates_live_environment(&self) -> bool {")
+ assert (
+ "!matches!(self, UpdateKind::Staged { .. })" in update_source[exemption : exemption + 200]
)
+ update_scan_gate = update_source.index("if kind.mutates_live_environment() {", update_wait)
update_scan = update_source.index(
"ensure_managed_environment_is_idle(&bin)",
- update_call,
+ update_scan_gate,
)
- update_spawn = update_source.index("spawn_update(&bin, &state)", update_scan)
- update_wait = update_source.index("wait_for_exit(&state)", update_spawn)
- update_guard_release = update_source.index("\n });", update_wait)
- assert update_call < update_scan < update_spawn < update_wait < update_guard_release
+ update_gated_child = update_source.index("run_child()", update_scan)
+ update_guard_release = update_source.index("\n })", update_gated_child)
+ assert update_child_fn < update_spawn < update_wait < update_scan_gate
+ assert update_scan_gate < update_call < update_scan
+ assert update_scan < update_gated_child < update_guard_release
+ # a staged child acquires the gate itself so app death cannot release it early.
+ configure_gate = update_source.index("fn configure_runtime_gate_environment(")
+ staged_branch = update_source.index("cmd.env_remove(", configure_gate)
+ stage_run = update_source.index("} else {\n run_child()", update_call)
+ assert configure_gate < staged_branch < update_child_fn < stage_run
-def test_runtime_gate_handoff_covers_tauri_backend_and_installer_autostart():
+
+def test_runtime_gate_handoff_covers_managed_children():
process_source = PROCESS_RS.read_text(encoding = "utf-8")
install_source = INSTALL_PS1.read_text(encoding = "utf-8")
studio_source = STUDIO_COMMAND.read_text(encoding = "utf-8")
start = process_source.index("pub fn start_backend(")
- handoff = process_source.index('cmd.env(STUDIO_RUNTIME_GATE_HANDOFF_ENV, "1")', start)
- spawn = process_source.index("cmd.spawn()", handoff)
- assert handoff < spawn
+ clear_handoff = process_source.index("cmd.env_remove(STUDIO_RUNTIME_GATE_HANDOFF_ENV)", start)
+ acquire = process_source.index('cmd.env(STUDIO_RUNTIME_GATE_ACQUIRE_ENV, "1")', clear_handoff)
+ spawn = process_source.index("cmd.spawn()", acquire)
+ assert clear_handoff < acquire < spawn
prompt = install_source.index("Start Unsloth Studio now?")
save = install_source.index("$_runtimeGateHandoff =", prompt)
@@ -1008,11 +1028,49 @@ def test_runtime_gate_handoff_covers_tauri_backend_and_installer_autostart():
studio_source.count(
"runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()"
)
- == 4
+ == 5
+ )
+ assert (
+ studio_source.count(
+ "runtime_gate_acquire = _studio_runtime_gate.consume_runtime_gate_acquire()"
+ )
+ == 1
)
assert studio_source.count("inherited = runtime_gate_handoff") >= 5
+def test_a_reopened_app_cannot_replace_or_discard_an_externally_owned_stage():
+ update_source = UPDATE_RS.read_text(encoding = "utf-8")
+ commands_source = COMMANDS_RS.read_text(encoding = "utf-8")
+ main_source = MAIN_RS.read_text(encoding = "utf-8")
+
+ owner_check = update_source.index("pub(crate) fn staged_update_is_owned_elsewhere()")
+ gate_probe = update_source.index("with_studio_runtime_launch_guard", owner_check)
+ owner_helper = update_source.index("fn staged_update_is_owned_elsewhere_at(", gate_probe)
+ stage_probe = update_source.index("crate::staged_update::STAGE_DIR", owner_helper)
+ status = update_source.index("pub(crate) fn is_staged_update_running")
+ status_uses_owner = update_source.index("staged_update_is_owned_elsewhere()", status)
+ assert status < status_uses_owner < owner_check < gate_probe < owner_helper < stage_probe
+
+ start = commands_source.index("pub async fn start_staged_update(")
+ start_guard = commands_source.index("is_staged_update_running", start)
+ start_spawn = commands_source.index("update::run_staged_update", start_guard)
+ cancel = commands_source.index("pub fn cancel_staged_update(", start_spawn)
+ cancel_stop = commands_source.index("update::stop_update", cancel)
+ cancel_guard = commands_source.index("with_studio_runtime_launch_guard", cancel_stop)
+ cancel_remove = commands_source.index("staged_update::discard", cancel_guard)
+ discard = commands_source.index("pub fn discard_staged_update(")
+ discard_guard = commands_source.index("with_studio_runtime_launch_guard", discard)
+ discard_remove = commands_source.index("staged_update::discard", discard_guard)
+ assert start < start_guard < start_spawn < cancel < cancel_stop < cancel_guard < cancel_remove
+ assert cancel_remove < discard < discard_guard < discard_remove
+
+ setup = main_source.index(".setup(|app| {")
+ reconcile_gate = main_source.index("with_studio_runtime_launch_guard", setup)
+ reconcile = main_source.index("staged_update::reconcile_at_launch", reconcile_gate)
+ assert setup < reconcile_gate < reconcile
+
+
def test_tauri_start_install_rejects_backend_conflicts_before_spawn():
source = COMMANDS_RS.read_text(encoding = "utf-8")
start = source.index("pub async fn start_install(")
diff --git a/tests/python/test_windows_studio_update_launcher.py b/tests/python/test_windows_studio_update_launcher.py
index 6ff5f65e6be..b72b544f5e4 100644
--- a/tests/python/test_windows_studio_update_launcher.py
+++ b/tests/python/test_windows_studio_update_launcher.py
@@ -125,6 +125,27 @@ def _update(studio, *, verify = True):
studio.update(local = False, package = "unsloth", verbose = False, verify = verify)
[email protected](sys.platform != "win32", reason = "Windows DLL locking only")
[email protected]("entry", ["unsloth", "-m"])
[email protected]("command", ["setup", "update"])
+def test_windows_mutating_entry_does_not_load_pydantic_core(entry, command):
+ code = f"""
+import sys
+sys.argv = [{entry!r}, "studio", {command!r}]
+from unsloth_cli import app
+assert "pydantic_core" not in sys.modules
+assert "unsloth_cli.commands.train" not in sys.modules
+"""
+ result = subprocess.run(
+ [sys.executable, "-c", code],
+ cwd = REPO_ROOT,
+ capture_output = True,
+ text = True,
+ check = False,
+ )
+ assert result.returncode == 0, result.stderr
+
+
def test_setup_noop_preserves_launcher_and_removes_backup(monkeypatch, studio, tmp_path):
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)
@@ -324,6 +345,42 @@ def test_non_windows_preserves_call_order_without_launcher_operations(
assert list(tmp_path.rglob("unsloth.exe*")) == []
+def test_an_in_process_update_does_not_stage(monkeypatch, studio, tmp_path):
+ """`stage` defaults to typer's OptionInfo, and that sentinel is truthy.
+
+ Only the CLI resolves it to a bool, so a plain `if stage:` sends every
+ in-process call down the staging path and skips the update entirely.
+ """
+ monkeypatch.setattr(studio.platform, "system", lambda: "Linux")
+ monkeypatch.setattr(studio.sys, "executable", str(tmp_path / "bin" / "python"))
+ monkeypatch.setattr(studio, "_ensure_studio_env_exported", lambda: None)
+ staged = []
+ monkeypatch.setattr(studio, "_stage_update", lambda **kwargs: staged.append(kwargs))
+ calls = []
+ monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: calls.append("setup"))
+ # Tolerant of the verify hook's arity, which is not what this test pins.
+ monkeypatch.setattr(
+ studio, "_fail_if_install_damaged", lambda *_a, **_k: calls.append("verify")
+ )
+ monkeypatch.setattr(
+ studio, "_refresh_desktop_shortcuts", lambda **_kwargs: calls.append("refresh")
+ )
+ for name in (
+ "SKIP_STUDIO_BASE",
+ "STUDIO_PACKAGE_NAME",
+ "STUDIO_LOCAL_INSTALL",
+ "STUDIO_LOCAL_REPO",
+ "UNSLOTH_TAURI_UPDATE",
+ "UNSLOTH_STUDIO_STAGE_ROOT",
+ ):
+ monkeypatch.delenv(name, raising = False)
+
+ _update(studio)
+
+ assert staged == []
+ assert calls == ["setup", "verify", "refresh"]
+
+
def _shim(studio, payload = ORIGINAL_LAUNCHER):
"""The hardlinked PATH shim install.ps1 creates beside the managed venv."""
path = studio.STUDIO_HOME / "bin" / "unsloth.exe"
diff --git a/tests/sh/test_setup_staged_root.sh b/tests/sh/test_setup_staged_root.sh
new file mode 100755
index 00000000000..71b8056ba1a
--- /dev/null
+++ b/tests/sh/test_setup_staged_root.sh
@@ -0,0 +1,110 @@
+#!/bin/bash
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+# UNSLOTH_STUDIO_STAGE_ROOT redirects a background update into a copy of the
+# environment, and the whole point is that the live install keeps running and
+# keeps working if the staged one is never activated. Anything the setup scripts
+# write outside the stage root breaks that, so the two paths that delete under
+# $STUDIO_HOME have to be gated on the override.
+#
+# Source-shape assertions: driving either script to those lines needs a real
+# managed venv. Both are checked, because the failure is per-platform.
+set -e
+
+SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
+SETUP_SH="$SCRIPT_DIR/../../studio/setup.sh"
+SETUP_PS1="$SCRIPT_DIR/../../studio/setup.ps1"
+PASS=0
+FAIL=0
+
+check() {
+ if [ "$2" = 0 ]; then echo " PASS: $1"; PASS=$((PASS+1));
+ else echo " FAIL: $1"; FAIL=$((FAIL+1)); fi
+}
+
+has() { grep -qF "$2" "$1" && echo 0 || echo 1; }
+
+# ── the runtime root itself ──
+check "setup.sh reads the stage override" \
+ "$(has "$SETUP_SH" 'STAGE_ROOT="${UNSLOTH_STUDIO_STAGE_ROOT:-}"')"
+check "setup.sh falls back to STUDIO_HOME" \
+ "$(has "$SETUP_SH" 'RUNTIME_ROOT="${STAGE_ROOT:-$STUDIO_HOME}"')"
+check "setup.ps1 reads the stage override" \
+ "$(has "$SETUP_PS1" '$env:UNSLOTH_STUDIO_STAGE_ROOT')"
+check "setup.ps1 falls back to StudioHome" \
+ "$(has "$SETUP_PS1" '$RuntimeRoot = if ($StageRoot) { $StageRoot } else { $StudioHome }')"
+
+# Every venv the update writes has to follow the override, or a staged run
+# installs straight into the environment the app is running from.
+for v in VENV_DIR VENV_T5_530_DIR VENV_T5_550_DIR VENV_T5_510_DIR; do
+ check "setup.sh points $v at RUNTIME_ROOT" \
+ "$(grep -qE "^${v}=\"\\\$RUNTIME_ROOT/" "$SETUP_SH" && echo 0 || echo 1)"
+done
+for v in VenvDir VenvT5_530Dir VenvT5_550Dir VenvT5_510Dir; do
+ check "setup.ps1 points \$$v at RuntimeRoot" \
+ "$(grep -qE "^\\\$${v} = Join-Path \\\$RuntimeRoot " "$SETUP_PS1" && echo 0 || echo 1)"
+done
+
+# ── the two deletes under the live $STUDIO_HOME ──
+# The legacy single sidecar. Its tiered replacements land under the stage root and
+# may never be activated, so removing this during a staged run leaves the running
+# install with no sidecar at all.
+_sh_legacy=$(sed -n '/^if \[ -d "\$STUDIO_HOME\/\.venv_t5" \]; then$/,/^fi$/p' "$SETUP_SH")
+check "setup.sh guards the legacy sidecar removal on STAGE_ROOT" \
+ "$(printf '%s' "$_sh_legacy" | grep -qF '[ -z "$STAGE_ROOT" ]' && echo 0 || echo 1)"
+check "setup.sh still removes it on a live update" \
+ "$(printf '%s' "$_sh_legacy" | grep -qF 'rm -rf "$STUDIO_HOME/.venv_t5"' && echo 0 || echo 1)"
+
+_ps_legacy=$(sed -n '/^if (Test-Path -LiteralPath \$VenvT5Legacy) {$/,/^}$/p' "$SETUP_PS1")
+check "setup.ps1 guards the legacy sidecar removal on StageRoot" \
+ "$(printf '%s' "$_ps_legacy" | grep -qF 'if (-not $StageRoot)' && echo 0 || echo 1)"
+check "setup.ps1 still removes it on a live update" \
+ "$(printf '%s' "$_ps_legacy" | grep -qF 'Remove-Item -LiteralPath $VenvT5Legacy -Recurse -Force' && echo 0 || echo 1)"
+
+# The WebView cache belongs to the app that is still running and rendering from it.
+check "setup.sh skips the webview cache clear while staging" \
+ "$(has "$SETUP_SH" 'if [ -z "$STAGE_ROOT" ] && [ -x "$VENV_DIR/bin/python" ]; then')"
+check "setup.ps1 skips the webview cache clear while staging" \
+ "$(has "$SETUP_PS1" 'if (-not $StageRoot -and (Test-Path -LiteralPath (Join-Path $VenvDir "Scripts\python.exe") -PathType Leaf)) {')"
+
+check "setup.sh stages the managed Node runtime" \
+ "$(has "$SETUP_SH" '_NODE_PARENT="$RUNTIME_ROOT"')"
+check "setup.sh stages llama.cpp and whisper.cpp" \
+ "$(has "$SETUP_SH" 'UNSLOTH_HOME="$RUNTIME_ROOT"')"
+check "setup.sh forwards the staged helper root to whisper.cpp source builds" \
+ "$(has "$SETUP_SH" 'env UNSLOTH_HOME="$UNSLOTH_HOME" sh "$_WHISPER_BUILD"')"
+check "whisper.cpp source builds honor the managed helper root" \
+ "$(has "$SCRIPT_DIR/../../scripts/build_whisper_cpp.sh" '${UNSLOTH_HOME:-}')"
+check "setup.sh does not install global uv while staging" \
+ "$(has "$SETUP_SH" 'step "uv" "using pip inside the staged environment"')"
+check "setup.ps1 stages the managed Node runtime" \
+ "$(has "$SETUP_PS1" '$NodeParent = $StageRoot')"
+check "setup.ps1 stages llama.cpp and whisper.cpp" \
+ "$(has "$SETUP_PS1" 'return (Join-Path $StageRoot "llama.cpp")')"
+check "setup.ps1 does not persist User PATH while staging" \
+ "$(has "$SETUP_PS1" 'Get-Variable -Name StageRoot -ValueOnly -ErrorAction SilentlyContinue')"
+check "setup.ps1 leaves vcredist unchanged while staging" \
+ "$(has "$SETUP_PS1" 'step "vcredist" "missing; unchanged during staging"')"
+check "setup.ps1 leaves long-path policy unchanged while staging" \
+ "$(has "$SETUP_PS1" 'step "long paths" "disabled; unchanged during staging"')"
+check "setup.ps1 does not install Git while staging" \
+ "$(has "$SETUP_PS1" 'Background staging cannot install Git; retry with the foreground updater.')"
+check "setup.ps1 preserves foreground Git bootstrap" \
+ "$(has "$SETUP_PS1" 'if ($gitNeeded -or -not $StageRoot) {')"
+check "setup.ps1 keeps the staging compiler cache under the stage root" \
+ "$(has "$SETUP_PS1" 'if ($StageRoot -or $LongPathsEnabled) {')"
+
+# ── the staged activation cannot dot-source a copied Activate script ──
+# A venv copied out of $STUDIO_HOME still names the original root in its activate
+# scripts, so the staged branch sets PATH itself. Assert-VenvActivated then proves
+# `python` really resolves inside the stage.
+check "setup.sh activates the staged venv without sourcing the copy" \
+ "$(has "$SETUP_SH" 'elif [ -n "$STAGE_ROOT" ]; then')"
+check "setup.ps1 activates the staged venv without dot-sourcing the copy" \
+ "$(has "$SETUP_PS1" 'function Enter-StudioVenv {')"
+check "setup.ps1 still asserts the interpreter after activating" \
+ "$(has "$SETUP_PS1" 'Assert-VenvActivated -VenvDir $VenvDir')"
+
+echo ""
+echo "Results: $PASS passed, $FAIL failed"
+[ "$FAIL" = 0 ]
diff --git a/tests/studio/test_amd_venv_repair_loop.ps1 b/tests/studio/test_amd_venv_repair_loop.ps1
index 388f9ded115..7844c764bfa 100644
--- a/tests/studio/test_amd_venv_repair_loop.ps1
+++ b/tests/studio/test_amd_venv_repair_loop.ps1
@@ -558,8 +558,10 @@ Assert-VenvActivated -VenvDir `$Venv
# ── where it is wired in ──
# Both ends sit immediately after a non-newline token, so a CRLF checkout fails the match rather
-# than yielding an empty region every -not check would pass against.
-$_actPat = '(?s)(\$ActivateScript = Join-Path \$VenvDir "Scripts\\Activate\.ps1"\n\. \$ActivateScript\n.*?Assert-VenvActivated -VenvDir \$VenvDir\n)'
+# than yielding an empty region every -not check would pass against. The dot-source is reached
+# through Enter-StudioVenv, which picks it or the staged-root PATH activation, so the region
+# spans that helper rather than requiring the dot-source on the very next line.
+$_actPat = '(?s)(\$ActivateScript = Join-Path \$VenvDir "Scripts\\Activate\.ps1"\n.*?\. \$ActivateScript\n.*?Assert-VenvActivated -VenvDir \$VenvDir\n)'
$_act = if ($setupText -match $_actPat) { $Matches[1] } else { "" }
Check "the activation block was found" ($_act -ne "")
Check "CRLF is normalised, not tolerated" (-not (($setupText -replace "`n", "`r`n") -match $_actPat))
@@ -583,7 +585,10 @@ Check "and that one is outside the swallowing catch" (
$setupText.IndexOf('} catch { }') -lt
$setupText.LastIndexOf('Assert-VenvActivated -VenvDir $VenvDir'))
# It refuses; it does not repair, and it does not wipe a venv install.ps1 may still restore from.
-Check "the guard does not delete anything" (($_act -ne "") -and -not ($_act -match 'Remove-Item'))
+# Env: is exempt: the staged branch clears PYTHONHOME the way Activate.ps1 does, and that removes
+# a variable, not a file.
+Check "the guard does not delete anything" (
+ ($_act -ne "") -and -not ($_act -match 'Remove-Item(?!\s+Env:)'))
Write-Host ""
Write-Host "=== an installer-managed repair never moves a GPU wheel to another family ==="
diff --git a/tests/studio/test_desktop_reliability_frontend_contract.py b/tests/studio/test_desktop_reliability_frontend_contract.py
index 87994e3b126..1bf94890eda 100644
--- a/tests/studio/test_desktop_reliability_frontend_contract.py
+++ b/tests/studio/test_desktop_reliability_frontend_contract.py
@@ -141,7 +141,7 @@ def test_desktop_update_keeps_the_in_app_path_on_a_guessed_policy():
give_up = manual_branch.split("checkDesktopUpdate()", 1)[0]
# Only a resolved policy may end the check without the in-app updater.
assert "if (resolved) {" in give_up
- assert 'setStatus("idle");' in give_up
+ assert 'updateStatus("idle");' in give_up
assert "await checkDesktopUpdate();" in manual_branch
# The Rust command self-gates on the real OS, so it is safe to consult first.
manual_cmd = policy.split("async fn check_desktop_manual_update", 1)[1]
diff --git a/unsloth_cli/__init__.py b/unsloth_cli/__init__.py
index 84dfc2cd594..1029a100e19 100644
--- a/unsloth_cli/__init__.py
+++ b/unsloth_cli/__init__.py
@@ -9,6 +9,13 @@ import sys as _sys
# behaviour and must not reach into a host application that imports us.
_entry_base = _os.path.basename(_sys.argv[0]).lower() if _sys.argv else ""
_is_entry_point = _entry_base in {"unsloth", "unsloth.exe"}
+_windows_studio_mutation_entry = (
+ _sys.platform == "win32"
+ and (_is_entry_point or _entry_base == "-m")
+ and len(_sys.argv) >= 3
+ and _sys.argv[1] == "studio"
+ and _sys.argv[2] in {"setup", "update"}
+)
_streams_reconfigured = False
@@ -66,16 +73,19 @@ import typer
from importlib.metadata import version as package_version, PackageNotFoundError
-from unsloth_cli.commands.train import train
-from unsloth_cli.commands.inference import inference
-from unsloth_cli.commands.chat import chat
-from unsloth_cli.commands.start import start_app
-from unsloth_cli.commands.export import export, list_checkpoints
-from unsloth_cli.commands.studio import (
- run as studio_run,
- studio_app,
- _expand_attached_np_short,
-)
+if _windows_studio_mutation_entry:
+ from unsloth_cli.commands.studio import studio_app, _expand_attached_np_short
+else:
+ from unsloth_cli.commands.train import train
+ from unsloth_cli.commands.inference import inference
+ from unsloth_cli.commands.chat import chat
+ from unsloth_cli.commands.start import start_app
+ from unsloth_cli.commands.export import export, list_checkpoints
+ from unsloth_cli.commands.studio import (
+ run as studio_run,
+ studio_app,
+ _expand_attached_np_short,
+ )
_entry_point_prepared = False
@@ -203,32 +213,33 @@ def main(
raise typer.Exit(code = 1)
-app.command()(train)
-app.command()(inference)
-app.command()(chat)
-app.command()(export)
-app.command("list-checkpoints")(list_checkpoints)
app.add_typer(studio_app, name = "studio", help = "Unsloth Studio commands.")
-app.add_typer(
- start_app,
- name = "start",
- help = "Start a coding agent (Claude, Codex, OpenClaw, OpenCode, Hermes, Pi) against Unsloth.",
-)
-# Backwards-compatible hidden alias: `unsloth connect` routes to `unsloth start`.
-app.add_typer(
- start_app,
- name = "connect",
- hidden = True,
- help = "Deprecated alias for `unsloth start`.",
-)
-
-# Top-level `unsloth run` aliases `unsloth studio run`; same context
-# so unknown flags still pass through to llama-server.
-app.command(
- "run",
- context_settings = {
- "allow_extra_args": True,
- "ignore_unknown_options": True,
- },
- help = "Alias for `unsloth studio run`.",
-)(studio_run)
+if not _windows_studio_mutation_entry:
+ app.command()(train)
+ app.command()(inference)
+ app.command()(chat)
+ app.command()(export)
+ app.command("list-checkpoints")(list_checkpoints)
+ app.add_typer(
+ start_app,
+ name = "start",
+ help = "Start a coding agent (Claude, Codex, OpenClaw, OpenCode, Hermes, Pi) against Unsloth.",
+ )
+ # backwards-compatible hidden alias: `unsloth connect` routes to `unsloth start`.
+ app.add_typer(
+ start_app,
+ name = "connect",
+ hidden = True,
+ help = "Deprecated alias for `unsloth start`.",
+ )
+
+ # top-level `unsloth run` aliases `unsloth studio run`; same context
+ # so unknown flags still pass through to llama-server.
+ app.command(
+ "run",
+ context_settings = {
+ "allow_extra_args": True,
+ "ignore_unknown_options": True,
+ },
+ help = "Alias for `unsloth studio run`.",
+ )(studio_run)
diff --git a/unsloth_cli/_studio_runtime_gate.py b/unsloth_cli/_studio_runtime_gate.py
index a5f0cfd09be..9e9ce3eba34 100644
--- a/unsloth_cli/_studio_runtime_gate.py
+++ b/unsloth_cli/_studio_runtime_gate.py
@@ -1,7 +1,7 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-"""Coordinate Windows launches that consume the Tauri-managed Unsloth environment."""
+"""Coordinate launches that consume the Tauri-managed Unsloth environment."""
from __future__ import annotations
@@ -19,6 +19,8 @@ from typing import Iterator, Mapping
_RUNTIME_MUTEX_PREFIX = "Global\\UnslothStudioManagedEnvironment-"
_PATH_RUNTIME_MUTEX_PREFIX = "Global\\UnslothStudioManagedEnvironmentPath-"
_RUNTIME_GATE_HANDOFF_ENV = "_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF"
+_RUNTIME_GATE_ACQUIRE_ENV = "_UNSLOTH_STUDIO_RUNTIME_GATE_ACQUIRE"
+_POSIX_RUNTIME_LOCK_FILE = ".studio-runtime.lock"
class StudioRuntimeGateBusy(RuntimeError):
@@ -197,13 +199,39 @@ def _current_windows_user_sid() -> str:
@contextlib.contextmanager
-def studio_runtime_launch_guard(studio_home: Path, *, inherited: bool = False) -> Iterator[bool]:
- """Hold the shared Windows launch gate through backend admission."""
-
- if sys.platform != "win32" or inherited:
+def studio_runtime_launch_guard(
+ studio_home: Path,
+ *,
+ inherited: bool = False,
+ wait: bool = False,
+) -> Iterator[bool]:
+ """Hold the shared launch gate through backend admission."""
+
+ if inherited and wait:
+ raise ValueError("a runtime gate cannot be inherited and acquired")
+ if inherited:
yield False
return
+ if sys.platform != "win32":
+ import fcntl
+
+ studio_home.mkdir(parents = True, exist_ok = True)
+ lock_file = (studio_home / _POSIX_RUNTIME_LOCK_FILE).open("a+b")
+ try:
+ try:
+ flags = fcntl.LOCK_EX if wait else fcntl.LOCK_EX | fcntl.LOCK_NB
+ fcntl.flock(lock_file.fileno(), flags)
+ except BlockingIOError as exc:
+ raise StudioRuntimeGateBusy(str(lock_file.name)) from exc
+ yield True
+ finally:
+ try:
+ fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
+ finally:
+ lock_file.close()
+ return
+
kernel32 = ctypes.WinDLL("kernel32", use_last_error = True)
kernel32.CreateMutexW.argtypes = [
ctypes.c_void_p,
@@ -223,7 +251,8 @@ def studio_runtime_launch_guard(studio_home: Path, *, inherited: bool = False) -
if not handle:
raise ctypes.WinError(ctypes.get_last_error())
- wait_result = kernel32.WaitForSingleObject(handle, 0)
+ timeout = 0xFFFFFFFF if wait else 0
+ wait_result = kernel32.WaitForSingleObject(handle, timeout)
if wait_result not in (0x00000000, 0x00000080): # WAIT_OBJECT_0, WAIT_ABANDONED
kernel32.CloseHandle(handle)
if wait_result == 0x00000102: # WAIT_TIMEOUT
@@ -372,6 +401,10 @@ def consume_runtime_gate_handoff() -> bool:
return os.environ.pop(_RUNTIME_GATE_HANDOFF_ENV, None) == "1"
+def consume_runtime_gate_acquire() -> bool:
+ return os.environ.pop(_RUNTIME_GATE_ACQUIRE_ENV, None) == "1"
+
+
def runtime_gate_child_environment(base: Mapping[str, str] | None = None) -> dict[str, str]:
child_env = dict(os.environ if base is None else base)
child_env[_RUNTIME_GATE_HANDOFF_ENV] = "1"
diff --git a/unsloth_cli/_studio_stage.py b/unsloth_cli/_studio_stage.py
new file mode 100644
index 00000000000..abd3cc4338c
--- /dev/null
+++ b/unsloth_cli/_studio_stage.py
@@ -0,0 +1,272 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import json
+import os
+import platform
+import shutil
+import subprocess
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Callable, Optional
+
+STAGE_DIR_NAME = ".update-stage"
+STAGE_ROOT_ENV = "UNSLOTH_STUDIO_STAGE_ROOT"
+SHELL_VERSION_ENV = "UNSLOTH_TAURI_SHELL_VERSION"
+READY_MARKER = "READY.json"
+VENV_NAME = "unsloth_studio"
+HELPER_NAMES = ("node", "llama.cpp", "whisper.cpp")
+MIN_FREE_BYTES = 1 << 30
+PROBE_TIMEOUT_SECONDS = 300
+
+RELOCATABLE_SHEBANG = (
+ "#!/bin/sh\n"
+ '\'\'\'exec\' "$(dirname -- "$(realpath -- "$0")")"/\'python\' "$0" "$@"\n'
+ "' '''\n"
+)
+
+
+class StageError(RuntimeError):
+ pass
+
+
+def is_staging() -> bool:
+ return bool(os.environ.get(STAGE_ROOT_ENV))
+
+
+def runtime_root(studio_home: Path) -> Path:
+ override = (os.environ.get(STAGE_ROOT_ENV) or "").strip()
+ return Path(override) if override else studio_home
+
+
+def stage_root(studio_home: Path) -> Path:
+ return studio_home / STAGE_DIR_NAME
+
+
+def managed_helper_root(studio_home: Path) -> Path:
+ legacy = Path.home() / ".unsloth" / "studio"
+ try:
+ is_legacy = studio_home.resolve() == legacy.resolve()
+ except (OSError, ValueError):
+ is_legacy = studio_home == legacy
+ return studio_home.parent if is_legacy else studio_home
+
+
+def venv_python(venv: Path) -> Path:
+ if platform.system() == "Windows":
+ return venv / "Scripts" / "python.exe"
+ return venv / "bin" / "python"
+
+
+def _copy_command(source: Path, destination: Path) -> Optional[list[str]]:
+ system = platform.system()
+ if system == "Darwin":
+ return ["cp", "-c", "-R", str(source), str(destination)]
+ if system == "Linux":
+ return ["cp", "-a", "--reflink=auto", str(source), str(destination)]
+ return None
+
+
+def clone_tree(source: Path, destination: Path) -> None:
+ command = _copy_command(source, destination)
+ if command is not None:
+ result = subprocess.run(command, capture_output = True, text = True)
+ if result.returncode == 0:
+ return
+ shutil.rmtree(destination, ignore_errors = True)
+ shutil.copytree(source, destination, symlinks = True)
+
+
+def _is_venv_python_shebang(first_line: bytes) -> bool:
+ if not first_line.startswith(b"#!"):
+ return False
+ target = first_line[2:].strip()
+ return b"/bin/python" in target and not target.startswith(b"/usr/bin/env")
+
+
+def _is_venv_python_shell_wrapper(lines: list[bytes]) -> bool:
+ return (
+ len(lines) >= 3
+ and lines[0] == b"#!/bin/sh"
+ and lines[1].startswith(b"'''exec' ")
+ and b"/bin/python" in lines[1]
+ and b'"$0" "$@"' in lines[1]
+ and lines[2] == b"' '''"
+ )
+
+
+def make_relocatable(venv: Path, *, exclude_scripts: tuple[str, ...] = ()) -> int:
+ cfg = venv / "pyvenv.cfg"
+ lines = cfg.read_text(encoding = "utf-8").splitlines()
+ if not any(line.split("=", 1)[0].strip() == "relocatable" for line in lines):
+ lines.append("relocatable = true")
+ cfg.write_text("\n".join(lines) + "\n", encoding = "utf-8")
+ if platform.system() == "Windows":
+ return 0
+ rewritten = 0
+ for script in (venv / "bin").iterdir():
+ if script.name in exclude_scripts or script.is_symlink() or not script.is_file():
+ continue
+ data = script.read_bytes()
+ lines = data.splitlines(keepends = True)
+ if not lines:
+ continue
+ first_line = lines[0].rstrip(b"\r\n")
+ if _is_venv_python_shebang(first_line):
+ body = b"".join(lines[1:])
+ elif _is_venv_python_shell_wrapper([line.rstrip(b"\r\n") for line in lines[:3]]):
+ body = b"".join(lines[3:])
+ else:
+ continue
+ script.write_bytes(RELOCATABLE_SHEBANG.encode("utf-8") + body)
+ rewritten += 1
+ return rewritten
+
+
+def discard(root: Path) -> None:
+ shutil.rmtree(root, ignore_errors = True)
+
+
+def _run(command: list[str], *, cwd: Path, env: dict[str, str]) -> subprocess.CompletedProcess:
+ return subprocess.run(
+ command,
+ cwd = str(cwd),
+ env = env,
+ capture_output = True,
+ text = True,
+ timeout = PROBE_TIMEOUT_SECONDS,
+ )
+
+
+def installed_version(venv: Path, env: dict[str, str]) -> str:
+ result = _run(
+ [
+ str(venv_python(venv)),
+ "-I",
+ "-c",
+ "import importlib.metadata as m; print(m.version('unsloth'))",
+ ],
+ cwd = venv.parent,
+ env = env,
+ )
+ version = result.stdout.strip()
+ if result.returncode != 0 or not version:
+ raise StageError(f"staged environment has no importable unsloth: {result.stderr.strip()}")
+ return version
+
+
+def probe_cli(venv: Path, env: dict[str, str]) -> None:
+ result = _run(
+ [str(venv_python(venv)), "-I", "-X", "utf8", "-m", "unsloth_cli", "-h"],
+ cwd = venv.parent,
+ env = env,
+ )
+ if result.returncode != 0:
+ raise StageError(f"staged CLI failed to start: {result.stderr.strip()[-2000:]}")
+
+
+def console_script(venv: Path) -> Path:
+ return venv / "bin" / "unsloth"
+
+
+def probe_console_script(venv: Path, env: dict[str, str]) -> None:
+ """POSIX runs this file, not `python -m`, so it is the probe that counts.
+
+ An installer rewrites it with a shebang naming the interpreter by absolute
+ path, and activation moves the venv out of that path, so a stale one shows up
+ nowhere else. Windows is exempt: resolve_managed_cli_invocation_with runs
+ python.exe there, and quarantine can take the unsigned launcher stub off a
+ working install, so its absence would fail a stage that is fine.
+ """
+ if platform.system() == "Windows":
+ return
+ script = console_script(venv)
+ if not script.is_file():
+ raise StageError(f"staged environment has no launcher at {script}")
+ try:
+ result = _run([str(script), "-h"], cwd = venv.parent, env = env)
+ except OSError as exc:
+ # A shebang naming an interpreter that is not there fails here, not with a
+ # return code: the kernel refuses the exec.
+ raise StageError(f"staged launcher is not executable: {exc}") from exc
+ if result.returncode != 0:
+ raise StageError(f"staged launcher failed to start: {result.stderr.strip()[-2000:]}")
+
+
+def finalize_for_activation(root: Path) -> None:
+ venv = root / VENV_NAME
+ make_relocatable(venv)
+ env = child_environment(root)
+ probe_cli(venv, env)
+ probe_console_script(venv, env)
+
+
+def child_environment(root: Path) -> dict[str, str]:
+ env = dict(os.environ)
+ env[STAGE_ROOT_ENV] = str(root)
+ scripts = root / VENV_NAME / ("Scripts" if platform.system() == "Windows" else "bin")
+ env["PATH"] = str(scripts) + os.pathsep + env.get("PATH", "")
+ env.pop("PYTHONHOME", None)
+ env.pop("PYTHONPATH", None)
+ env.pop("VIRTUAL_ENV", None)
+ return env
+
+
+def run_staged_update(root: Path, args: list[str]) -> int:
+ python = venv_python(root / VENV_NAME)
+ command = [str(python), "-I", "-X", "utf8", "-m", "unsloth_cli", "studio", "update", *args]
+ return subprocess.call(command, cwd = str(root), env = child_environment(root))
+
+
+def write_ready_marker(root: Path, backend_version: str, shell_version: Optional[str]) -> Path:
+ marker = root / READY_MARKER
+ payload = {
+ "backend_version": backend_version,
+ "shell_version": shell_version,
+ "created_at": datetime.now(timezone.utc).isoformat(),
+ }
+ marker.write_text(json.dumps(payload, indent = 2) + "\n", encoding = "utf-8")
+ return marker
+
+
+def stage(
+ studio_home: Path,
+ *,
+ update_args: list[str],
+ echo: Callable[[str], None],
+ run_update: Callable[[Path, list[str]], int] = run_staged_update,
+) -> dict:
+ live = studio_home / VENV_NAME
+ if not (live / "pyvenv.cfg").is_file():
+ raise StageError(f"no managed environment at {live}")
+ root = stage_root(studio_home)
+ discard(root)
+ if root.exists():
+ raise StageError(f"could not clear the previous staging directory at {root}")
+ if shutil.disk_usage(studio_home).free < MIN_FREE_BYTES:
+ raise StageError("not enough free disk space to prepare an update")
+ root.mkdir(parents = True)
+ try:
+ echo("[TAURI:STEP] clone")
+ clone_tree(live, root / VENV_NAME)
+ helper_root = managed_helper_root(studio_home)
+ for name in HELPER_NAMES:
+ helper = helper_root / name
+ if helper.is_dir():
+ clone_tree(helper, root / name)
+ make_relocatable(root / VENV_NAME, exclude_scripts = ("unsloth",))
+ echo("[TAURI:STEP] update")
+ if run_update(root, update_args) != 0:
+ raise StageError("staged update failed")
+ echo("[TAURI:STEP] verify")
+ finalize_for_activation(root)
+ env = child_environment(root)
+ version = installed_version(root / VENV_NAME, env)
+ shell_version = (os.environ.get(SHELL_VERSION_ENV) or "").strip() or None
+ write_ready_marker(root, version, shell_version)
+ except BaseException:
+ discard(root)
+ raise
+ return {"backend_version": version, "root": str(root)}
diff --git a/unsloth_cli/commands/studio.py b/unsloth_cli/commands/studio.py
index 9399ae211a3..2e9f60becce 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -28,7 +28,7 @@ from pathlib import Path
from typing import List, Literal, Optional, Sequence, Tuple
import typer
-from unsloth_cli import _studio_deps, _studio_runtime_gate
+from unsloth_cli import _studio_deps, _studio_runtime_gate, _studio_stage
from unsloth_cli._inference import SpeculativeType
from unsloth_cli.commands import _password_prompt
@@ -289,10 +289,11 @@ def _is_application_control_block(error: OSError) -> bool:
@contextlib.contextmanager
-def _studio_runtime_launch_guard(*, inherited: bool = False):
+def _studio_runtime_launch_guard(*, inherited: bool = False, wait: bool = False):
guard = _studio_runtime_gate.studio_runtime_launch_guard(
STUDIO_HOME,
inherited = inherited,
+ wait = wait,
)
try:
acquired = guard.__enter__()
@@ -1939,6 +1940,7 @@ def studio_default(
_require_bind_host(host)
runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()
+ runtime_gate_acquire = _studio_runtime_gate.consume_runtime_gate_acquire()
_preserve_cloudflare_intent(cloudflare, secure)
# --secure requires the tunnel; force a loopback bind.
@@ -2119,29 +2121,32 @@ def studio_default(
typer.echo("Unsloth Studio not set up. Run install.sh first.")
raise typer.Exit(1)
- with _studio_deps.studio_backend_imports("unsloth studio"):
- run_mod = _load_run_module()
- run_server = run_mod.run_server
+ with _studio_runtime_launch_guard(
+ inherited = runtime_gate_handoff,
+ wait = runtime_gate_acquire,
+ ):
+ with _studio_deps.studio_backend_imports("unsloth studio"):
+ run_mod = _load_run_module()
+ run_server = run_mod.run_server
- if not silent:
- display_host = _display_host_for_bind(run_mod, host)
- typer.echo(f"Starting Unsloth Studio on http://{_url_host(display_host)}:{port}")
+ if not silent:
+ display_host = _display_host_for_bind(run_mod, host)
+ typer.echo(f"Starting Unsloth Studio on http://{_url_host(display_host)}:{port}")
- run_kwargs = dict(
- host = host,
- port = port,
- silent = silent,
- api_only = api_only,
- llama_parallel_slots = parallel,
- cloudflare = cloudflare,
- secure = secure,
- enable_tools = enable_tools,
- )
- # Forward the frontend validated before the gate (in-venv path), so the
- # in-process server serves exactly the dist we vouched for.
- if resolved_frontend is not None:
- run_kwargs["frontend_path"] = resolved_frontend
- with _studio_runtime_launch_guard(inherited = runtime_gate_handoff):
+ run_kwargs = dict(
+ host = host,
+ port = port,
+ silent = silent,
+ api_only = api_only,
+ llama_parallel_slots = parallel,
+ cloudflare = cloudflare,
+ secure = secure,
+ enable_tools = enable_tools,
+ )
+ # Forward the frontend validated before the gate (in-venv path), so the
+ # in-process server serves exactly the dist we vouched for.
+ if resolved_frontend is not None:
+ run_kwargs["frontend_path"] = resolved_frontend
run_server(**run_kwargs)
try:
@@ -3984,7 +3989,8 @@ def _fail_if_install_damaged(package_name: str = "unsloth") -> None:
is the shape behind "just re-run the installer", and it is only actionable
if the update says so.
"""
- if _studio_deps.running_outside_managed_venv((STUDIO_HOME / "unsloth_studio",)):
+ managed_venv = _studio_stage.runtime_root(STUDIO_HOME) / "unsloth_studio"
+ if _studio_deps.running_outside_managed_venv((managed_venv,)):
# This CLI does not live in the venv the update just wrote, so its own
# file list describes the wrong tree. Silence beats a wrong answer.
return
@@ -4113,11 +4119,24 @@ def update(
"--verify/--no-verify",
help = "After updating, scan installed files for damage an update cannot repair.",
),
+ stage: bool = typer.Option(
+ False,
+ "--stage",
+ hidden = True,
+ help = "Prepare the update in a copy of the environment without touching the live one.",
+ ),
):
"""Update Unsloth Studio dependencies and rebuild."""
# Re-export UNSLOTH_STUDIO_HOME for env-mode installs so the refresh
# subprocess resolves the same install root the user originally chose.
_ensure_studio_env_exported()
+ # `is True`, not truthiness: only the CLI resolves the parameter to a bool. An
+ # in-process caller that leaves it out gets typer's OptionInfo sentinel, which
+ # is truthy, and every such call would stage instead of updating.
+ if stage is True:
+ _stage_update(local = local, package = package, verbose = verbose, verify = verify)
+ return
+ staging = _studio_stage.is_staging()
# Ensure SKIP_STUDIO_BASE is not inherited from a parent install.ps1 session
os.environ.pop("SKIP_STUDIO_BASE", None)
os.environ["STUDIO_PACKAGE_NAME"] = package
@@ -4176,9 +4195,16 @@ def update(
# the gate keeps a second Unsloth process off the venv, the transaction
# keeps the launcher recoverable across the setup it wraps.
runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()
- with _studio_runtime_launch_guard(inherited = runtime_gate_handoff):
- _studio_runtime_gate.ensure_managed_environment_is_idle(STUDIO_HOME)
- with _WindowsLauncherUpdateTransaction() as launcher_update:
+ with _studio_runtime_launch_guard(inherited = runtime_gate_handoff or staging):
+ if not staging:
+ _studio_runtime_gate.ensure_managed_environment_is_idle(STUDIO_HOME)
+ # Constructed after the idle scan, which test_studio_runtime_gate pins: the
+ # transaction wraps the mutation, so nothing of it may precede the gate.
+ launcher_transaction = _WindowsLauncherUpdateTransaction()
+ if staging:
+ # A staged run writes no launcher; there is nothing to keep recoverable.
+ launcher_transaction.enabled = False
+ with launcher_transaction as launcher_update:
_run_setup_script(verbose = verbose, repo_root = repo_root)
# This deliberately runs even with --no-verify: the broad package scan
# is optional, but a successful update must leave its own launcher usable.
@@ -4187,13 +4213,39 @@ def update(
_fail_if_install_damaged(package)
# Tauri desktop owns its own bundle entries; skip CLI launcher refresh
# so a Tauri-initiated update doesn't create duplicate shortcuts.
- if os.environ.get("UNSLOTH_TAURI_UPDATE") == "1":
+ if staging or os.environ.get("UNSLOTH_TAURI_UPDATE") == "1":
if verbose:
typer.echo(" refresh-launcher skipped (Tauri update)")
return
_refresh_desktop_shortcuts(verbose = verbose)
+def _stage_update(*, local: bool, package: str, verbose: bool, verify: bool) -> None:
+ if local:
+ typer.echo("Error: --stage cannot be combined with --local.", err = True)
+ raise typer.Exit(2)
+ if _studio_stage.is_staging():
+ typer.echo("Error: --stage cannot run inside a staged update.", err = True)
+ raise typer.Exit(2)
+ args = ["--package", package]
+ if verbose:
+ args.append("--verbose")
+ if not verify:
+ args.append("--no-verify")
+ runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()
+ with _studio_runtime_launch_guard(inherited = runtime_gate_handoff):
+ try:
+ result = _studio_stage.stage(STUDIO_HOME, update_args = args, echo = typer.echo)
+ except _studio_stage.StageError as exc:
+ typer.echo(f"[TAURI:ERROR] {exc}")
+ raise typer.Exit(1)
+ except Exception as exc:
+ # convert staging exceptions to the structured error stream consumed by the desktop.
+ typer.echo(f"[TAURI:ERROR] {type(exc).__name__}: {exc}")
+ raise typer.Exit(1)
+ typer.echo(f"Staged Unsloth Studio {result['backend_version']} at {result['root']}")
+
+
class _WindowsLauncherUpdateTransaction:
"""Keep the managed Windows launcher recoverable during a Python update."""
diff --git a/unsloth_cli/tests/test_studio_update_stage.py b/unsloth_cli/tests/test_studio_update_stage.py
new file mode 100644
index 00000000000..c1c40b67bab
--- /dev/null
+++ b/unsloth_cli/tests/test_studio_update_stage.py
@@ -0,0 +1,416 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+from __future__ import annotations
+
+import json
+import os
+import platform
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+_REPO_ROOT = Path(__file__).resolve().parents[2]
+if str(_REPO_ROOT) not in sys.path:
+ sys.path.insert(0, str(_REPO_ROOT))
+
+from unsloth_cli import _studio_stage # noqa: E402
+
+
+def _make_venv(root: Path, prefix: Path | None = None) -> Path:
+ venv = root / _studio_stage.VENV_NAME
+ prefix = prefix or venv
+ (venv / "bin").mkdir(parents = True)
+ (venv / "pyvenv.cfg").write_text("home = /usr/bin\nversion_info = 3.13\n", encoding = "utf-8")
+ (venv / "bin" / "unsloth").write_text(
+ f"#!{prefix}/bin/python\nimport sys\nprint('cli')\n", encoding = "utf-8"
+ )
+ (venv / "bin" / "pip").write_text(
+ f"#!{prefix}/bin/python3.13\nprint('pip')\n", encoding = "utf-8"
+ )
+ (venv / "bin" / "activate").write_text(f"VIRTUAL_ENV='{prefix}'\n", encoding = "utf-8")
+ (venv / "bin" / "env-script").write_text("#!/usr/bin/env python\nprint(1)\n", encoding = "utf-8")
+ (venv / "bin" / "native").write_bytes(b"\x7fELF\x02\x01\x01")
+ return venv
+
+
+def test_runtime_root_follows_the_stage_override(monkeypatch, tmp_path):
+ monkeypatch.delenv(_studio_stage.STAGE_ROOT_ENV, raising = False)
+ assert _studio_stage.runtime_root(tmp_path) == tmp_path
+ assert not _studio_stage.is_staging()
+
+ monkeypatch.setenv(_studio_stage.STAGE_ROOT_ENV, str(tmp_path / "stage"))
+ assert _studio_stage.runtime_root(tmp_path) == tmp_path / "stage"
+ assert _studio_stage.is_staging()
+
+
[email protected](sys.platform == "win32", reason = "POSIX shebangs")
+def test_make_relocatable_rewrites_only_venv_python_shebangs(tmp_path):
+ venv = _make_venv(tmp_path)
+
+ rewritten = _studio_stage.make_relocatable(venv)
+
+ assert rewritten == 2
+ for name in ("unsloth", "pip"):
+ text = (venv / "bin" / name).read_text(encoding = "utf-8")
+ assert text.startswith(_studio_stage.RELOCATABLE_SHEBANG)
+ assert "realpath" in text.splitlines()[1]
+ assert (venv / "bin" / "unsloth").read_text(encoding = "utf-8").endswith("print('cli')\n")
+ assert (
+ (venv / "bin" / "env-script")
+ .read_text(encoding = "utf-8")
+ .startswith("#!/usr/bin/env python")
+ )
+ assert (venv / "bin" / "native").read_bytes() == b"\x7fELF\x02\x01\x01"
+ assert (venv / "bin" / "activate").read_text(encoding = "utf-8") == f"VIRTUAL_ENV='{venv}'\n"
+ assert "relocatable = true" in (venv / "pyvenv.cfg").read_text(encoding = "utf-8")
+
+
+def test_make_relocatable_does_not_duplicate_the_flag(tmp_path):
+ venv = _make_venv(tmp_path)
+ (venv / "pyvenv.cfg").write_text("home = /usr/bin\nrelocatable = true\n", encoding = "utf-8")
+
+ _studio_stage.make_relocatable(venv)
+
+ assert (venv / "pyvenv.cfg").read_text(encoding = "utf-8").count("relocatable") == 1
+
+
[email protected](sys.platform == "win32", reason = "POSIX shebangs")
+def test_make_relocatable_rewrites_shell_wrapper_for_path_with_spaces(tmp_path):
+ venv = _make_venv(tmp_path / "stage with spaces")
+ script = venv / "bin" / "pip"
+ script.write_text(
+ f"#!/bin/sh\n'''exec' '{venv}/bin/python' \"$0\" \"$@\"\n' '''\nprint('pip')\n",
+ encoding = "utf-8",
+ )
+
+ assert _studio_stage.make_relocatable(venv) == 2
+
+ text = script.read_text(encoding = "utf-8")
+ assert text.startswith(_studio_stage.RELOCATABLE_SHEBANG)
+ assert str(venv) not in text
+ assert text.endswith("print('pip')\n")
+
+
+def test_clone_tree_copies_symlinks_as_symlinks(tmp_path):
+ source = tmp_path / "src"
+ (source / "bin").mkdir(parents = True)
+ (source / "bin" / "real").write_text("x", encoding = "utf-8")
+ os.symlink("real", source / "bin" / "link")
+
+ _studio_stage.clone_tree(source, tmp_path / "dst")
+
+ assert (tmp_path / "dst" / "bin" / "link").is_symlink()
+ assert (tmp_path / "dst" / "bin" / "link").read_text(encoding = "utf-8") == "x"
+
+
+def test_managed_helper_root_matches_default_and_custom_layout(monkeypatch, tmp_path):
+ monkeypatch.setattr(_studio_stage.Path, "home", lambda: tmp_path)
+
+ assert _studio_stage.managed_helper_root(tmp_path / ".unsloth" / "studio") == (
+ tmp_path / ".unsloth"
+ )
+ assert _studio_stage.managed_helper_root(tmp_path / "custom") == tmp_path / "custom"
+
+
+def test_stage_builds_a_ready_marker_from_a_successful_update(monkeypatch, tmp_path):
+ home = tmp_path / "studio"
+ _make_venv(home)
+ for name in _studio_stage.HELPER_NAMES:
+ (home / name).mkdir()
+ (home / name / "tag").write_text("live", encoding = "utf-8")
+ monkeypatch.setenv(_studio_stage.SHELL_VERSION_ENV, "0.1.900-beta")
+ seen: dict = {}
+
+ def fake_update(root: Path, args: list[str]) -> int:
+ seen["root"] = root
+ seen["args"] = args
+ return 0
+
+ monkeypatch.setattr(_studio_stage, "installed_version", lambda venv, env: "2026.9.1")
+ monkeypatch.setattr(_studio_stage, "probe_cli", lambda venv, env: None)
+ monkeypatch.setattr(_studio_stage, "probe_console_script", lambda venv, env: None)
+ echoed: list[str] = []
+
+ result = _studio_stage.stage(
+ home, update_args = ["--package", "unsloth"], echo = echoed.append, run_update = fake_update
+ )
+
+ root = home / _studio_stage.STAGE_DIR_NAME
+ assert seen == {"root": root, "args": ["--package", "unsloth"]}
+ assert result == {"backend_version": "2026.9.1", "root": str(root)}
+ marker = json.loads((root / _studio_stage.READY_MARKER).read_text(encoding = "utf-8"))
+ assert marker["backend_version"] == "2026.9.1"
+ assert marker["shell_version"] == "0.1.900-beta"
+ assert (root / _studio_stage.VENV_NAME / "pyvenv.cfg").is_file()
+ for name in _studio_stage.HELPER_NAMES:
+ assert (root / name / "tag").read_text(encoding = "utf-8") == "live"
+ assert (
+ (home / _studio_stage.VENV_NAME / "bin" / "unsloth")
+ .read_text(encoding = "utf-8")
+ .startswith(f"#!{home / _studio_stage.VENV_NAME}/bin/python")
+ )
+ assert echoed == ["[TAURI:STEP] clone", "[TAURI:STEP] update", "[TAURI:STEP] verify"]
+
+
+def test_stage_discards_the_tree_when_the_update_fails(monkeypatch, tmp_path):
+ home = tmp_path / "studio"
+ _make_venv(home)
+ monkeypatch.delenv(_studio_stage.SHELL_VERSION_ENV, raising = False)
+
+ with pytest.raises(_studio_stage.StageError, match = "staged update failed"):
+ _studio_stage.stage(
+ home, update_args = [], echo = lambda _: None, run_update = lambda root, args: 1
+ )
+
+ assert not (home / _studio_stage.STAGE_DIR_NAME).exists()
+ assert (home / _studio_stage.VENV_NAME / "pyvenv.cfg").is_file()
+
+
+def test_stage_discards_the_tree_when_verification_fails(monkeypatch, tmp_path):
+ home = tmp_path / "studio"
+ _make_venv(home)
+
+ def broken(venv: Path, env: dict) -> str:
+ raise _studio_stage.StageError("no unsloth")
+
+ monkeypatch.setattr(_studio_stage, "finalize_for_activation", lambda root: None)
+ monkeypatch.setattr(_studio_stage, "installed_version", broken)
+
+ with pytest.raises(_studio_stage.StageError, match = "no unsloth"):
+ _studio_stage.stage(
+ home, update_args = [], echo = lambda _: None, run_update = lambda root, args: 0
+ )
+
+ assert not (home / _studio_stage.STAGE_DIR_NAME).exists()
+
+
[email protected](sys.platform == "win32", reason = "POSIX console scripts")
+def test_same_version_stage_preserves_the_launcher_until_update_verification(monkeypatch, tmp_path):
+ home = tmp_path / "studio"
+ live_venv = _make_venv(home)
+ live_launcher = (live_venv / "bin" / "unsloth").read_bytes()
+
+ def same_version_update(root: Path, args: list[str]) -> int:
+ staged_launcher = root / _studio_stage.VENV_NAME / "bin" / "unsloth"
+ assert staged_launcher.read_bytes() == live_launcher
+ return 0
+
+ monkeypatch.setattr(_studio_stage, "installed_version", lambda venv, env: "2026.8.22")
+ monkeypatch.setattr(_studio_stage, "probe_cli", lambda venv, env: None)
+ monkeypatch.setattr(_studio_stage, "probe_console_script", lambda venv, env: None)
+
+ _studio_stage.stage(home, update_args = [], echo = lambda _: None, run_update = same_version_update)
+
+ staged_launcher = (
+ home / _studio_stage.STAGE_DIR_NAME / _studio_stage.VENV_NAME / "bin" / "unsloth"
+ )
+ assert staged_launcher.read_text(encoding = "utf-8").startswith(_studio_stage.RELOCATABLE_SHEBANG)
+
+
+def test_stage_refuses_without_a_managed_environment(tmp_path):
+ with pytest.raises(_studio_stage.StageError, match = "no managed environment"):
+ _studio_stage.stage(
+ tmp_path, update_args = [], echo = lambda _: None, run_update = lambda root, args: 0
+ )
+
+
+def test_stage_refuses_when_the_previous_stage_could_not_be_cleared(monkeypatch, tmp_path):
+ _make_venv(tmp_path)
+ stale = _studio_stage.stage_root(tmp_path)
+ (stale / "leftover").mkdir(parents = True)
+ # discard() swallows its errors, so a locked or undeletable tree would otherwise
+ # be staged into and shipped as if it were a fresh clone.
+ monkeypatch.setattr(_studio_stage, "discard", lambda root: None)
+
+ with pytest.raises(_studio_stage.StageError, match = "could not clear"):
+ _studio_stage.stage(
+ tmp_path, update_args = [], echo = lambda _: None, run_update = lambda root, args: 0
+ )
+ assert (stale / "leftover").is_dir()
+
+
+def test_child_environment_points_the_staged_cli_at_the_stage_root(monkeypatch, tmp_path):
+ monkeypatch.setenv("VIRTUAL_ENV", "/elsewhere")
+ monkeypatch.setenv("PYTHONHOME", "/elsewhere")
+ monkeypatch.setenv("PYTHONPATH", "/foreign/checkout")
+
+ env = _studio_stage.child_environment(tmp_path)
+
+ assert env[_studio_stage.STAGE_ROOT_ENV] == str(tmp_path)
+ assert env["PATH"].split(os.pathsep)[0] == str(
+ tmp_path
+ / _studio_stage.VENV_NAME
+ / ("Scripts" if platform.system() == "Windows" else "bin")
+ )
+ assert "VIRTUAL_ENV" not in env
+ assert "PYTHONHOME" not in env
+ assert "PYTHONPATH" not in env
+
+
+def test_staged_python_commands_use_isolated_mode(monkeypatch, tmp_path):
+ venv = _make_venv(tmp_path)
+ commands: list[list[str]] = []
+
+ def fake_run(command, *, cwd, env):
+ commands.append(command)
+ return type("Result", (), {"returncode": 0, "stdout": "2026.9.1\n", "stderr": ""})()
+
+ monkeypatch.setattr(_studio_stage, "_run", fake_run)
+ _studio_stage.installed_version(venv, {})
+ _studio_stage.probe_cli(venv, {})
+
+ assert all(command[1] == "-I" for command in commands)
+
+
+def test_nested_update_uses_isolated_mode(monkeypatch, tmp_path):
+ _make_venv(tmp_path)
+ captured: dict = {}
+
+ def fake_call(command, *, cwd, env):
+ captured.update(command = command, cwd = cwd, env = env)
+ return 0
+
+ monkeypatch.setenv("PYTHONPATH", "/foreign/checkout")
+ monkeypatch.setattr(_studio_stage.subprocess, "call", fake_call)
+
+ assert _studio_stage.run_staged_update(tmp_path, ["--verbose"]) == 0
+ assert captured["command"][1:3] == ["-I", "-X"]
+ assert "PYTHONPATH" not in captured["env"]
+
+
+def test_update_stage_flag_refuses_local(monkeypatch):
+ from typer.testing import CliRunner
+ from unsloth_cli.commands import studio as studio_mod
+
+ monkeypatch.delenv(_studio_stage.STAGE_ROOT_ENV, raising = False)
+ result = CliRunner().invoke(studio_mod.studio_app, ["update", "--stage", "--local"])
+
+ assert result.exit_code == 2
+ assert "--stage cannot be combined with --local" in result.output
+
+
+def test_update_stage_reports_a_structured_error(monkeypatch):
+ from typer.testing import CliRunner
+ from unsloth_cli.commands import studio as studio_mod
+
+ monkeypatch.delenv(_studio_stage.STAGE_ROOT_ENV, raising = False)
+
+ def failing_stage(home, *, update_args, echo):
+ raise _studio_stage.StageError("clone failed")
+
+ monkeypatch.setattr(_studio_stage, "stage", failing_stage)
+ result = CliRunner().invoke(studio_mod.studio_app, ["update", "--stage"])
+
+ assert result.exit_code == 1
+ assert "[TAURI:ERROR] clone failed" in result.output
+
+
+def test_update_stage_passes_the_update_options_through(monkeypatch):
+ from typer.testing import CliRunner
+ from unsloth_cli.commands import studio as studio_mod
+
+ monkeypatch.delenv(_studio_stage.STAGE_ROOT_ENV, raising = False)
+ captured: dict = {}
+
+ def fake_stage(home, *, update_args, echo):
+ captured["home"] = home
+ captured["args"] = update_args
+ return {"backend_version": "2026.9.1", "root": "/stage"}
+
+ monkeypatch.setattr(_studio_stage, "stage", fake_stage)
+ result = CliRunner().invoke(
+ studio_mod.studio_app,
+ ["update", "--stage", "--verbose", "--no-verify", "--package", "unsloth"],
+ )
+
+ assert result.exit_code == 0, result.output
+ assert captured["home"] == studio_mod.STUDIO_HOME
+ assert captured["args"] == ["--package", "unsloth", "--verbose", "--no-verify"]
+ assert "Staged Unsloth Studio 2026.9.1" in result.output
+
+
+def test_update_stage_reports_an_unexpected_failure_as_a_tauri_error(monkeypatch):
+ from typer.testing import CliRunner
+ from unsloth_cli.commands import studio as studio_mod
+
+ monkeypatch.delenv(_studio_stage.STAGE_ROOT_ENV, raising = False)
+
+ def failing_stage(home, *, update_args, echo):
+ # model an unlabeled full-disk staging failure.
+ raise OSError(28, "No space left on device")
+
+ monkeypatch.setattr(_studio_stage, "stage", failing_stage)
+ result = CliRunner().invoke(studio_mod.studio_app, ["update", "--stage"])
+
+ assert result.exit_code == 1
+ assert "[TAURI:ERROR] OSError:" in result.output
+ assert "No space left on device" in result.output
+
+
[email protected](sys.platform == "win32", reason = "POSIX console scripts")
+def test_stage_relocates_the_launcher_the_update_rewrote(monkeypatch, tmp_path):
+ home = tmp_path / "studio"
+ _make_venv(home)
+ stage_venv = home / _studio_stage.STAGE_DIR_NAME / _studio_stage.VENV_NAME
+
+ def reinstalling_update(root: Path, args: list[str]) -> int:
+ # What pip/uv do on every upgrade: rewrite the console script with the
+ # interpreter named by absolute path, inside the stage.
+ (root / _studio_stage.VENV_NAME / "bin" / "unsloth").write_text(
+ f"#!{root / _studio_stage.VENV_NAME}/bin/python\nprint('cli')\n", encoding = "utf-8"
+ )
+ return 0
+
+ monkeypatch.setattr(_studio_stage, "installed_version", lambda venv, env: "2026.9.1")
+ monkeypatch.setattr(_studio_stage, "probe_cli", lambda venv, env: None)
+ monkeypatch.setattr(_studio_stage, "probe_console_script", lambda venv, env: None)
+
+ _studio_stage.stage(home, update_args = [], echo = lambda _: None, run_update = reinstalling_update)
+
+ launcher = (stage_venv / "bin" / "unsloth").read_text(encoding = "utf-8")
+ # Activation moves the venv out of .update-stage, so an absolute shebang into
+ # it would leave the activated backend unable to start at all.
+ assert launcher.startswith(_studio_stage.RELOCATABLE_SHEBANG)
+ assert str(_studio_stage.STAGE_DIR_NAME) not in launcher.splitlines()[1]
+
+
[email protected](sys.platform == "win32", reason = "POSIX console scripts")
+def test_probe_console_script_rejects_a_launcher_that_cannot_start(tmp_path):
+ venv = _make_venv(tmp_path)
+ launcher = venv / "bin" / "unsloth"
+ launcher.write_text("#!/nonexistent/python\n", encoding = "utf-8")
+ launcher.chmod(0o755)
+
+ with pytest.raises(_studio_stage.StageError, match = "launcher"):
+ _studio_stage.probe_console_script(venv, dict(os.environ))
+
+
[email protected](sys.platform == "win32", reason = "POSIX console scripts")
+def test_probe_console_script_accepts_a_relocated_launcher(tmp_path):
+ venv = _make_venv(tmp_path)
+ (venv / "bin" / "python").write_text("#!/bin/sh\nexit 0\n", encoding = "utf-8")
+ (venv / "bin" / "python").chmod(0o755)
+ _studio_stage.make_relocatable(venv)
+ (venv / "bin" / "unsloth").chmod(0o755)
+
+ _studio_stage.probe_console_script(venv, dict(os.environ))
+
+
[email protected](sys.platform == "win32", reason = "POSIX console scripts")
+def test_activation_finalizer_repairs_a_launcher_written_by_an_old_outer_stage(tmp_path):
+ stage_root = tmp_path / "studio" / _studio_stage.STAGE_DIR_NAME
+ venv = _make_venv(stage_root)
+ python = venv / "bin" / "python"
+ python.write_text("#!/bin/sh\nexit 0\n", encoding = "utf-8")
+ python.chmod(0o755)
+ (venv / "bin" / "unsloth").chmod(0o755)
+
+ _studio_stage.finalize_for_activation(stage_root)
+ live = tmp_path / "studio" / _studio_stage.VENV_NAME
+ venv.rename(live)
+
+ result = subprocess.run([str(live / "bin" / "unsloth"), "-h"], check = False)
+ assert result.returncode == 0