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: remove the background staged desktop update and return to the classic update (#10604)

Daniel Hanf9acb7069d54
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsx
index c653cbab7bd..6209254ec94 100644
--- a/studio/frontend/src/app/provider.tsx
+++ b/studio/frontend/src/app/provider.tsx
@@ -79,17 +79,11 @@ type TauriMonitor = NonNullable<
// Keep in step with MOBILE_BREAKPOINT in hooks/use-mobile.ts.
const MIN_DESKTOP_LAYOUT_WIDTH = 768;
-// Room the corner rail keeps around its cards so its overflow clip does not cut
-// their shadows off (#9246). Sized off the rendered blur, not the radius:
-// below, dark's 0 8px 28px -6px is one level of #181818 by 16px and light's is
-// one level of white by 8px; above, light ends by 6px and dark is under a level
-// by 8px. The rail sits on `bottom-0` and its bottom padding carries the cards
-// back up, so they still land 16px off the corner.
+// Room the corner rail keeps around its cards so its overflow clip does not cut their shadows off (#9246).
const STACK_SHADOW_GUTTER_BOTTOM = 16;
const STACK_SHADOW_GUTTER_TOP = 8;
-// Logical px per CSS px: webview zoom above the display scale (Windows text
-// scaling); 1 if none.
+// Logical px per CSS px: webview zoom above the display scale; 1 if none.
function logicalPerCssPx(monitorScale: number): number {
if (typeof window === "undefined" || !(monitorScale > 0)) return 1;
const ratio = window.devicePixelRatio / monitorScale;
@@ -117,7 +111,6 @@ function delay(milliseconds: number): Promise<void> {
return new Promise((resolve) => window.setTimeout(resolve, milliseconds));
}
-/** Watches native geometry changes that may arrive after a restore call resolves. */
async function observeWindowLayout(
win: TauriWindow,
isCurrent: WindowLayoutGuard,
@@ -183,7 +176,6 @@ function measureTauriWindowLayout(
);
}
-/** Sizes the window and centers it inside the work area. */
async function placeWindow(
win: TauriWindow,
{ LogicalSize, PhysicalPosition }: WindowModule,
@@ -215,14 +207,12 @@ async function showSetupWindow(isCurrent: WindowLayoutGuard): Promise<void> {
const win = windowModule.getCurrentWindow();
await invoke("reset_app_window_layout_initialized");
if (!isCurrent()) return;
- // Clear app-mode constraints before showing the smaller setup window.
await win.setSizeConstraints(null);
if (!isCurrent()) return;
await win.setResizable(false);
if (!isCurrent()) return;
const measured = await measureTauriWindowLayout(windowModule, win, isCurrent);
if (!measured) return;
- // Keep the non-resizable setup window fully visible.
const setupSize = fitWindowSize(
PREFERRED_SETUP_WINDOW_SIZE,
measured.bounds.maximum,
@@ -245,7 +235,6 @@ async function enforceWindowSizeBounds(
[win.innerSize(), win.scaleFactor(), win.isMaximized(), win.isFullscreen()],
);
if (!isCurrent()) return;
- // Let the window manager size maximized and fullscreen windows.
if (isMaximized || isFullscreen) return;
const currentSize = {
@@ -273,10 +262,7 @@ async function applyAppWindowLayout(
if (!isCurrent()) return;
const win = windowModule.getCurrentWindow();
- // Setup-window activity may create plugin state before the full app is ever
- // shown, so use a dedicated full-app marker to decide whether restoration is
- // appropriate. Keep checking plugin state so a missing/corrupt state file
- // falls back to a monitor-safe centered layout.
+ // Setup-window activity can create plugin state before the full app is shown, so use a dedicated marker.
const [hasInitializedAppLayout, hasSavedState] = await Promise.all([
invoke<boolean>("has_initialized_app_window_layout"),
invoke<boolean>("has_saved_window_state"),
@@ -297,14 +283,11 @@ async function applyAppWindowLayout(
// Subscribe before restoring so native events cannot race listener setup.
layoutObserver = await observeWindowLayout(win, isCurrent);
if (!layoutObserver) return;
- // Subsequent launch: plugin restores size/position/maximized, with built-in
- // off-screen protection for positions saved on a now-disconnected display.
await restoreStateCurrent(
StateFlags.SIZE | StateFlags.POSITION | StateFlags.MAXIMIZED,
);
if (!isCurrent()) return;
} else {
- // First launch: fit to the current work area and center.
const cssSafeLogicalWidth = measured.monitor
? Math.round(
MIN_DESKTOP_LAYOUT_WIDTH *
@@ -410,25 +393,12 @@ function TauriUpdateLayer({
onCopyDiagnostics={update.copyDiagnostics}
/>
) : (
- // Capped like the browser stack: the download panel shares it, so both must fit.
<div
- // Scrolls at the cap rather than spilling cards off screen: at a large
- // type size the banner floors alone exceed it. Wheel over a card scrolls
- // this box and focus scrolls into it, so the fold is reachable while the
- // rail stays click-through.
- // The gutter keeps the card shadows out of that clip: across, cancelled
- // by the negative margin; below and above, by the block padding. The
- // cards still land on 16px, since the box sits on the floor and the
- // bottom gutter carries them back up.
+ // Scrolls at the cap rather than spilling cards off screen; the gutter keeps the card shadows out of that clip.
className="pointer-events-none fixed bottom-0 right-4 -mx-3 flex max-h-[calc(100dvh_-_8px)] flex-col items-end gap-2 overflow-y-auto overflow-x-hidden overscroll-contain px-3"
- // The rail is measured from the outside, per card, by
- // tests/studio/playwright_update_banner_layout.py. Reaching it through
- // whichever banner happens to be up finds nothing when none is, which is
- // exactly the state the download panel has to be judged in.
+ // Measured from the outside, per card, by tests/studio/playwright_update_banner_layout.py.
data-testid="overlay-rail"
- // Block gutter in px, never a spacing utility: those are rem, and at any
- // root but 16px the cards would drift off the corner. Across stays a
- // utility, since px-3 and -mx-3 cancel whatever a rem is worth.
+ // Block gutter in px, never a spacing utility: those are rem, and the cards would drift off the corner.
style={{
paddingTop: STACK_SHADOW_GUTTER_TOP,
paddingBottom: STACK_SHADOW_GUTTER_BOTTOM,
@@ -438,8 +408,6 @@ function TauriUpdateLayer({
<UpdateBanner
status={update.status}
info={update.info}
- preparation={update.preparation}
- logs={update.logs}
dismissed={update.dismissed}
lastFailure={update.lastFailure}
isExternalServer={isExternalServer}
@@ -512,8 +480,7 @@ const CUSTOM_CHROME_STYLE = {
"--studio-window-control-inset": "112px",
} as CSSProperties;
-// Mirror the titlebar heights onto <html>: the styles above sit on a wrapper
-// div, so overlays portalled into document.body would read them as empty.
+// Mirror the titlebar heights onto <html>: overlays portalled into document.body read the wrapper styles as empty.
function DesktopChromeVarsEffect({
usesCustomTitlebar,
usesNativeMacTitlebar,
@@ -530,8 +497,7 @@ function DesktopChromeVarsEffect({
set("--studio-custom-titlebar-height", usesCustomTitlebar ? "34px" : null);
set("--studio-mac-titlebar-height", usesNativeMacTitlebar ? "34px" : null);
set("--studio-window-control-inset", usesCustomTitlebar ? "112px" : null);
- // How far body-portaled surfaces (dialogs, alert dialogs) must stay clear of the
- // top: either titlebar paints over them, and neither inherits the wrapper's style.
+ // How far body-portaled surfaces must stay clear of the top: either titlebar paints over them.
set(
"--studio-window-chrome-top",
usesCustomTitlebar || usesNativeMacTitlebar ? "34px" : null,
@@ -566,13 +532,8 @@ function TauriWrapper({ children }: { children: ReactNode }) {
startRepair,
} = useTauriBackend();
- // Settings' manual repair reruns the INSTALLER, not `studio update`: an update reuses the
- // environment it finds, so a venv whose PyTorch was replaced by a CPU-only wheel comes back
- // from a successful update still CPU-only.
- //
- // Through a ref, not a dependency: startRepair is a plain function declaration rebuilt on
- // every render, so listing it would give the context a new identity on each status tick and
- // pinning it with [] would freeze the first render's closure.
+ // Settings' manual repair reruns the INSTALLER, not `studio update`, so a CPU-only venv is rebuilt rather than reused.
+ // Through a ref, not a dependency: startRepair is rebuilt on every render.
const startRepairRef = useRef(startRepair);
startRepairRef.current = startRepair;
const repairController = useMemo(
@@ -616,8 +577,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
if (!payload || disposed) return;
stopListening?.();
stopListening = undefined;
- // Native tray reveal focuses the window. Re-run the deferred layout now
- // that currentMonitor() can resolve the restored display.
+ // Native tray reveal focuses the window; re-run the deferred layout now that currentMonitor() resolves.
launchedHidden = Promise.resolve(false);
appliedWindowModeRef.current = null;
setWindowRevealRevision((revision) => revision + 1);
@@ -633,7 +593,6 @@ function TauriWrapper({ children }: { children: ReactNode }) {
};
}, []);
- // Keep the Tauri window hidden until setup or app layout is ready.
useEffect(() => {
if (!isTauri) return;
@@ -656,7 +615,6 @@ function TauriWrapper({ children }: { children: ReactNode }) {
nextMode === "setup" ? showSetupWindow : applyAppWindowLayout;
applyWindowMode(isCurrent).catch(async () => {
if (!isCurrent()) return;
- // On failure, at minimum make the window visible and resizable so user can fix manually.
try {
await showWindowFallback();
} catch {
@@ -728,27 +686,15 @@ function TauriWrapper({ children }: { children: ReactNode }) {
return (
<>
{children}
- {/* One bottom-right stack so overlays never overlap: download panel at the
- corner, banners above, each owning its width. */}
- {/* Capped to the viewport, or a long download list plus expanded notes
- pushes the top of the stack off screen. */}
+ {/* One bottom-right stack so overlays never overlap. */}
+ {/* Capped to the viewport: a long download list plus expanded notes would
+ push the top of the stack off screen. */}
<div
- // Scrolls at the cap rather than spilling cards off screen: at a
- // large type size the banner floors alone exceed it. Wheel over a
- // card scrolls this box and focus scrolls into it, so the fold is
- // reachable while the rail stays click-through.
- // The gutter keeps the card shadows out of that clip: across,
- // cancelled by the negative margin; below and above, by the block
- // padding. The cards still land on 16px, since the box sits on the
- // floor and the bottom gutter carries them back up.
+ // Scrolls at the cap rather than spilling cards off screen; the gutter keeps the card shadows out of that clip.
className="pointer-events-none fixed bottom-0 right-4 -mx-3 flex max-h-[calc(100dvh_-_8px)] flex-col items-end gap-2 overflow-y-auto overflow-x-hidden overscroll-contain px-3"
- // The rail is measured from the outside, per card, by
- // tests/studio/playwright_update_banner_layout.py. Reaching it through
- // whichever banner happens to be up finds nothing when none is, which is
- // exactly the state the download panel has to be judged in.
+ // Measured from the outside, per card, by tests/studio/playwright_update_banner_layout.py.
data-testid="overlay-rail"
- // Block gutter in px, never a spacing utility: those are rem, and at
- // any root but 16px the cards would drift off the corner.
+ // Block gutter in px, never a spacing utility: those are rem, and the cards would drift off the corner.
style={{
paddingTop: STACK_SHADOW_GUTTER_TOP,
paddingBottom: STACK_SHADOW_GUTTER_BOTTOM,
@@ -764,8 +710,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
enabled={!WEB_UPDATE_HIDDEN_ROUTES.has(pathname)}
/>
<DownloadManagerPanel positioned={false} />
- {/* Last in the stack, so the persistent card sits at the corner and the
- transient banners above it never cover it. */}
+ {/* Last in the stack, so the persistent card sits at the corner. */}
<LoadedModelsIndicator positioned={false} />
</div>
</>
@@ -808,9 +753,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
/>
);
- // Over the shell, not instead of it: ClosingScreen covers the app and the update layer
- // alike, and a declined quit puts the user back where they were rather than remounting
- // the tree under them.
+ // Over the shell, not instead of it: a declined quit must not remount the tree.
const content = (
<TauriRepairContext.Provider value={repairController}>
{shell}
@@ -826,8 +769,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
);
if (!usesCustomTitlebar) {
- // macOS desktop uses the native titlebar and returns here before the
- // custom-titlebar branch, so mount the updater banner on this path too.
+ // macOS returns here before the custom-titlebar branch, so mount the updater banner too.
if (usesNativeMacTitlebar) {
return (
<div
@@ -880,11 +822,7 @@ function TauriWrapper({ children }: { children: ReactNode }) {
);
}
-/**
- * Mirrors the appearance customization store onto <html> (inline CSS vars,
- * classes, attributes). Colors are per resolved light/dark mode, so re-apply
- * whenever either the customization or the resolved theme changes.
- */
+/** Mirrors the appearance customization store onto <html>; colors are per resolved light/dark mode. */
function AppearanceCustomizationEffect() {
const { theme, resolved } = useTheme();
const customization = useAppearanceCustomStore((s) => s.customization);
@@ -918,8 +856,6 @@ export function AppProvider({ children }: AppProviderProps) {
const reduceMotion = useAppearanceCustomStore(
(s) => s.customization.reduceMotion,
);
- // A start toast describes the surface it was raised on, and lasts 8s from a
- // root-level Toaster; see dismissStartToasts for what it lands on otherwise.
useEffect(() => {
dismissStartToasts();
}, [pathname]);
@@ -935,8 +871,6 @@ export function AppProvider({ children }: AppProviderProps) {
visibleToasts={2}
expand={true}
closeButton={true}
- // Header routes clear their controls. Desktop chrome also stays clear,
- // except where a macOS page header overlays the native titlebar.
offset={toastOffsets.default}
mobileOffset={toastOffsets.mobile}
/>
diff --git a/studio/frontend/src/components/tauri/update-banner.tsx b/studio/frontend/src/components/tauri/update-banner.tsx
index 0e5493d73f3..c796c7d45c2 100644
--- a/studio/frontend/src/components/tauri/update-banner.tsx
+++ b/studio/frontend/src/components/tauri/update-banner.tsx
@@ -2,7 +2,6 @@
// 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,
@@ -11,22 +10,14 @@ 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 { ChevronDown, CircleAlert, Download } from "lucide-react";
+import { 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;
@@ -52,8 +43,6 @@ function formatVersion(version: string | null | undefined): string {
export function UpdateBanner({
status,
info,
- preparation = INITIAL_PREPARATION,
- logs = [],
dismissed,
lastFailure,
isExternalServer = false,
@@ -70,13 +59,7 @@ 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";
@@ -86,7 +69,6 @@ export function UpdateBanner({
const currentVersion = formatVersion(info?.currentVersion);
const latestVersion = formatVersion(info?.version);
const Icon = showFailure ? CircleAlert : Download;
- // The Unsloth version offered. Not a notes key; it scopes the expanded state.
const notesTargetVersion = info?.version?.replace(LEADING_V, "") ?? null;
const notesOpen =
notesTargetVersion !== null && notesVersion === notesTargetVersion;
@@ -115,113 +97,24 @@ 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 }}
transition={{ duration: 0.35, ease: EASE_OUT_QUART }}
className={cn(
- // Wider than the other overlays: notes preview plus three buttons.
positioned
? "fixed bottom-4 right-4 z-[9999] w-[calc(100vw-2rem)] max-w-[448px]"
: cn(
"pointer-events-auto flex w-[calc(100vw-2rem)] max-w-[448px] shrink-0 flex-col",
- // Only rendered notes may shrink in the capped rail. Without
- // them, shrink-0 keeps the compact card at its natural height.
+ // Only rendered notes may shrink in the capped rail.
"has-[[data-slot=update-release-notes]]:min-h-[calc(117px+93px*var(--ui-font-scale,1))] has-[[data-slot=update-release-notes]]:shrink max-[383px]:has-[[data-slot=update-release-notes]]:min-h-[calc(24px+224px*var(--ui-font-scale,1))]",
),
)}
data-testid="tauri-update-banner"
>
- {/* Paint the full floor even when the notes content is short. */}
+ {/* Paint the full floor even when the notes are short. */}
<div className="relative flex max-h-[calc(100dvh_-_2rem)] min-h-0 grow flex-col overflow-hidden rounded-[24px] bg-white px-5 pb-4 pt-5 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)]">
<button
type="button"
@@ -271,7 +164,7 @@ export function UpdateBanner({
? "Open the GitHub release page to install the Linux package"
: isExternalServer
? "Run `unsloth studio update` from your terminal"
- : "Prepares in the background. You keep working and restart when it is ready"}
+ : "A new app update is available"}
</p>
</div>
</div>
@@ -292,7 +185,6 @@ export function UpdateBanner({
<div
className={cn(
- // Wraps on a narrow card, never compresses on a short one.
"mt-4 flex shrink-0 flex-wrap items-center gap-x-1 gap-y-2",
!showFailure && notesTargetVersion
? "justify-between"
@@ -303,7 +195,6 @@ export function UpdateBanner({
<Button
size="sm"
variant="ghost"
- // same type size as the action buttons
className="-ml-2 h-auto whitespace-nowrap rounded-full px-2.5 py-2 text-ui-13 font-medium text-foreground"
onClick={() =>
setNotesVersion(notesOpen ? null : notesTargetVersion)
@@ -346,7 +237,6 @@ export function UpdateBanner({
</Button>
</>
) : (
- // wrap + right-align so the action pair stays together
<div className="flex flex-wrap items-center justify-end gap-x-1 gap-y-2">
<Button
size="sm"
@@ -369,11 +259,7 @@ export function UpdateBanner({
)}
</div>
{(manualMessage || manualReport) && (
- // The clipboard fallback, and the one region of the failure card
- // that may give up height. The card is capped at the viewport and
- // clips, and the rail cannot scroll to what that cap hides, so
- // without a scroller here the report the reader is being asked to
- // select and copy is the part that goes missing in a short window.
+ // The one region that may give up height: the card is capped and clips, and the rail cannot scroll to it.
<div
className="hover-scrollbar min-h-0 flex-1 overflow-y-auto overscroll-contain"
data-testid="tauri-update-manual-report"
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 dbf2ac6293f..fc7c7c12ed6 100644
--- a/studio/frontend/src/features/settings/components/desktop-update-control.tsx
+++ b/studio/frontend/src/features/settings/components/desktop-update-control.tsx
@@ -4,7 +4,6 @@
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";
@@ -12,7 +11,6 @@ function formatDesktopVersion(version: string): string {
return version.startsWith("v") ? version : `v${version}`;
}
-/** Explains the automatic check, so the button does not read as the only path. */
export function DesktopUpdateNote(): ReactElement | null {
const t = useT();
const update = useTauriUpdateController();
@@ -24,24 +22,18 @@ export function DesktopUpdateNote(): ReactElement | null {
);
}
-// Lives in General, under the version rows it acts on: that is the tab the
-// settings dialog opens on. Desktop-only, outside Tauri there is no controller
-// in context and the row renders nothing.
+// Lives in General, under the version rows it acts on. Desktop-only: outside Tauri there is no controller.
export function DesktopUpdateControl(): ReactElement | null {
const t = useT();
const update = useTauriUpdateController();
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 || preparing;
+ const busy = checking || inFlight;
const available = update.info !== null && !checking;
const checkFailed = update.checkError !== null && !available;
@@ -58,17 +50,10 @@ export function DesktopUpdateControl(): ReactElement | null {
? t("settings.about.update.desktopExternalServer")
: update.updatePolicyMode === "manual_linux_package"
? t("settings.about.update.desktopManualInstall")
- : fastRestart
- ? t("settings.about.update.desktopReadyToRestartDescription")
- : ready
- ? t("settings.about.update.desktopReadyToInstallDescription")
- : preparing
- ? t("settings.about.update.desktopPreparingDescription")
- : t("settings.about.update.desktopAvailableDescription");
+ : 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,
- // release manifest, or updater itself.
+ // Keep the raw reason: failures come from the network, HTTP, manifest or updater.
description = update.checkError ?? label;
} else if (update.hasChecked) {
label = t("settings.about.update.desktopCurrent");
@@ -81,13 +66,7 @@ export function DesktopUpdateControl(): ReactElement | null {
const action = available
? update.updatePolicyMode === "manual_linux_package"
? t("settings.about.update.openReleasePage")
- : fastRestart
- ? t("settings.about.update.restartToUpdate")
- : ready
- ? t("settings.about.update.finishUpdate")
- : preparing
- ? t("settings.about.update.preparing")
- : t("settings.about.update.updateNow")
+ : 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 74855f8a0eb..2a2553242c2 100644
--- a/studio/frontend/src/hooks/use-tauri-update.ts
+++ b/studio/frontend/src/hooks/use-tauri-update.ts
@@ -2,45 +2,26 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { useEffect, useRef, useState } from "react";
-import { isTrainingStartPending, useTrainingRuntimeStore } from "@/features/training";
-import { apiUrl, isTauri } from "@/lib/api-base";
+import { isTauri } from "@/lib/api-base";
import {
copySupportDiagnostics,
type CopySupportDiagnosticsResult,
} from "@/lib/tauri-diagnostics";
import {
- adoptStagedUpdate,
- cancelStagedUpdate,
checkDesktopUpdate,
desktopUpdateBundleStatus,
- discardStagedUpdate,
downloadDesktopUpdate,
installDesktopUpdate,
- stagedUpdateStatus,
- startStagedUpdate,
- waitForDesktopUpdateDownload,
+ listenDesktopUpdateDownload,
+ sameUpdateVersion,
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"
@@ -51,8 +32,7 @@ export interface UpdateInfo {
currentVersion: string;
// Backend release this build pins, which preflight checks against.
pypiVersion?: string;
- // latest.json's `notes`: a static download blurb, the same every release.
- // Kept as updater metadata, not shown; the popup fetches the real notes.
+ // latest.json's `notes`: a static download blurb. Kept as metadata, not shown.
body?: string;
date?: string;
}
@@ -79,7 +59,6 @@ interface ManualUpdateInfo {
date?: string;
}
-/** `pypi_version` from latest.json, which the updater passes through raw. */
function rawPypiVersion(raw: Record<string, unknown>): string | undefined {
const value = raw.pypi_version;
return typeof value === "string" && value.length > 0 ? value : undefined;
@@ -99,12 +78,9 @@ const DEFAULT_UPDATE_POLICY: DesktopUpdatePolicy = {
};
const STARTUP_UPDATE_CHECK_DELAY_MS = 5000;
const PERIODIC_UPDATE_CHECK_INTERVAL_MS = 60 * 60 * 1000;
-
-const PREPARATION_STATUSES: ReadonlySet<UpdateStatus> = new Set([
- "available",
- "preparing",
- "ready",
-]);
+const BUNDLE_DOWNLOAD_POLL_MS = 500;
+// A native download that stalls without clearing the flag would otherwise hold the update forever.
+const BUNDLE_DOWNLOAD_WAIT_MS = 10 * 60 * 1000;
// Desktop quit never fires beforeunload, and only the renderer sees the shell installer.
function publishShellUpdateActive(active: boolean): void {
@@ -133,18 +109,6 @@ 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");
@@ -162,20 +126,14 @@ 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 [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 lastCheckAtRef = useRef<number | null>(null);
const checkingRef = useRef(false);
const updatingRef = useRef(false);
- // Windows kill-on-close: false once a re-arm has failed, and every path that
- // starts a backend has to check it or the orphan risk comes straight back.
+ // Windows kill-on-close: false once a re-arm has failed, and every path that starts a backend must check it.
+ // A webview reload resets this ref while the native job may still be disarmed, so the first gate asks natively.
const cleanupRearmedRef = useRef(true);
- // A webview reload rebuilds this hook with the ref back at its initial value
- // while the native job may still be disarmed, so the first gate of a mount
- // asks the native side instead of trusting it.
const cleanupCheckedRef = useRef(false);
async function resumeCleanup(): Promise<boolean> {
@@ -200,29 +158,16 @@ export function useTauriUpdate(isExternalServer = false) {
setInfo(nextInfo);
}
- function restoredPreparationStatus(previousStatus: UpdateStatus): UpdateStatus {
- if (previousStatus === "available") return previousStatus;
- const nextStatus = preparationStatus(preparationRef.current);
- if (nextStatus === "ready" && previousStatus !== "ready") {
- setDismissed(false);
- }
- return nextStatus;
- }
-
- function offerUpdate(nextInfo: UpdateInfo, previousStatus?: UpdateStatus) {
+ function offerUpdate(nextInfo: UpdateInfo) {
const isNewOffer = infoRef.current?.version !== nextInfo.version;
replaceInfo(nextInfo);
if (isNewOffer) {
- // Only a version the user has not seen may reopen the banner.
setLastFailure(null);
setError(null);
setDismissed(false);
}
- updateStatus(
- !isNewOffer && previousStatus && PREPARATION_STATUSES.has(previousStatus)
- ? restoredPreparationStatus(previousStatus)
- : "available",
- );
+ // An hourly re-offer of the version already on show must not reopen a dismissed banner.
+ updateStatus("available");
}
function replaceLogs(nextLogs: string[]) {
@@ -262,24 +207,6 @@ 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;
@@ -302,10 +229,7 @@ export function useTauriUpdate(isExternalServer = false) {
}
}
- async function checkManualUpdate(
- policy: DesktopUpdatePolicy,
- previousStatus: UpdateStatus,
- ) {
+ async function checkManualUpdate(policy: DesktopUpdatePolicy) {
if (policy.mode !== "manual_linux_package") return false;
const { invoke } = await import("@tauri-apps/api/core");
const manualUpdate = await invoke<ManualUpdateInfo | null>(
@@ -313,16 +237,13 @@ export function useTauriUpdate(isExternalServer = false) {
);
if (!manualUpdate) return false;
updateRef.current = null;
- offerUpdate(
- {
- version: manualUpdate.version,
- currentVersion: manualUpdate.currentVersion,
- pypiVersion: manualUpdate.pypiVersion ?? undefined,
- body: manualUpdate.body,
- date: manualUpdate.date,
- },
- previousStatus,
- );
+ offerUpdate({
+ version: manualUpdate.version,
+ currentVersion: manualUpdate.currentVersion,
+ pypiVersion: manualUpdate.pypiVersion ?? undefined,
+ body: manualUpdate.body,
+ date: manualUpdate.date,
+ });
return true;
}
@@ -337,7 +258,6 @@ export function useTauriUpdate(isExternalServer = false) {
async function checkForUpdate() {
if (checkingRef.current || updatingRef.current) return;
- const previousStatus = statusRef.current;
// A manual check covers startup, so the delayed timer must not repeat it.
checkedRef.current = true;
lastCheckAtRef.current = Date.now();
@@ -350,69 +270,48 @@ export function useTauriUpdate(isExternalServer = false) {
if (policy.mode === "manual_linux_package") {
// Self-gates on the real target_os, so it is authoritative even if policy is a guess.
- if (await checkManualUpdate(policy, previousStatus)) return;
+ if (await checkManualUpdate(policy)) return;
if (resolved) {
- // latest.json has no deb/rpm key, so the in-app updater would offer an
- // AppImage this install cannot apply. Stop instead.
+ // latest.json has no deb/rpm key, so the in-app updater would offer an AppImage this install cannot apply.
updateRef.current = null;
replaceInfo(null);
- await clearPreparedBackendUpdate();
updateStatus("idle");
return;
}
- // Guessed policy, no manual offer: macOS, Windows and AppImage land here
- // and do have an in-app path. Fall through to it.
+ // Guessed policy, no manual offer: macOS, Windows and AppImage do have an in-app path.
}
const update = await checkDesktopUpdate();
if (update) {
updateRef.current = update;
- offerUpdate(
- {
- version: update.version,
- currentVersion: update.currentVersion,
- pypiVersion: rawPypiVersion(update.rawJson),
- body: update.body,
- date: update.date,
- },
- previousStatus,
- );
+ offerUpdate({
+ version: update.version,
+ currentVersion: update.currentVersion,
+ pypiVersion: rawPypiVersion(update.rawJson),
+ body: update.body,
+ date: update.date,
+ });
} else {
updateRef.current = null;
replaceInfo(null);
- resetPreparation();
- await clearPreparedBackendUpdate();
updateStatus("idle");
}
} catch (e) {
console.error("Update check failed:", e);
setCheckError(String(e));
- updateStatus(
- infoRef.current
- ? PREPARATION_STATUSES.has(previousStatus)
- ? restoredPreparationStatus(previousStatus)
- : previousStatus
- : "idle",
- );
+ updateStatus(infoRef.current ? "available" : "idle");
} finally {
checkingRef.current = false;
setHasChecked(true);
}
}
- async function clearPreparedBackendUpdate() {
- const staged = await stagedUpdateStatus();
- if (staged.staging) await cancelStagedUpdate();
- await discardStagedUpdate();
- }
-
function checkForUpdateWhenSafe() {
- // preparation and recovery own version-specific state until they settle.
- if (statusRef.current === "preparing" || statusRef.current === "error") return;
+ // Recovery owns version-specific state until the user settles it.
+ if (statusRef.current === "error") return;
void checkForUpdate();
}
- // scheduled checks use the mount's stable closure, which only reads refs and state setters.
const scheduledCheckRef = useRef(checkForUpdateWhenSafe);
useEffect(() => {
@@ -449,138 +348,37 @@ export function useTauriUpdate(isExternalServer = false) {
};
}, []);
- 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) {
+ // Attached only once a download is in flight and released whichever way the wait ends.
+ let unlisten: (() => void) | null = null;
+ const waitUntil = Date.now() + BUNDLE_DOWNLOAD_WAIT_MS;
try {
for (;;) {
+ // A bundle retained by an earlier attempt is reused, so a retry usually stops here.
const bundle = await desktopUpdateBundleStatus();
- const decision = desktopDownloadDecision(bundle, version);
- if (decision === "ready") {
- patchPreparation({ shell: "done", shellProgress: 100 });
+ if (bundle.downloaded && sameUpdateVersion(bundle.version, version)) {
+ setUpdateProgress(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;
+ // A webview reload leaves the native download running with no listener, and a second one is refused.
+ if (!bundle.downloading) break;
+ if (Date.now() >= waitUntil) break;
+ if (!unlisten) {
+ unlisten = await listenDesktopUpdateDownload(version, setUpdateProgress);
}
- 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,
+ await new Promise((resolve) =>
+ setTimeout(resolve, BUNDLE_DOWNLOAD_POLL_MS),
);
- 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" });
+ } finally {
+ unlisten?.();
}
+ await downloadDesktopUpdate(version, setUpdateProgress);
}
async function installUpdate() {
@@ -589,8 +387,7 @@ export function useTauriUpdate(isExternalServer = false) {
const cleanups: (() => void)[] = [];
try {
- // A retry re-enters here, and start_backend_update spawns an
- // environment-mutating child of its own.
+ // A retry re-enters here, and start_backend_update spawns a mutating child of its own.
if (!(await crashCleanupReady())) return;
const { policy } = await resolveUpdatePolicy();
if (policy.mode === "manual_linux_package") {
@@ -610,106 +407,72 @@ export function useTauriUpdate(isExternalServer = false) {
const update = updateRef.current;
if (!update) return;
- if (statusRef.current === "available") {
- void prepareUpdate(update.version, policy);
- return;
- }
const { invoke } = await import("@tauri-apps/api/core");
- 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("backend");
+ updateStatus("updating-backend");
+ replaceLogs([]);
+ setUpdateProgress(0);
+ setError(null);
+ setCheckError(null);
+ setLastFailure(null);
+ setDismissed(false);
- 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 { 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)));
- },
- );
+ 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));
- if (backendResult !== "complete") {
- retainFailure(backendResult, "backend");
- setError(backendResult);
- updateStatus("error");
- return;
- }
+ invoke("start_backend_update").catch((e) => resolve(String(e)));
+ },
+ );
- await ensureBundleDownloaded();
- setUpdatePhase("shell_install");
- updateStatus("installing");
+ if (backendResult !== "complete") {
+ retainFailure(backendResult, "backend");
+ setError(backendResult);
+ updateStatus("error");
+ return;
}
- // `update::is_update_running` is already false here, and quitting mid-install
- // leaves a half-updated app.
+ await ensureBundleDownloaded();
+ setUpdatePhase("shell_install");
+ updateStatus("installing");
+
+ // `update::is_update_running` is already false here, and quitting mid-install leaves a half-updated app.
publishShellUpdateActive(true);
try {
await installDesktopUpdate();
} catch (installError) {
- // Failed or cancelled: we keep running, so the cleanup the pre-exit hook
- // stood down has to come back.
+ // Failed or cancelled: we keep running, so the stood-down cleanup has to come back.
await resumeCleanup();
throw installError;
} finally {
publishShellUpdateActive(false);
}
- // Deliberately NOT re-arming kill-on-close before the restart: relaunch()
- // starts the replacement as a child, so it inherits this job, and re-arming
- // would make this process kill it on the way out.
- // The whole handoff is inside the recovery scope: anything that throws here
- // leaves this process running with cleanup still stood down.
+ // Deliberately NOT re-arming kill-on-close before the restart: relaunch() starts the replacement as a child,
+ // which inherits this job. The handoff stays in the recovery scope, or a throw leaves cleanup stood down.
try {
- // relaunch() re-execs with the original argv, so flag the inherited --hidden as not a
- // login start. It only fails when there is a --hidden to suppress, so let it stop the
- // restart.
+ // relaunch() re-execs with the original argv, so flag the inherited --hidden as not a login start.
await invoke("mark_in_app_relaunch");
const { relaunch } = await import("@tauri-apps/plugin-process");
await relaunch();
} catch (relaunchError) {
// No replacement process, so the marker would outlive it and unhide a later login start.
await invoke("clear_in_app_relaunch").catch(() => {});
- // Still this process, so the cleanup has to come back after all.
await resumeCleanup();
throw relaunchError;
}
@@ -717,11 +480,8 @@ export function useTauriUpdate(isExternalServer = false) {
console.error("Update failed:", e);
const msg = String(e);
- // Shell update failed, so restart the backend on the updated code.
if (phaseRef.current === "shell_download" || phaseRef.current === "shell_install") {
- // A backend started under a job that still has kill-on-close disabled is
- // the orphan this PR exists to prevent, so retry the re-arm and stop here
- // if it will not take.
+ // A backend started under a job with kill-on-close disabled is the orphan this prevents.
if (!(await crashCleanupReady())) {
retainFailure(msg, phaseRef.current ?? "shell_install");
return;
@@ -767,8 +527,7 @@ export function useTauriUpdate(isExternalServer = false) {
const { invoke } = await import("@tauri-apps/api/core");
cleanupRearmedRef.current = await invoke<boolean>("desktop_update_cleanup_armed");
} catch {
- // On the desktop this is the one answer we cannot assume: fail closed
- // and let the gate below re-arm. In the browser there is no job at all.
+ // The one answer we cannot assume on the desktop: fail closed and let the gate re-arm.
cleanupRearmedRef.current = !isTauri;
}
}
@@ -783,8 +542,7 @@ export function useTauriUpdate(isExternalServer = false) {
async function skipAndRestart() {
const skippedError = error;
- // Same gate as the recovery path: this is offered on every error, so it is
- // the other way a user could start a backend under a disarmed job.
+ // Same gate as the recovery path: this is offered on every error.
if (!(await crashCleanupReady())) return;
try {
const { invoke } = await import("@tauri-apps/api/core");
@@ -822,12 +580,10 @@ export function useTauriUpdate(isExternalServer = false) {
});
}
- // Install target for Linux packages that cannot self-update.
const manualReleaseUrl =
updatePolicy.mode === "manual_linux_package" && info
? manualReleasePageUrl(updatePolicy, info.version)
: null;
- // Release page for the offered version, on every platform, for the notes link.
const releasePageUrl = info ? manualReleasePageUrl(updatePolicy, info.version) : null;
return {
@@ -841,7 +597,6 @@ 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 ca5badeb662..73640d675e4 100644
--- a/studio/frontend/src/i18n/locales/ar.ts
+++ b/studio/frontend/src/i18n/locales/ar.ts
@@ -1277,9 +1277,8 @@ export const ar = {
docs: "التوثيق",
agentDocs: "فتح توثيق إعداد {agent}",
copyGeneratedCommand: "نسخ الأمر المُنشأ",
- // English is the baseline until these are translated. The three-part
- // sentence below is assembled in a fixed order around an inline link, so
- // it needs restructuring before it can be translated well.
+ // English is the baseline until translated: the three-part sentence is assembled around an
+ // inline link and needs restructuring first.
automaticSettingsNote:
"Unsloth automatically applies the model’s recommended settings if you have not set any flags.",
configurationNote:
@@ -1711,7 +1710,7 @@ export const ar = {
desktopCheckingDescription: "يستغرق ذلك عادةً بضع ثوانٍ.",
desktopAvailable: "يتوفر إصدار جديد من تطبيق سطح المكتب: {version}",
desktopAvailableDescription:
- "حدّث الآن ليُجهَّز التحديث في الخلفية. يمكنك متابعة عملك وإعادة التشغيل عندما يصبح جاهزًا.",
+ "حدّث الآن، وسيُعاد تشغيل تطبيق سطح المكتب عند اكتمال التحديث.",
desktopExternalServer:
"شغّل الأمر `unsloth studio update` في الطرفية التي شغّلت الخادم.",
desktopManualInstall:
@@ -1720,20 +1719,11 @@ 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 3e6908bfae1..1f10d06b50b 100644
--- a/studio/frontend/src/i18n/locales/de.ts
+++ b/studio/frontend/src/i18n/locales/de.ts
@@ -1306,9 +1306,8 @@ export const de = {
docs: "Dokumentation",
agentDocs: "Einrichtungsdokumentation zu {agent} öffnen",
copyGeneratedCommand: "Generierten Befehl kopieren",
- // English is the baseline until these are translated. The three-part
- // sentence below is assembled in a fixed order around an inline link, so
- // it needs restructuring before it can be translated well.
+ // English is the baseline until translated: the three-part sentence is assembled around an
+ // inline link and needs restructuring first.
automaticSettingsNote:
"Unsloth automatically applies the model’s recommended settings if you have not set any flags.",
configurationNote:
@@ -1758,7 +1757,7 @@ export const de = {
"Dies dauert in der Regel einige Sekunden.",
desktopAvailable: "Version {version} der Desktop-App ist verfügbar",
desktopAvailableDescription:
- "Aktualisieren Sie jetzt, um das Update im Hintergrund vorzubereiten. Sie können weiterarbeiten und neu starten, sobald es bereit ist.",
+ "Aktualisieren Sie jetzt. Die Desktop-App wird nach Abschluss des Updates neu gestartet.",
desktopExternalServer:
"Führen Sie `unsloth studio update` in dem Terminal aus, über das Sie Ihren Server gestartet haben.",
desktopManualInstall:
@@ -1769,20 +1768,11 @@ 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 c59c68afe3f..ae5ab703f31 100644
--- a/studio/frontend/src/i18n/locales/en.ts
+++ b/studio/frontend/src/i18n/locales/en.ts
@@ -465,8 +465,7 @@ export const en = {
droppedNotice: "Some lines were skipped: the log was written faster than it could be read.",
morePending: "More lines are still being read; they arrive on the next refresh.",
staleSession: "File logging is turned off, so this is an earlier session and will not update.",
- // Not rendered: extra terms the settings search matches this tab on, so
- // the pane is still reachable by searching for debug or an error.
+ // Not rendered: extra terms the settings search matches this tab on.
keywords: "debug debugging log logs error errors crash traceback stack trace troubleshoot diagnostics failed",
},
voice: {
@@ -1702,7 +1701,7 @@ export const en = {
desktopCheckingDescription: "This usually takes a few seconds.",
desktopAvailable: "Desktop app {version} is available",
desktopAvailableDescription:
- "Update now to prepare it in the background. You keep working and restart when it is ready.",
+ "Update now and the desktop app will restart when it finishes.",
desktopExternalServer:
"Run `unsloth studio update` from the terminal that started your server.",
desktopManualInstall:
@@ -1712,20 +1711,11 @@ 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.",
@@ -2428,8 +2418,7 @@ export const en = {
"Weights {model} + context {context} = {total} of {budget} usable VRAM",
readoutWithSpec:
"Weights {model} + KV {kv} + MTP draft {spec} = {total} of {budget} usable VRAM",
- // Measured against llama.cpp: the cache is allocated at context creation,
- // sized to n_ctx, so the rate is what a longer context actually costs.
+ // Measured against llama.cpp: the cache is allocated at context creation, sized to n_ctx.
kvRate: "KV reserved, ~{rate}/token",
oomLikely: "With current settings OOM likely",
tooLarge: "Larger than VRAM, will offload to CPU. A smaller quantization runs faster",
diff --git a/studio/frontend/src/i18n/locales/es.ts b/studio/frontend/src/i18n/locales/es.ts
index 8d69a3f6f7a..7672a69b8fb 100644
--- a/studio/frontend/src/i18n/locales/es.ts
+++ b/studio/frontend/src/i18n/locales/es.ts
@@ -1300,9 +1300,8 @@ export const es = {
docs: "Documentación",
agentDocs: "Abrir la documentación de configuración de {agent}",
copyGeneratedCommand: "Copiar el comando generado",
- // English is the baseline until these are translated. The three-part
- // sentence below is assembled in a fixed order around an inline link, so
- // it needs restructuring before it can be translated well.
+ // English is the baseline until translated: the three-part sentence is assembled around an
+ // inline link and needs restructuring first.
automaticSettingsNote:
"Unsloth automatically applies the model’s recommended settings if you have not set any flags.",
configurationNote:
@@ -1750,7 +1749,7 @@ export const es = {
desktopAvailable:
"La versión {version} de la app de escritorio está disponible",
desktopAvailableDescription:
- "Actualiza ahora para prepararla en segundo plano. Puedes seguir trabajando y reiniciar cuando esté lista.",
+ "Actualiza ahora y la app de escritorio se reiniciará cuando termine.",
desktopExternalServer:
"Ejecuta `unsloth studio update` desde el terminal que inició el servidor.",
desktopManualInstall:
@@ -1761,20 +1760,11 @@ 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 ae11e19c222..f680a10308b 100644
--- a/studio/frontend/src/i18n/locales/fr.ts
+++ b/studio/frontend/src/i18n/locales/fr.ts
@@ -1304,9 +1304,8 @@ export const fr = {
docs: "Documentation",
agentDocs: "Ouvrir la documentation de configuration de {agent}",
copyGeneratedCommand: "Copier la commande générée",
- // English is the baseline until these are translated. The three-part
- // sentence below is assembled in a fixed order around an inline link, so
- // it needs restructuring before it can be translated well.
+ // English is the baseline until translated: the three-part sentence is assembled around an
+ // inline link and needs restructuring first.
automaticSettingsNote:
"Unsloth automatically applies the model’s recommended settings if you have not set any flags.",
configurationNote:
@@ -1759,7 +1758,7 @@ export const fr = {
desktopAvailable:
"La version {version} de l’application de bureau est disponible",
desktopAvailableDescription:
- "Mettez à jour maintenant pour la préparer en arrière-plan. Vous continuez à travailler et redémarrez lorsqu’elle est prête.",
+ "Effectuez la mise à jour maintenant. L’application de bureau redémarrera une fois l’opération terminée.",
desktopExternalServer:
"Exécutez `unsloth studio update` dans le terminal depuis lequel vous avez lancé le serveur.",
desktopManualInstall:
@@ -1770,20 +1769,11 @@ 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 15860f57503..3992b18561f 100644
--- a/studio/frontend/src/i18n/locales/hi.ts
+++ b/studio/frontend/src/i18n/locales/hi.ts
@@ -1280,9 +1280,8 @@ export const hi = {
docs: "दस्तावेज़",
agentDocs: "{agent} के सेटअप दस्तावेज़ खोलें",
copyGeneratedCommand: "बनाया गया कमांड कॉपी करें",
- // English is the baseline until these are translated. The three-part
- // sentence below is assembled in a fixed order around an inline link, so
- // it needs restructuring before it can be translated well.
+ // English is the baseline until translated: the three-part sentence is assembled around an
+ // inline link and needs restructuring first.
automaticSettingsNote:
"Unsloth automatically applies the model’s recommended settings if you have not set any flags.",
configurationNote:
@@ -1718,7 +1717,7 @@ export const hi = {
"इसमें आम तौर पर कुछ सेकंड लगते हैं।",
desktopAvailable: "डेस्कटॉप ऐप {version} उपलब्ध है",
desktopAvailableDescription:
- "अभी अपडेट करें, यह पृष्ठभूमि में तैयार होगा। आप काम करते रह सकते हैं और तैयार होने पर फिर से शुरू करें।",
+ "अभी अपडेट करें। अपडेट पूरा होने पर डेस्कटॉप ऐप फिर से शुरू होगा।",
desktopExternalServer:
"जिस टर्मिनल से सर्वर शुरू किया गया था, उसमें `unsloth studio update` चलाएँ।",
desktopManualInstall:
@@ -1728,20 +1727,11 @@ 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 df2aeef06dd..ba861d22e3d 100644
--- a/studio/frontend/src/i18n/locales/it.ts
+++ b/studio/frontend/src/i18n/locales/it.ts
@@ -1272,9 +1272,8 @@ export const it = {
docs: "Documentazione",
agentDocs: "Apri la documentazione di configurazione di {agent}",
copyGeneratedCommand: "Copia il comando generato",
- // English is the baseline until these are translated. The three-part
- // sentence below is assembled in a fixed order around an inline link, so
- // it needs restructuring before it can be translated well.
+ // English is the baseline until translated: the three-part sentence is assembled around an
+ // inline link and needs restructuring first.
automaticSettingsNote:
"Unsloth automatically applies the model’s recommended settings if you have not set any flags.",
configurationNote:
@@ -1725,7 +1724,7 @@ export const it = {
desktopAvailable:
"È disponibile la versione {version} dell'app desktop",
desktopAvailableDescription:
- "Aggiorna ora per prepararlo in background. Puoi continuare a lavorare e riavviare quando è pronto.",
+ "Aggiorna ora: al termine, l'app desktop verrà riavviata.",
desktopExternalServer:
"Esegui `unsloth studio update` nel terminale da cui hai avviato il server.",
desktopManualInstall:
@@ -1736,20 +1735,11 @@ 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 0b1ab6612fc..5d0b481ea2d 100644
--- a/studio/frontend/src/i18n/locales/ja.ts
+++ b/studio/frontend/src/i18n/locales/ja.ts
@@ -1259,9 +1259,8 @@ export const ja = {
docs: "ドキュメント",
agentDocs: "{agent} のセットアップドキュメントを開く",
copyGeneratedCommand: "生成されたコマンドをコピー",
- // English is the baseline until these are translated. The three-part
- // sentence below is assembled in a fixed order around an inline link, so
- // it needs restructuring before it can be translated well.
+ // English is the baseline until translated: the three-part sentence is assembled around an
+ // inline link and needs restructuring first.
automaticSettingsNote:
"Unsloth automatically applies the model’s recommended settings if you have not set any flags.",
configurationNote:
@@ -1682,7 +1681,7 @@ export const ja = {
desktopCheckingDescription: "通常は数秒で完了します。",
desktopAvailable: "デスクトップアプリ {version} を利用できます",
desktopAvailableDescription:
- "今すぐアップデートすると、バックグラウンドで準備されます。作業を続けたまま、準備ができたら再起動してください。",
+ "今すぐアップデートします。完了するとデスクトップアプリが再起動します。",
desktopExternalServer:
"サーバーを起動したターミナルで `unsloth studio update` を実行してください。",
desktopManualInstall:
@@ -1693,19 +1692,11 @@ 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 d4c91ab04b8..734c68e6fd5 100644
--- a/studio/frontend/src/i18n/locales/ko.ts
+++ b/studio/frontend/src/i18n/locales/ko.ts
@@ -1273,9 +1273,8 @@ export const ko = {
docs: "문서",
agentDocs: "{agent} 설정 문서 열기",
copyGeneratedCommand: "생성된 명령 복사",
- // English is the baseline until these are translated. The three-part
- // sentence below is assembled in a fixed order around an inline link, so
- // it needs restructuring before it can be translated well.
+ // English is the baseline until translated: the three-part sentence is assembled around an
+ // inline link and needs restructuring first.
automaticSettingsNote:
"Unsloth automatically applies the model’s recommended settings if you have not set any flags.",
configurationNote:
@@ -1708,7 +1707,7 @@ export const ko = {
desktopCheckingDescription: "보통 몇 초 정도 걸립니다.",
desktopAvailable: "데스크톱 앱 {version} 버전을 사용할 수 있습니다",
desktopAvailableDescription:
- "지금 업데이트하면 백그라운드에서 준비됩니다. 계속 작업하다가 준비되면 다시 시작하세요.",
+ "지금 업데이트하면 완료 후 데스크톱 앱이 다시 시작됩니다.",
desktopExternalServer:
"서버를 시작한 터미널에서 `unsloth studio update`를 실행하세요.",
desktopManualInstall:
@@ -1718,17 +1717,11 @@ 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 20c60a9cdfc..30861513404 100644
--- a/studio/frontend/src/i18n/locales/pt-br.ts
+++ b/studio/frontend/src/i18n/locales/pt-br.ts
@@ -1288,9 +1288,8 @@ export const ptBR = {
docs: "Documentação",
agentDocs: "Abrir a documentação de configuração do {agent}",
copyGeneratedCommand: "Copiar comando gerado",
- // English is the baseline until these are translated. The three-part
- // sentence below is assembled in a fixed order around an inline link, so
- // it needs restructuring before it can be translated well.
+ // English is the baseline until translated: the three-part sentence is assembled around an
+ // inline link and needs restructuring first.
automaticSettingsNote:
"Unsloth automatically applies the model’s recommended settings if you have not set any flags.",
configurationNote:
@@ -1733,7 +1732,7 @@ export const ptBR = {
desktopAvailable:
"A versão {version} do aplicativo de desktop está disponível",
desktopAvailableDescription:
- "Atualize agora para preparar em segundo plano. Você continua trabalhando e reinicia quando estiver pronto.",
+ "Atualize agora. O aplicativo de desktop será reiniciado quando a atualização terminar.",
desktopExternalServer:
"Execute `unsloth studio update` no terminal usado para iniciar o servidor.",
desktopManualInstall:
@@ -1744,20 +1743,11 @@ 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 1312d448205..8a28bb807fd 100644
--- a/studio/frontend/src/i18n/locales/ru.ts
+++ b/studio/frontend/src/i18n/locales/ru.ts
@@ -1283,9 +1283,8 @@ export const ru = {
docs: "Документация",
agentDocs: "Открыть документацию по настройке {agent}",
copyGeneratedCommand: "Копировать сформированную команду",
- // English is the baseline until these are translated. The three-part
- // sentence below is assembled in a fixed order around an inline link, so
- // it needs restructuring before it can be translated well.
+ // English is the baseline until translated: the three-part sentence is assembled around an
+ // inline link and needs restructuring first.
automaticSettingsNote:
"Unsloth automatically applies the model’s recommended settings if you have not set any flags.",
configurationNote:
@@ -1730,7 +1729,7 @@ export const ru = {
desktopAvailable:
"Доступна версия {version} настольного приложения",
desktopAvailableDescription:
- "Установите обновление сейчас, чтобы подготовить его в фоновом режиме. Вы можете продолжать работу и перезапустить приложение, когда всё будет готово.",
+ "Установите обновление сейчас. После установки настольное приложение перезапустится.",
desktopExternalServer:
"Выполните `unsloth studio update` в терминале, из которого был запущен сервер.",
desktopManualInstall:
@@ -1742,20 +1741,11 @@ 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 9f35d118dd1..2e4e99b0cb5 100644
--- a/studio/frontend/src/i18n/locales/zh-CN.ts
+++ b/studio/frontend/src/i18n/locales/zh-CN.ts
@@ -1248,9 +1248,8 @@ export const zhCN = {
docs: "文档",
agentDocs: "打开 {agent} 的配置文档",
copyGeneratedCommand: "复制生成的命令",
- // English is the baseline until these are translated. The three-part
- // sentence below is assembled in a fixed order around an inline link, so
- // it needs restructuring before it can be translated well.
+ // English is the baseline until translated: the three-part sentence is assembled around an
+ // inline link and needs restructuring first.
automaticSettingsNote:
"Unsloth automatically applies the model’s recommended settings if you have not set any flags.",
configurationNote:
@@ -1667,7 +1666,7 @@ export const zhCN = {
desktopChecking: "正在检查更新",
desktopCheckingDescription: "通常只需几秒钟。",
desktopAvailable: "桌面应用 {version} 已可用",
- desktopAvailableDescription: "立即更新,更新将在后台准备。你可以继续工作,准备好后再重启。",
+ desktopAvailableDescription: "立即更新,完成后桌面应用将自动重启。",
desktopExternalServer:
"请在启动服务器的终端中运行 `unsloth studio update`。",
desktopManualInstall: "打开发布页面,安装最新的 Linux 软件包。",
@@ -1675,17 +1674,11 @@ 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 5eaea5987f8..0c63201ebc6 100644
--- a/studio/frontend/src/lib/tauri-updater.ts
+++ b/studio/frontend/src/lib/tauri-updater.ts
@@ -1,13 +1,6 @@
// 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 {
- downloadPercent,
- sameUpdateVersion,
- type DesktopUpdateBundleStatus,
- type StagedUpdateStatus,
-} from "@/lib/update-preparation";
-
export interface DesktopUpdateMetadata {
currentVersion: string;
version: string;
@@ -16,12 +9,30 @@ export interface DesktopUpdateMetadata {
rawJson: Record<string, unknown>;
}
+export interface DesktopUpdateBundleStatus {
+ version: string | null;
+ downloaded: boolean;
+ downloading: boolean;
+}
+
interface DesktopUpdateDownloadEvent {
version: string;
downloaded: number;
total: number | null;
}
+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 downloadPercent(downloaded: number, total: number | null): number {
+ if (!total || total <= 0) return 0;
+ return Math.min(100, Math.round((downloaded / total) * 100));
+}
+
export async function checkDesktopUpdate(): Promise<DesktopUpdateMetadata | null> {
const { invoke } = await import("@tauri-apps/api/core");
return invoke<DesktopUpdateMetadata | null>("check_desktop_update");
@@ -32,53 +43,41 @@ export async function desktopUpdateBundleStatus(): Promise<DesktopUpdateBundleSt
return invoke<DesktopUpdateBundleStatus>("desktop_update_bundle_status");
}
-export async function downloadDesktopUpdate(
+/**
+ * Progress for the one bundle download in flight, whoever started it. Split out of
+ * `downloadDesktopUpdate` because a webview reload leaves the native download running with
+ * nothing listening, and the update that comes back has none of its own to report on.
+ */
+export async function listenDesktopUpdateDownload(
expectedVersion: string,
onProgress: (percent: number) => void,
-): Promise<void> {
- const [{ invoke }, { listen }] = await Promise.all([
- import("@tauri-apps/api/core"),
- import("@tauri-apps/api/event"),
- ]);
- const unlisten = await listen<DesktopUpdateDownloadEvent>(
+): Promise<() => void> {
+ const { listen } = await import("@tauri-apps/api/event");
+ return 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(
+export async function downloadDesktopUpdate(
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));
- },
+ const { invoke } = await import("@tauri-apps/api/core");
+ const unlisten = await listenDesktopUpdateDownload(
+ expectedVersion,
+ onProgress,
);
try {
- while (!isCancelled()) {
- const status = await desktopUpdateBundleStatus();
- if (!status.downloading) return;
- await new Promise((resolve) => setTimeout(resolve, pollMs));
+ 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();
}
@@ -88,52 +87,3 @@ 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
deleted file mode 100644
index 51155b86a60..00000000000
--- a/studio/frontend/src/lib/update-preparation.ts
+++ /dev/null
@@ -1,180 +0,0 @@
-// 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/tauri-update-schedule.test.ts b/studio/frontend/tests/tauri-update-schedule.test.ts
index 8612c914ef1..acca3f0e6e3 100644
--- a/studio/frontend/tests/tauri-update-schedule.test.ts
+++ b/studio/frontend/tests/tauri-update-schedule.test.ts
@@ -8,6 +8,14 @@ import { loadWithStubs } from "./helpers/module-stubs.ts";
const STARTUP_DELAY_MS = 5_000;
const PERIODIC_INTERVAL_MS = 60 * 60 * 1_000;
+const BUNDLE_POLL_MS = 500;
+const BUNDLE_WAIT_MS = 10 * 60 * 1_000;
+
+interface BundleState {
+ version: string | null;
+ downloaded: boolean;
+ downloading: boolean;
+}
type UpdateController = {
checkForUpdate: () => Promise<void>;
@@ -18,10 +26,12 @@ type Listener = EventListenerOrEventListenerObject;
interface HookHarnessOptions {
failCheckAt?: number;
- holdPreparation?: boolean;
noUpdateAt?: number;
- rejectDiscard?: boolean;
tauri?: boolean;
+ /** Whether `start_backend_update` resolves; the shell steps only run if it does. */
+ backendUpdate?: "completes" | "fails";
+ /** One entry per `desktopUpdateBundleStatus` poll; the last one repeats. */
+ bundleStates?: BundleState[];
}
function createEventTarget() {
@@ -186,6 +196,7 @@ function createHookReact() {
const effects: Array<() => unknown> = [];
const cleanups: Array<() => void> = [];
const statusUpdates: string[] = [];
+ const progressUpdates: number[] = [];
let stateIndex = 0;
return {
react: {
@@ -196,6 +207,7 @@ function createHookReact() {
(next: unknown) => {
if (index === 0 && typeof next === "string")
statusUpdates.push(next);
+ if (typeof next === "number") progressUpdates.push(next);
},
];
},
@@ -215,6 +227,7 @@ function createHookReact() {
unmount(): void {
for (const cleanup of cleanups.splice(0)) cleanup();
},
+ progressUpdates,
statusUpdates,
};
}
@@ -223,10 +236,10 @@ function hookHarness(
t: TestContext,
{
failCheckAt,
- holdPreparation = false,
noUpdateAt,
- rejectDiscard = false,
tauri = true,
+ backendUpdate = "fails",
+ bundleStates = [{ version: null, downloaded: false, downloading: false }],
}: HookHarnessOptions = {},
) {
const browser = installBrowserClock();
@@ -236,26 +249,35 @@ function hookHarness(
browser.restore();
});
let checks = 0;
- const initialPreparation = {
- shell: "pending",
- backend: "pending",
- shellProgress: 0,
+ let polls = 0;
+ let relaunches = 0;
+ const events = new Map<string, Set<(event: { payload: unknown }) => void>>();
+ const emit = (name: string, payload?: unknown) => {
+ for (const callback of events.get(name) ?? []) callback({ payload });
+ };
+ // What the hook does with the download it is only watching, not running.
+ const download: {
+ attached: string[];
+ released: number;
+ started: number;
+ report: (percent: number) => void;
+ } = {
+ attached: [],
+ released: 0,
+ started: 0,
+ report: () => {
+ throw new Error("no download listener is attached");
+ },
};
const hook = loadWithStubs<{
useTauriUpdate: () => UpdateController;
}>(new URL("../src/hooks/use-tauri-update.ts", import.meta.url), {
react: host.react,
- "@/features/training": {
- isTrainingStartPending: () => false,
- useTrainingRuntimeStore: { getState: () => ({}) },
- },
- "@/lib/api-base": { apiUrl: (path: string) => path, isTauri: tauri },
+ "@/lib/api-base": { isTauri: tauri },
"@/lib/tauri-diagnostics": {
copySupportDiagnostics: async () => ({ copied: true }),
},
"@/lib/tauri-updater": {
- adoptStagedUpdate: () => Promise.resolve({}),
- cancelStagedUpdate: () => Promise.resolve(),
checkDesktopUpdate: () => {
checks += 1;
if (checks === failCheckAt) throw new Error("update check failed");
@@ -266,35 +288,30 @@ function hookHarness(
rawJson: {},
});
},
- desktopUpdateBundleStatus: () =>
- holdPreparation
- ? new Promise(() => {})
- : Promise.resolve({ downloaded: false }),
- discardStagedUpdate: () =>
- rejectDiscard
- ? Promise.reject(new Error("discard failed"))
- : Promise.resolve(),
- downloadDesktopUpdate: () => Promise.resolve(),
+ desktopUpdateBundleStatus: () => {
+ const state = bundleStates[Math.min(polls, bundleStates.length - 1)];
+ polls += 1;
+ return Promise.resolve(state);
+ },
+ downloadDesktopUpdate: () => {
+ download.started += 1;
+ return Promise.resolve();
+ },
installDesktopUpdate: () => Promise.resolve(),
- stagedUpdateStatus: () => Promise.resolve({ staging: false }),
- startStagedUpdate: () => Promise.resolve(),
- waitForDesktopUpdateDownload: () => Promise.resolve(),
+ listenDesktopUpdateDownload: (
+ version: string,
+ onProgress: (percent: number) => void,
+ ) => {
+ download.attached.push(version);
+ download.report = onProgress;
+ return Promise.resolve(() => {
+ download.released += 1;
+ });
+ },
+ sameUpdateVersion: (left: string | null | undefined, right: string) =>
+ Boolean(left) && left === right,
},
"@/lib/toast": { toast: { error: () => undefined } },
- "@/lib/update-preparation": {
- INITIAL_PREPARATION: initialPreparation,
- backendIdle: () => true,
- desktopDownloadDecision: () => "ready",
- preparationStatus: (preparation: typeof initialPreparation) =>
- preparation.shell === "done" && preparation.backend === "skipped"
- ? "ready"
- : "preparing",
- restartPlan: () => "classic",
- sameUpdateVersion: () => true,
- settleWithin: async () => null,
- stagingDecision: () => "skip",
- waitForBackendIdle: async () => "cancelled",
- },
"@tauri-apps/api/core": {
invoke: async (command: string) => {
if (command === "desktop_update_policy") {
@@ -305,12 +322,35 @@ function hookHarness(
};
}
if (command === "desktop_update_cleanup_armed") return true;
+ if (command === "start_backend_update") {
+ // The command itself decides the backend step, rather than a stub that happens to throw.
+ if (backendUpdate === "fails")
+ throw new Error("backend update failed");
+ queueMicrotask(() => emit("update-complete"));
+ return undefined;
+ }
+ if (command === "set_renderer_activity") return undefined;
+ if (command === "mark_in_app_relaunch") return undefined;
throw new Error(`unexpected invoke: ${command}`);
},
},
"@tauri-apps/api/event": {
- listen: async () => {
- throw new Error("backend update failed");
+ listen: async (
+ name: string,
+ callback: (event: { payload: unknown }) => void,
+ ) => {
+ const registered =
+ events.get(name) ?? new Set<(event: { payload: unknown }) => void>();
+ registered.add(callback);
+ events.set(name, registered);
+ return () => {
+ registered.delete(callback);
+ };
+ },
+ },
+ "@tauri-apps/plugin-process": {
+ relaunch: async () => {
+ relaunches += 1;
},
},
});
@@ -320,7 +360,11 @@ function hookHarness(
browser,
checks: () => checks,
controller,
+ download,
host,
+ polls: () => polls,
+ progressUpdates: host.progressUpdates,
+ relaunches: () => relaunches,
statusUpdates: host.statusUpdates,
};
}
@@ -362,17 +406,16 @@ test("a manual check suppresses only the startup check", async (t) => {
assert.equal(hook.checks(), 2);
});
-test("a periodic recheck preserves a prepared update", async (t) => {
+test("a periodic recheck keeps an offered update available", async (t) => {
const hook = hookHarness(t);
hook.browser.fireTimeouts(STARTUP_DELAY_MS);
await settle();
- await hook.controller.installUpdate();
- await settle();
- assert.equal(hook.statusUpdates.at(-1), "ready");
+ assert.equal(hook.statusUpdates.at(-1), "available");
hook.browser.fireIntervals(PERIODIC_INTERVAL_MS);
await settle();
- assert.equal(hook.statusUpdates.at(-1), "ready");
+ assert.equal(hook.checks(), 2);
+ assert.equal(hook.statusUpdates.at(-1), "available");
});
test("a failed periodic recheck preserves an untouched offer", async (t) => {
@@ -387,8 +430,8 @@ test("a failed periodic recheck preserves an untouched offer", async (t) => {
assert.equal(hook.statusUpdates.at(-1), "available");
});
-test("a cleanup failure does not restore a withdrawn offer", async (t) => {
- const hook = hookHarness(t, { noUpdateAt: 2, rejectDiscard: true });
+test("a withdrawn offer goes back to idle", async (t) => {
+ const hook = hookHarness(t, { noUpdateAt: 2 });
hook.browser.fireTimeouts(STARTUP_DELAY_MS);
await settle();
assert.equal(hook.statusUpdates.at(-1), "available");
@@ -399,38 +442,80 @@ test("a cleanup failure does not restore a withdrawn offer", async (t) => {
assert.equal(hook.statusUpdates.at(-1), "idle");
});
-test("scheduled checks wait for update preparation", async (t) => {
- const hook = hookHarness(t, { holdPreparation: true });
+test("scheduled checks leave a failed install in its error state", async (t) => {
+ const hook = hookHarness(t);
hook.browser.fireTimeouts(STARTUP_DELAY_MS);
await settle();
+ assert.equal(hook.statusUpdates.at(-1), "available");
+
+ // start_backend_update itself refuses, which is the failure the classic path reports.
await hook.controller.installUpdate();
- assert.equal(hook.statusUpdates.at(-1), "preparing");
+ await settle();
+ assert.equal(hook.statusUpdates.at(-1), "error");
hook.browser.advance(PERIODIC_INTERVAL_MS + 1);
hook.browser.fireIntervals(PERIODIC_INTERVAL_MS);
hook.browser.fireWindow("focus");
await settle();
assert.equal(hook.checks(), 1);
- assert.equal(hook.statusUpdates.at(-1), "preparing");
+ assert.equal(hook.statusUpdates.at(-1), "error");
});
-test("scheduled checks preserve update recovery", async (t) => {
- const hook = hookHarness(t);
+test("a bundle download the update did not start reports its progress", async (t) => {
+ const hook = hookHarness(t, {
+ backendUpdate: "completes",
+ // A webview reload left a native download running, and a second one would be refused.
+ bundleStates: [
+ { version: "2.0.0", downloaded: false, downloading: true },
+ { version: "2.0.0", downloaded: false, downloading: true },
+ { version: "2.0.0", downloaded: true, downloading: false },
+ ],
+ });
hook.browser.fireTimeouts(STARTUP_DELAY_MS);
await settle();
- await hook.controller.installUpdate();
+
+ const installing = hook.controller.installUpdate();
await settle();
- assert.equal(hook.statusUpdates.at(-1), "ready");
+ assert.deepEqual(hook.download.attached, ["2.0.0"]);
+ hook.download.report(40);
- await hook.controller.installUpdate();
- assert.equal(hook.statusUpdates.at(-1), "error");
+ hook.browser.fireTimeouts(BUNDLE_POLL_MS);
+ await settle();
+ assert.deepEqual(hook.download.attached, ["2.0.0"]);
- hook.browser.advance(PERIODIC_INTERVAL_MS + 1);
- hook.browser.fireIntervals(PERIODIC_INTERVAL_MS);
- hook.browser.fireWindow("focus");
+ hook.browser.fireTimeouts(BUNDLE_POLL_MS);
await settle();
- assert.equal(hook.checks(), 1);
- assert.equal(hook.statusUpdates.at(-1), "error");
+ await installing;
+
+ assert.equal(hook.polls(), 3);
+ assert.equal(hook.download.started, 0);
+ assert.equal(hook.download.released, 1);
+ assert.ok(hook.progressUpdates.includes(40));
+ assert.equal(hook.progressUpdates.at(-1), 100);
+ assert.equal(hook.relaunches(), 1);
+});
+
+test("waiting out a bundle download the update did not start is bounded", async (t) => {
+ const hook = hookHarness(t, {
+ backendUpdate: "completes",
+ // Stuck: the flag never clears, so without the bound the update waits forever.
+ bundleStates: [{ version: "2.0.0", downloaded: false, downloading: true }],
+ });
+ hook.browser.fireTimeouts(STARTUP_DELAY_MS);
+ await settle();
+
+ const installing = hook.controller.installUpdate();
+ await settle();
+ assert.deepEqual(hook.download.attached, ["2.0.0"]);
+
+ hook.browser.advance(BUNDLE_WAIT_MS);
+ hook.browser.fireTimeouts(BUNDLE_POLL_MS);
+ await settle();
+ await installing;
+
+ // Handed back to the real download, which is what surfaces the failure.
+ assert.equal(hook.download.started, 1);
+ assert.equal(hook.download.released, 1);
});
test("restoring an overdue hidden window checks immediately", async (t) => {
diff --git a/studio/frontend/tests/update-preparation.test.ts b/studio/frontend/tests/update-preparation.test.ts
deleted file mode 100644
index de413b091cb..00000000000
--- a/studio/frontend/tests/update-preparation.test.ts
+++ /dev/null
@@ -1,272 +0,0 @@
-// 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/src-tauri/src/commands.rs b/studio/src-tauri/src/commands.rs
index ba16a1493f1..97272e6db02 100644
--- a/studio/src-tauri/src/commands.rs
+++ b/studio/src-tauri/src/commands.rs
@@ -1,8 +1,6 @@
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};
@@ -350,12 +348,7 @@ pub async fn start_server(
info!("start_server command called with port {}", port);
let diagnostics_state = diagnostics.inner().clone();
- 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),
- };
+ let generation = process::start_backend(&app, &state, port, &shutdown, &diagnostics_state)?;
// Spawn health watchdog for the owned backend — detects
// deadlocks and hangs that stdout-based crash detection misses.
@@ -390,12 +383,7 @@ pub async fn start_managed_server(
let started = Instant::now();
let diagnostics_state = diagnostics.inner().clone();
- 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),
- };
+ let generation = process::start_backend(&app, &state, port, &shutdown, &diagnostics_state)?;
info!(
"start_managed_server spawned generation={} in {}ms",
@@ -839,81 +827,6 @@ 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.
///
@@ -2300,10 +2213,7 @@ async fn health_watchdog(
"missing_validated_port",
);
error!("Health watchdog: backend never reported a validated port, killing and declaring dead");
- let stopped = process::stop_backend(&state, &shutdown, Some(&diagnostics));
- if stopped.is_ok() && process::request_staged_rollback_restart(&app, &state) {
- break;
- }
+ let _ = process::stop_backend(&state, &shutdown, Some(&diagnostics));
let _ = app.emit("server-crashed", ());
break;
}
@@ -2426,10 +2336,7 @@ async fn health_watchdog(
} else {
error!("Health watchdog: backend unresponsive, killing and declaring dead");
// Kill the zombie process so retry can start fresh
- let stopped = process::stop_backend(&state, &shutdown, Some(&diagnostics));
- if stopped.is_ok() && process::request_staged_rollback_restart(&app, &state) {
- break;
- }
+ let _ = process::stop_backend(&state, &shutdown, Some(&diagnostics));
}
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 25a06c3d61f..4d7dfb296e9 100644
--- a/studio/src-tauri/src/desktop_backend_owner.rs
+++ b/studio/src-tauri/src/desktop_backend_owner.rs
@@ -79,7 +79,6 @@ pub(crate) struct VerifiedOwnedBackend {
pub backend_pid: u32,
pub generation: u64,
pub readiness: OwnedBackendReadiness,
- pub backend_version: Option<String>,
}
#[allow(dead_code)]
@@ -127,7 +126,6 @@ struct HealthDesktopOwner {
struct HealthResponse {
version: Option<String>,
native_path_leases_supported: Option<bool>,
- torch_warm_in_progress: Option<bool>,
}
#[derive(Debug)]
@@ -827,6 +825,37 @@ 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,
@@ -937,34 +966,8 @@ 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?;
- 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),
- ))
+ health_ready_status(port, Some(&access_token)).await
}
pub(crate) async fn probe_owned_backend_state(
@@ -988,24 +991,6 @@ 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(),
@@ -1031,73 +1016,58 @@ async fn probe_owned_backend_state_with_warmup(
continue;
}
if let Some(reason) = lifecycle_control_block_reason(&liveness) {
- return (OwnedBackendProbe::Unmanageable { port, reason }, false);
+ return OwnedBackendProbe::Unmanageable { port, reason };
}
if !desktop_login_route_compatible(port, timeout).await {
- return (
- OwnedBackendProbe::Unmanageable {
- port,
- reason: "desktop_login_probe_failed".to_string(),
- },
- false,
- );
+ return OwnedBackendProbe::Unmanageable {
+ port,
+ reason: "desktop_login_probe_failed".to_string(),
+ };
}
- let (readiness, backend_version, torch_warm_in_progress) = if require_desktop_secret {
+ let readiness = 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(),
- },
- false,
- )
+ return OwnedBackendProbe::Unmanageable {
+ port,
+ reason: "desktop_auth_secret_missing".to_string(),
+ }
}
- Err(reason) => return (OwnedBackendProbe::Unmanageable { port, reason }, false),
+ 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),
+ match authenticated_health_ready_status(port, &secret).await {
+ Ok(readiness) => readiness,
+ Err(reason) => return OwnedBackendProbe::Unmanageable { port, reason },
}
} 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, None, false)
+ OwnedBackendReadiness::Ready
};
- verified.push((port, readiness, backend_version, torch_warm_in_progress));
+ verified.push((port, readiness));
}
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, 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,
- )
+ let (port, readiness) = verified.remove(0);
+ OwnedBackendProbe::Verified(VerifiedOwnedBackend {
+ backend_pid: owner.backend_pid(),
+ generation: owner.generation(),
+ owner,
+ port,
+ readiness,
+ })
}
#[allow(dead_code)]
@@ -1444,15 +1414,12 @@ mod tests {
])
.await;
- let (readiness, version, torch_warm_in_progress) =
- authenticated_health_ready(port, "desktop-test-secret")
- .await
- .unwrap();
+ let readiness = authenticated_health_ready_status(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]
@@ -1460,28 +1427,6 @@ 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 be8e09bfc4c..724ede196cf 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> {
}
}
-pub(crate) fn compare_versions(left: &str, right: &str) -> i8 {
+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 d82096ca9d9..110fb51cfdc 100644
--- a/studio/src-tauri/src/desktop_updater.rs
+++ b/studio/src-tauri/src/desktop_updater.rs
@@ -137,26 +137,6 @@ 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 {
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index 730e7bd6628..8b8871131ff 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -31,7 +31,7 @@ use process::new_backend_state;
use simplelog::{
CombinedLogger, Config, LevelFilter, SharedLogger, TermLogger, TerminalMode, WriteLogger,
};
-use std::ffi::{OsStr, OsString};
+use std::ffi::OsStr;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
@@ -50,9 +50,6 @@ 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
@@ -1823,71 +1820,7 @@ 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();
@@ -1968,10 +1901,6 @@ 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,
@@ -2030,13 +1959,10 @@ 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(),
- );
+ staged_update::reconcile_legacy_at_launch(&diagnostics::studio_dir());
Ok(())
}) {
- warn!("Staged update activation deferred: {error}");
+ warn!("Legacy staged update cleanup deferred: {error}");
}
// Recover legacy desktop installs before the first preflight.
if let Err(error) = desktop_backend_owner::ensure_installed_studio_root_id() {
@@ -2186,23 +2112,6 @@ 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 13c3b223312..c8dc2bd7427 100644
--- a/studio/src-tauri/src/preflight.rs
+++ b/studio/src-tauri/src/preflight.rs
@@ -509,7 +509,6 @@ mod tests {
readiness: OwnedBackendReadiness::Stale {
reason: "backend_outdated".to_string(),
},
- backend_version: None,
},
)
};
diff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rs
index 5694dda788a..5dae83906cd 100644
--- a/studio/src-tauri/src/process.rs
+++ b/studio/src-tauri/src/process.rs
@@ -3461,7 +3461,6 @@ 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 || {
@@ -3469,7 +3468,6 @@ pub fn start_backend(
stdout,
&app_handle,
&state_clone,
- &shutdown_clone,
&diagnostics_clone,
&backend_log_clone,
false,
@@ -3482,7 +3480,6 @@ 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 || {
@@ -3490,7 +3487,6 @@ pub fn start_backend(
stderr,
&app_handle,
&state_clone,
- &shutdown_clone,
&diagnostics_clone,
&backend_log_clone,
true,
@@ -3503,40 +3499,6 @@ 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)) {
@@ -3628,57 +3590,9 @@ 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,
@@ -3686,10 +3600,6 @@ 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,
@@ -3717,7 +3627,6 @@ 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
@@ -3726,62 +3635,17 @@ async fn validate_candidate_port(
break false;
}
attempts += 1;
- 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,
- )
+ let ok = if let Some(owner) = owner.clone() {
+ matches!(
+ 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,
- 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)
+ crate::desktop_backend_owner::VerifiedOwnedBackend { port: verified_port, .. }
+ ) if verified_port == port
+ )
} else {
- (generic_backend_health_ok(port).await, false)
+ generic_backend_health_ok(port).await
};
- 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
@@ -3811,14 +3675,6 @@ 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",
@@ -3861,23 +3717,6 @@ 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,
@@ -4000,7 +3839,6 @@ 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,
@@ -4071,14 +3909,12 @@ 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,
@@ -4200,9 +4036,6 @@ 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", ());
}
@@ -6123,99 +5956,6 @@ 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/staged_update.rs b/studio/src-tauri/src/staged_update.rs
index 91e3338f8be..f0aeecaf829 100644
--- a/studio/src-tauri/src/staged_update.rs
+++ b/studio/src-tauri/src/staged_update.rs
@@ -1,15 +1,20 @@
+//! Cleans up what the 805-807 background update left on disk. Nothing here activates a stage.
+//!
+//! Those releases cloned the managed runtime into `.update-stage`, swapped it in at the next
+//! launch and kept the replaced trees in `.update-prev` until a health probe confirmed the new
+//! backend. An install that took such an update can still carry a half-written stage, an
+//! unconfirmed runtime, or rollback trash. Every step below is a rename or a delete, so
+//! running it twice does nothing the first run did not.
+
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 serde::Deserialize;
+use std::fs;
use std::path::{Path, PathBuf};
-pub(crate) const STAGE_DIR: &str = ".update-stage";
+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";
@@ -34,118 +39,103 @@ fn live_entry(home: &Path, name: &str) -> PathBuf {
}
}
-#[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)]
+/// The 807 journal also carried `backend_version` and `shell_version`. Unknown fields are
+/// ignored, so a journal from any of 805-807 still parses.
+#[derive(Clone, Debug, Default, Deserialize, 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)
+/// Undo whatever a 805-807 background update left behind, then never stage again.
+pub(crate) fn reconcile_legacy_at_launch(home: &Path) {
+ remove_stale_trash(home);
+ // Written by the old shell's fail-fast path and by this wheel's refusal; read by nothing here.
+ let _ = fs::remove_file(home.join(FAILED_MARKER));
+ // Before the rollback, not after: a READY stage must never be activated, and a rollback that
+ // still saw one would leave unrestored entries live beside the restored runtime.
+ discard_stage(home);
+ if let Err(error) = roll_back_unconfirmed(home) {
+ warn!("[staged-update] could not restore the previous runtime: {error}");
+ }
}
-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(())
+/// Settle a deferred legacy rollback before an update mutates the live runtime.
+///
+/// `reconcile_legacy_at_launch` leaves a PENDING journal alone while a backend is on the tree,
+/// which is right at launch and wrong afterwards: a classic update would install into a runtime
+/// the journal still names as something to undo, and the next idle launch would restore the
+/// pre-update trees over it. Refusing beats updating a runtime about to be replaced by a backup.
+pub(crate) fn reconcile_before_update(home: &Path) -> Result<(), String> {
+ // Nothing a 805-807 update left behind, so nothing to probe for.
+ if !home.join(PREV_DIR).is_dir() && !home.join(STAGE_DIR).exists() {
+ return Ok(());
+ }
+ reconcile_before_update_with(home, live_tree_in_use(home))
}
-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);
+fn reconcile_before_update_with(home: &Path, in_use: bool) -> Result<(), String> {
+ // Restarting is the whole fix: an idle launch finishes the rollback itself, and on POSIX the
+ // backend this update would replace is usually the one holding the tree.
+ const RESTART: &str =
+ "An unfinished background update from an earlier release is still waiting on a \
+ running backend. Quit Unsloth Studio, reopen it, and update again.";
+ if in_use {
+ return Err(RESTART.to_string());
}
- if let Some(versions) = read_versions(&home.join(FAILED_MARKER)) {
- return StagedUpdateStatus::with("failed", Some(versions));
+ discard_stage(home);
+ roll_back_unconfirmed_with(home, false)?;
+ if home.join(PREV_DIR).join(PENDING_MARKER).is_file() {
+ return Err(RESTART.to_string());
}
- StagedUpdateStatus::with("none", None)
+ Ok(())
}
-pub(crate) fn discard(home: &Path) {
- let _ = fs::remove_dir_all(home.join(STAGE_DIR));
+/// A rename, not a delete: `.update-stage` holds a clone of the managed venv and every native
+/// helper, and unlinking a torch tree here would hold the runtime gate through all of setup.
+/// Move it into the trash namespace a later launch sweeps anyway.
+fn discard_stage(home: &Path) {
+ discard_stage_with(home, |from, to| fs::rename(from, to));
}
-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}");
+fn discard_stage_with(home: &Path, rename: impl Fn(&Path, &Path) -> std::io::Result<()>) {
+ let stage = home.join(STAGE_DIR);
+ if !stage.exists() {
return;
}
- if let Err(error) = activate_ready(home, shell_version) {
- warn!("[staged-update] activation failed: {error}");
+ let trash = trash_path(home, "stage");
+ if rename(&stage, &trash).is_ok() {
+ std::thread::spawn(move || {
+ let _ = fs::remove_dir_all(trash);
+ });
+ return;
}
+ // Also off the launch path. On Windows the rename fails exactly when a file inside is still
+ // open, which is the multi-gigabyte case the background delete exists for. Nothing activates
+ // a stage any more, so a tree that outlives this call is inert.
+ std::thread::spawn(move || {
+ let _ = fs::remove_dir_all(stage);
+ });
+}
+
+/// Distinct within a launch as well as between launches: a coarse clock can hand two calls the
+/// same reading, and the second rename would land on the first call's trash directory.
+static TRASH_SEQUENCE: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
+
+fn trash_path(home: &Path, label: &str) -> PathBuf {
+ let suffix = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap_or_default()
+ .as_nanos();
+ let sequence = TRASH_SEQUENCE.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ home.join(format!(
+ "{ROLLBACK_TRASH_PREFIX}{label}-{}-{suffix}-{sequence}",
+ std::process::id()
+ ))
}
fn remove_stale_trash(home: &Path) {
@@ -171,113 +161,59 @@ fn remove_stale_trash(home: &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;
+/// Quarantine the confirmed backup, then unlink it off that path.
+///
+/// A delete in place would take entries out from under the marker vouching for the live runtime,
+/// and an interrupted one would leave a `.update-prev` the next launch reads as an unconfirmed
+/// activation and rolls back to. The rename is the whole decision, and it is atomic.
+fn quarantine_confirmed_previous(home: &Path, prev: PathBuf) {
+ let trash = trash_path(home, "confirmed");
+ if fs::rename(&prev, &trash).is_err() {
+ // Still confirmed and consistent, and every step here repeats safely: leave it for the
+ // next launch rather than start a delete that could strand the marker.
+ warn!("[staged-update] could not quarantine the confirmed backup, leaving it for the next launch");
+ return;
}
- info!("[staged-update] backend healthy, dropping previous runtime");
std::thread::spawn(move || {
- remove_confirmed_previous(&prev);
+ let _ = fs::remove_dir_all(trash);
});
- 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);
+ // `live_tree_in_use` reads every pid record and, on Windows, probes the managed environment.
+ // An install that never took a 805-807 update has nothing to decide and must not pay for it.
+ if !home.join(PREV_DIR).is_dir() {
+ return Ok(());
}
- restart();
- Ok(true)
+ roll_back_unconfirmed_with(home, live_tree_in_use(home))
}
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);
+ // 807 vouched for the runtime that is live now. Keep it and drop the copy off the launch path.
+ quarantine_confirmed_previous(home, 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));
+ if prev.join(ROLLED_BACK_MARKER).is_file() {
+ // The restore already happened; only the bookkeeping is left.
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 journal.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.
+ // Renaming the tree under a live process is unsafe and this runtime was never confirmed,
+ // so leave the marker and decide at the next launch.
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())
@@ -287,15 +223,9 @@ fn roll_back_unconfirmed_with(home: &Path, in_use: bool) -> Result<(), String> {
.map(str::to_string)
.collect()
});
- info!("[staged-update] staged backend never became healthy, restoring previous runtime");
+ info!("[staged-update] restoring the runtime a background update replaced");
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_file(prev.join(PENDING_MARKER));
let _ = fs::remove_dir_all(&prev);
std::thread::spawn(move || {
let _ = fs::remove_dir_all(trash);
@@ -303,157 +233,20 @@ fn roll_back_unconfirmed_with(home: &Path, in_use: bool) -> Result<(), String> {
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,
- }
-}
-
+/// An entry the previous runtime did not have is moved aside rather than left: a legacy install
+/// has nothing to put back for tiered sidecars, so the restored backend would otherwise import
+/// from an environment nothing ever confirmed.
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()
- ));
+ let trash = trash_path(home, "rollback");
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() {
@@ -462,7 +255,7 @@ fn restore_previous_runtime(
}
rename_tracked(&old, &live, &mut moved)?;
}
- } else if !staged.exists() && live.exists() {
+ } else if live.exists() {
rename_tracked(&live, &trash.join(name), &mut moved)?;
}
}
@@ -476,44 +269,6 @@ fn restore_previous_runtime(
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,
@@ -527,13 +282,10 @@ fn rename_tracked(
/// 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.
+/// Mirrors `live_sibling_backend` in studio/backend/run.py and reads all three record kinds,
+/// since a backend may have only one: a startup marker while binding, a per-port record once
+/// bound, a bare `studio.pid` otherwise. Markers matter most: the backend keeps its marker after
+/// dropping its pid records, and renaming the tree in that window moves it under a live importer.
fn recorded_pids(home: &Path) -> Vec<u32> {
let mut pids = Vec::new();
let mut timed = Vec::new();
@@ -543,8 +295,7 @@ fn recorded_pids(home: &Path) -> Vec<u32> {
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.
+ // Markers share the per-port record layout, so both carry the start time.
let pid = name
.strip_suffix(".marker")
.and_then(|rest| rest.strip_prefix("studio-starting-"))
@@ -557,8 +308,7 @@ fn recorded_pids(home: &Path) -> Vec<u32> {
let Some(pid) = pid else {
continue;
};
- // Judged either way, so the untimed legacy record below must not
- // resurrect a pid this evidence already rejected.
+ // Judged either way, so the untimed legacy record must not resurrect this pid.
timed.push(pid);
if crate::process_identity::pid_start_time_matches(
pid,
@@ -570,8 +320,7 @@ fn recorded_pids(home: &Path) -> Vec<u32> {
}
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.
+ // It carries no start time, so alone it would re-add a pid proved reused.
if !timed.contains(&pid) {
pids.push(pid);
}
@@ -605,26 +354,33 @@ fn live_tree_in_use(home: &Path) -> bool {
mod tests {
use super::*;
+ const READY_MARKER: &str = "READY.json";
+
+ /// Always one level below a private container: `live_entry` resolves the native helpers
+ /// against the parent, so a home directly under the temp directory would have the rollback
+ /// renaming whatever sits beside it.
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
+ let home = 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()
+ ))
+ .join("studio");
+ fs::create_dir_all(&home).unwrap();
+ home
}
- /// 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.
+ /// Two code paths drop a tree on a background thread, and Windows refuses to remove a
+ /// directory while another handle walks inside it, so a racing teardown fails with
+ /// ERROR_ACCESS_DENIED. Retry until the deleter is done.
fn cleanup(home: PathBuf) {
for _ in 0..100 {
if fs::remove_dir_all(&home).is_ok() || !home.exists() {
+ let _ = home.parent().map(fs::remove_dir_all);
return;
}
std::thread::sleep(std::time::Duration::from_millis(20));
@@ -632,6 +388,15 @@ mod tests {
fs::remove_dir_all(&home).unwrap();
}
+ fn wait_gone(path: &Path) {
+ for _ in 0..250 {
+ if !path.exists() {
+ return;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(20));
+ }
+ }
+
fn make_runtime(root: &Path, tag: &str) {
for name in RUNTIME_ENTRIES {
fs::create_dir_all(root.join(name)).unwrap();
@@ -643,202 +408,217 @@ mod tests {
fs::read_to_string(root.join(name).join("tag")).unwrap_or_default()
}
- fn stage_ready(home: &Path, versions: &StagedVersions) {
+ /// The marker bodies 805-807 wrote, versions and all.
+ fn write_marker(path: &Path, previous_entries: &[String]) {
+ fs::create_dir_all(path.parent().unwrap()).unwrap();
+ let body = serde_json::json!({
+ "backend_version": "2026.9.1",
+ "shell_version": "0.1.900-beta",
+ "previous_entries": previous_entries,
+ });
+ fs::write(path, serde_json::to_vec_pretty(&body).unwrap()).unwrap();
+ }
+
+ fn stage_ready(home: &Path) {
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();
+ write_marker(&stage.join(READY_MARKER), &[]);
}
- fn versions(shell: Option<&str>) -> StagedVersions {
- StagedVersions {
- backend_version: "2026.9.1".into(),
- shell_version: shell.map(str::to_string),
+ /// What 805-807 did at activation: live trees into `.update-prev`, staged trees into their
+ /// place, a PENDING journal naming what was displaced.
+ fn activate_by_hand(home: &Path) -> Vec<String> {
+ let stage = home.join(STAGE_DIR);
+ let prev = home.join(PREV_DIR);
+ fs::create_dir_all(&prev).unwrap();
+ let previous_entries: Vec<String> = all_runtime_entries()
+ .filter(|name| live_entry(home, name).exists())
+ .map(str::to_string)
+ .collect();
+ write_marker(&prev.join(PENDING_MARKER), &previous_entries);
+ for name in all_runtime_entries() {
+ let staged = stage.join(name);
+ let live = live_entry(home, name);
+ if !staged.exists() {
+ continue;
+ }
+ if live.exists() {
+ fs::rename(&live, prev.join(name)).unwrap();
+ }
+ fs::rename(&staged, &live).unwrap();
}
+ let _ = fs::remove_dir_all(&stage);
+ previous_entries
}
#[test]
- fn ready_stage_replaces_the_runtime_and_keeps_the_previous_one_pending() {
- let home = temp_home("activate");
+ fn a_ready_stage_is_deleted_and_never_activated() {
+ let home = temp_home("ready-stage");
make_runtime(&home, "old");
- stage_ready(&home, &versions(Some("0.1.900-beta")));
+ stage_ready(&home);
- reconcile_at_launch(&home, "0.1.900-beta");
+ reconcile_legacy_at_launch(&home);
- 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"))));
+ // Renamed aside rather than unlinked, so the stage is unreachable once the call returns.
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!(!home.join(PREV_DIR).exists());
+ // Safe to repeat: nothing left to do and nothing undone.
+ reconcile_legacy_at_launch(&home);
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");
+ fn a_ready_stage_is_discarded_before_the_rollback_it_would_otherwise_survive() {
+ // 807 crashed mid-swap: the managed venv is the staged one, the sidecars are not, and the
+ // stage still holds the entries the swap never reached.
+ let home = temp_home("ready-stage-and-pending");
make_runtime(&home, "old");
- stage_ready(&home, &versions(Some("0.1.899-beta")));
+ stage_ready(&home);
+ let stage = home.join(STAGE_DIR);
+ let prev = home.join(PREV_DIR);
+ let previous_entries: Vec<String> = RUNTIME_ENTRIES
+ .iter()
+ .map(|name| (*name).to_string())
+ .collect();
+ write_marker(&prev.join(PENDING_MARKER), &previous_entries);
+ fs::rename(home.join("unsloth_studio"), prev.join("unsloth_studio")).unwrap();
+ fs::rename(stage.join("unsloth_studio"), home.join("unsloth_studio")).unwrap();
+ assert_eq!(tag(&home, "unsloth_studio"), "new");
+ assert!(stage.join(".venv_t5_530").exists());
- reconcile_at_launch(&home, "0.1.900-beta");
+ reconcile_legacy_at_launch(&home);
- assert_eq!(tag(&home, "unsloth_studio"), "old");
- assert!(!home.join(STAGE_DIR).exists());
+ // The discard runs first, so the rollback cannot leave a fourth staged entry live.
+ for name in RUNTIME_ENTRIES {
+ assert_eq!(tag(&home, name), "old", "{name}");
+ }
+ assert!(!stage.exists());
+ assert!(!prev.exists());
cleanup(home);
}
#[test]
- fn incomplete_stage_is_removed() {
- let home = temp_home("partial");
+ fn a_stage_that_cannot_be_renamed_is_still_swept() {
+ let home = temp_home("stage-rename-fails");
make_runtime(&home, "old");
- make_runtime(&home.join(STAGE_DIR), "half");
- assert_eq!(status(&home).state, "partial");
+ stage_ready(&home);
+ let stage = home.join(STAGE_DIR);
- reconcile_at_launch(&home, "0.1.900-beta");
+ // Windows refuses the rename while a file inside is open, the one case the background
+ // delete exists for, so the fallback runs off the launch path too.
+ discard_stage_with(&home, |_, _| Err(std::io::Error::other("rename refused")));
+ wait_gone(&stage);
+ assert!(!stage.exists());
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();
+ fn two_trash_names_in_one_launch_never_collide() {
+ let home = temp_home("trash-names");
- reconcile_at_launch(&home, "0.1.900-beta");
+ let first = trash_path(&home, "stage");
+ let second = trash_path(&home, "stage");
- assert_eq!(tag(&home, "unsloth_studio"), "old");
- assert!(!home.join(STAGE_DIR).exists());
- assert_eq!(status(&home).state, "failed");
+ assert_ne!(first, second);
+ for path in [&first, &second] {
+ let name = path.file_name().unwrap().to_str().unwrap();
+ // Still swept by `remove_stale_trash`, which matches on the prefix alone.
+ assert!(name.starts_with(ROLLBACK_TRASH_PREFIX), "{name}");
+ }
cleanup(home);
}
#[test]
- fn unconfirmed_activation_rolls_back_and_records_the_failure() {
- let home = temp_home("rollback");
+ fn a_retained_desktop_update_bundle_survives_the_cleanup() {
+ // The classic update installs this bundle after the backend step, in the same directory.
+ let home = temp_home("bundle");
make_runtime(&home, "old");
- stage_ready(&home, &versions(None));
- reconcile_at_launch(&home, "0.1.900-beta");
- assert_eq!(tag(&home, "unsloth_studio"), "new");
+ stage_ready(&home);
+ for name in [".desktop-update-bundle", ".desktop-update-bundle.json"] {
+ fs::write(home.join(name), b"bundle").unwrap();
+ }
- reconcile_at_launch(&home, "0.1.900-beta");
+ reconcile_legacy_at_launch(&home);
- 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"));
+ for name in [".desktop-update-bundle", ".desktop-update-bundle.json"] {
+ assert_eq!(fs::read(home.join(name)).unwrap(), b"bundle", "{name}");
+ }
cleanup(home);
}
#[test]
- fn failed_activation_rolls_back_once_without_waiting_for_an_app_relaunch() {
- let home = temp_home("same-launch-rollback");
+ fn a_half_written_stage_is_removed() {
+ let home = temp_home("partial-stage");
make_runtime(&home, "old");
- stage_ready(&home, &versions(None));
- activate_ready(&home, "0.1.900-beta").unwrap();
+ make_runtime(&home.join(STAGE_DIR), "half");
+
+ reconcile_legacy_at_launch(&home);
- 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);
+ assert!(!home.join(STAGE_DIR).exists());
cleanup(home);
}
#[test]
- fn failed_activation_waits_until_the_live_runtime_is_unused() {
- let home = temp_home("same-launch-live");
+ fn the_compatibility_failure_marker_is_removed_at_launch() {
+ let home = temp_home("failed-marker");
make_runtime(&home, "old");
- stage_ready(&home, &versions(None));
- activate_ready(&home, "0.1.900-beta").unwrap();
- let me = std::process::id();
+ // What an 807 shell's `--stage` attempt against this wheel leaves behind.
fs::write(
- home.join(format!("studio-starting-{me}.marker")),
- format!("{me}\n"),
+ home.join(FAILED_MARKER),
+ r#"{"backend_version": "2026.9.1", "shell_version": "0.1.807-beta"}"#,
)
.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);
+ reconcile_legacy_at_launch(&home);
+
+ assert!(!home.join(FAILED_MARKER).exists());
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
cleanup(home);
}
#[test]
- fn confirmation_drops_the_previous_runtime_and_the_next_launch_keeps_the_new_one() {
- let home = temp_home("confirm");
+ fn an_unconfirmed_activation_is_rolled_back_at_launch() {
+ let home = temp_home("rollback");
make_runtime(&home, "old");
- stage_ready(&home, &versions(None));
- reconcile_at_launch(&home, "0.1.900-beta");
+ stage_ready(&home);
+ activate_by_hand(&home);
+ assert_eq!(tag(&home, "unsloth_studio"), "new");
- 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");
+ reconcile_legacy_at_launch(&home);
- assert_eq!(tag(&home, "unsloth_studio"), "new");
- assert_eq!(status(&home).state, "none");
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
+ assert_eq!(tag(&home, ".venv_t5_530"), "old");
+ assert!(!home.join(PREV_DIR).exists());
+ assert!(!home.join(FAILED_MARKER).exists());
+
+ reconcile_legacy_at_launch(&home);
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
cleanup(home);
}
#[test]
- fn an_older_backend_cannot_confirm_a_newer_activation() {
- let home = temp_home("confirm-version");
+ fn an_807_journal_with_extra_fields_still_names_the_entries_to_restore() {
+ let home = temp_home("journal-compat");
make_runtime(&home, "old");
- stage_ready(&home, &versions(None));
- activate_ready(&home, "0.1.900-beta").unwrap();
+ let prev = home.join(PREV_DIR);
+ fs::create_dir_all(&prev).unwrap();
+ let body = r#"{
+ "backend_version": "2026.9.1",
+ "shell_version": "0.1.807-beta",
+ "previous_entries": ["unsloth_studio", ".venv_t5_530"],
+ "unknown_807_field": 7
+ }"#;
+ fs::write(prev.join(PENDING_MARKER), body).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));
- }
+ let journal = read_journal(&prev.join(PENDING_MARKER)).unwrap();
+
+ assert_eq!(journal.previous_entries, ["unsloth_studio", ".venv_t5_530"]);
cleanup(home);
}
@@ -847,15 +627,12 @@ mod tests {
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));
+ stage_ready(&home);
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 previous_entries: Vec<String> =
+ RUNTIME_ENTRIES.iter().map(|name| (*name).to_string()).collect();
+ write_marker(&prev.join(PENDING_MARKER), &previous_entries);
let mut completed = 0;
for name in RUNTIME_ENTRIES {
@@ -870,6 +647,7 @@ mod tests {
fs::rename(stage.join(name), home.join(name)).unwrap();
completed += 1;
}
+ let _ = fs::remove_dir_all(&stage);
roll_back_unconfirmed_with(&home, false).unwrap();
@@ -885,21 +663,9 @@ mod tests {
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);
+ stage_ready(&home);
+ let previous_entries = activate_by_hand(&home);
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();
@@ -913,20 +679,17 @@ mod tests {
}
#[test]
- fn an_interrupted_rollback_marker_recreates_the_failed_version() {
+ fn an_interrupted_rollback_marker_only_drops_the_bookkeeping() {
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();
+ write_marker(&prev.join(ROLLED_BACK_MARKER), &[]);
- roll_back_unconfirmed_with(&home, false).unwrap();
+ reconcile_legacy_at_launch(&home);
- assert_eq!(read_versions(&home.join(FAILED_MARKER)), Some(versions(None)));
+ // The restore already ran; this launch neither redoes it nor leaves a marker.
+ assert!(!home.join(FAILED_MARKER).exists());
assert_eq!(tag(&home, "unsloth_studio"), "old");
- assert!(!stage.exists());
assert!(!prev.exists());
cleanup(home);
}
@@ -935,59 +698,84 @@ mod tests {
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();
+ stage_ready(&home);
+ activate_by_hand(&home);
let prev = home.join(PREV_DIR);
- write_versions(&prev.join(CONFIRMED_MARKER), &versions(None)).unwrap();
+ write_marker(&prev.join(CONFIRMED_MARKER), &[]);
- roll_back_unconfirmed_with(&home, false).unwrap();
+ reconcile_legacy_at_launch(&home);
+ // The superseded runtime is dropped on a background thread.
+ wait_gone(&prev);
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");
+ fn a_confirmed_backup_leaves_the_directory_the_moment_it_is_dropped() {
+ let home = temp_home("confirmed-quarantine");
make_runtime(&home, "old");
- let stage = home.join(STAGE_DIR);
- make_runtime(&stage, "new");
+ stage_ready(&home);
+ activate_by_hand(&home);
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();
+ write_marker(&prev.join(CONFIRMED_MARKER), &[]);
- let result = swap_entries(&home, &stage, &prev, false);
+ roll_back_unconfirmed_with(&home, false).unwrap();
- 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");
+ // Renamed, not emptied: a delete in place would take entries out from under the
+ // confirmation, and an interrupted one would leave a backup with no marker.
+ assert!(!prev.exists());
+ assert_eq!(tag(&home, "unsloth_studio"), "new");
+
+ reconcile_legacy_at_launch(&home);
+ assert_eq!(tag(&home, "unsloth_studio"), "new");
cleanup(home);
}
#[test]
- fn swapping_back_restores_the_runtime_the_activation_replaced() {
- let home = temp_home("swap-back");
+ fn a_deferred_rollback_is_settled_before_an_update_touches_the_runtime() {
+ let home = temp_home("before-update");
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();
+ stage_ready(&home);
+ activate_by_hand(&home);
+ // The launch found a backend on the tree and left the decision for later.
+ roll_back_unconfirmed_with(&home, true).unwrap();
+ assert!(home.join(PREV_DIR).join(PENDING_MARKER).is_file());
+
+ reconcile_before_update_with(&home, false).unwrap();
+
+ // Settled here, so no later launch can put this backup back over the update.
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
+ assert!(!home.join(PREV_DIR).exists());
+ cleanup(home);
+ }
+
+ #[test]
+ fn an_update_is_refused_while_a_deferred_rollback_cannot_be_settled() {
+ let home = temp_home("before-update-busy");
+ make_runtime(&home, "old");
+ stage_ready(&home);
+ activate_by_hand(&home);
+
+ let error = reconcile_before_update_with(&home, true).unwrap_err();
- swap_entries(&home, &stage, &prev, false).unwrap();
+ // Restarting is what settles it, so the message says that and not a path.
+ assert!(error.contains("Quit Unsloth Studio"), "{error}");
+ // Nothing moved, so the launch after this one still has its decision to make.
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();
+ assert!(home.join(PREV_DIR).join(PENDING_MARKER).is_file());
+ cleanup(home);
+ }
- for name in RUNTIME_ENTRIES {
- assert_eq!(tag(&home, name), "old", "{name}");
- assert_eq!(tag(&stage, name), "new", "{name}");
- }
+ #[test]
+ fn an_install_that_never_staged_has_nothing_to_settle_before_an_update() {
+ let home = temp_home("before-update-clean");
+ make_runtime(&home, "old");
+
+ reconcile_before_update(&home).unwrap();
+
+ assert_eq!(tag(&home, "unsloth_studio"), "old");
cleanup(home);
}
@@ -997,43 +785,37 @@ mod tests {
// 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");
+ // The 807 update built all of them and swapped them in.
+ stage_ready(&home);
+ activate_by_hand(&home);
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");
+ reconcile_legacy_at_launch(&home);
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();
+ fn native_helpers_roll_back_with_the_python_runtime() {
+ let home = temp_home("helpers");
+ let container = home.parent().unwrap().to_path_buf();
make_runtime(&home, "old");
- stage_ready(&home, &versions(None));
+ stage_ready(&home);
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();
-
+ activate_by_hand(&home);
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();
@@ -1041,49 +823,21 @@ mod tests {
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() {
+ fn a_runtime_still_in_use_defers_to_the_next_launch() {
let home = temp_home("defer");
make_runtime(&home, "old");
- stage_ready(&home, &versions(None));
- reconcile_at_launch(&home, "0.1.900-beta");
+ stage_ready(&home);
+ activate_by_hand(&home);
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.
+ // Force-closed after activation: a backend is alive on the new tree, so
+ // renaming it out from under that process is not an option.
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());
@@ -1091,7 +845,7 @@ mod tests {
roll_back_unconfirmed_with(&home, false).unwrap();
assert_eq!(tag(&home, "unsloth_studio"), "old");
- assert_eq!(status(&home).state, "failed");
+ assert!(!home.join(PREV_DIR).exists());
cleanup(home);
}
@@ -1102,7 +856,7 @@ mod tests {
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");
+ reconcile_legacy_at_launch(&home);
for _ in 0..50 {
if !trash.exists() {
break;
@@ -1119,8 +873,7 @@ mod tests {
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.
+ // The OS will not say, so neither the reuse guard nor its assertion can fire.
fs::remove_dir_all(home).ok();
return None;
}
@@ -1131,8 +884,7 @@ mod tests {
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.
+ // What a backend has while binding, and keeps after dropping its pid records.
fs::write(
home.join(format!("studio-starting-{me}.marker")),
format!("{me}\n"),
@@ -1149,8 +901,7 @@ mod tests {
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.
+ // A start time nowhere near this process: the pid has since been handed out again.
fs::write(
home.join(format!("studio-8888-{me}.pid")),
format!("{me}\n1.0\n"),
@@ -1172,45 +923,4 @@ mod tests {
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 dfd943dc465..0d52425dee9 100644
--- a/studio/src-tauri/src/update.rs
+++ b/studio/src-tauri/src/update.rs
@@ -7,83 +7,32 @@ use std::process::{Command, ExitStatus, Stdio};
use std::sync::{Arc, Mutex};
use tauri::{AppHandle, Emitter};
-// ── Types ──
#[derive(Default)]
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",
}
}
@@ -91,41 +40,31 @@ impl UpdateKind {
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, 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
- // types by hand, and the one that decides which install gets rewritten: a
- // user-site unsloth_cli must not be able to answer `from unsloth_cli import app`
- // here. Everything else inherits, because the console script does.
+ // Isolated, as this call site shipped: it is the one managed invocation nobody types by
+ // hand and the one that decides which install gets rewritten, so a user-site unsloth_cli
+ // must not answer `from unsloth_cli import app` here.
let mut cmd = crate::process::build_managed_cli_command_with(
bin,
args,
crate::process::Isolation::Isolated,
)?;
- // The only managed invocation that scrubs, and the only one that shipped doing it.
- // Elsewhere inheriting is the point, since the console script honours these. Here
- // 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.
+ // The only managed invocation that scrubs: a foreign PYTHONHOME stops the managed
+ // interpreter finding its own site-packages, and a PYTHONPATH pointing at another checkout
+ // updates the wrong install.
cmd.env_remove("PYTHONHOME");
cmd.env_remove("PYTHONPATH");
Ok(cmd)
}
fn configure_tauri_update_environment(cmd: &mut Command) {
- // The desktop owns both its shortcuts and its frontend bundle. The managed
- // Python update only needs backend dependencies and native helpers.
+ // The desktop owns its shortcuts and frontend bundle; this update needs only backend deps.
cmd.env_remove("UNSLOTH_STUDIO_HOME");
cmd.env_remove("STUDIO_HOME");
cmd.env("UNSLOTH_TAURI_UPDATE", "1");
@@ -136,30 +75,15 @@ 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);
- }
+// The shell holds the retained POSIX flock around the whole update child, so the CLI must
+// inherit the gate rather than take it again. Set everywhere, as Windows always did.
+fn configure_runtime_gate_environment(cmd: &mut Command) {
+ cmd.env(crate::process::STUDIO_RUNTIME_GATE_HANDOFF_ENV, "1");
}
fn spawn_update(
bin: &std::path::Path,
state: &UpdateState,
- kind: &UpdateKind,
) -> Result<
(
Option<std::process::ChildStdout>,
@@ -172,24 +96,11 @@ 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, kind.args())?;
+ let mut cmd = build_update_command(bin, UPDATE_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.
+ // A login-started desktop inherits C:\Windows\system32, which the CLI refuses to run from.
crate::process::apply_managed_cli_context(&mut cmd).map_err(|error| {
format!(
"Failed to pick a working directory for the update: {}",
@@ -197,22 +108,17 @@ fn spawn_update(
)
})?;
- // PYTHONPATH is dropped by the context itself on Windows, where -I covers
- // only the first interpreter and the update starts more.
+ // PYTHONPATH is dropped by the context itself on Windows, where -I covers only the first
+ // interpreter and the update starts more.
#[cfg(target_os = "linux")]
crate::process::scrub_appimage_python_env(&mut cmd);
- // Keep the update on the desktop-managed install and avoid rebuilding assets
- // that are already compiled into the signed Tauri bundle.
+ // Keep the update on the desktop-managed install and skip assets already in the bundle.
configure_tauri_update_environment(&mut cmd);
- if matches!(kind, UpdateKind::Staged { .. }) {
- configure_staged_update_environment(&mut cmd);
- }
- configure_runtime_gate_environment(&mut cmd, kind);
+ configure_runtime_gate_environment(&mut cmd);
- // read_lossy_lines decodes as UTF-8, and here the child is Python itself,
- // which otherwise encodes redirected streams with the locale code page.
+ // read_lossy_lines decodes as UTF-8; the child is Python, which otherwise uses the locale page.
#[cfg(windows)]
{
cmd.env("PYTHONUTF8", "1");
@@ -244,7 +150,6 @@ fn spawn_update(
Ok((stdout, stderr))
}
-// ── Stream ──
fn read_lossy_lines<R: std::io::Read>(
stream: R,
@@ -324,7 +229,6 @@ fn stream_output(
threads
}
-// ── Wait ──
fn wait_for_exit(state: &UpdateState) -> Result<(ExitStatus, bool), String> {
const MAX_WAIT_ITERATIONS: u32 = 72_000; // 2h at 100ms intervals
@@ -336,13 +240,11 @@ 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));
}
},
@@ -357,7 +259,6 @@ fn wait_for_exit(state: &UpdateState) -> Result<(ExitStatus, bool), String> {
Err("Update timed out after 2 hours".to_string())
}
-// ── Public API ──
pub fn run_backend_update(
app: AppHandle,
@@ -376,24 +277,6 @@ pub(crate) fn run_backend_update_for_repair(
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_update(
app: AppHandle,
state: UpdateState,
@@ -430,9 +313,16 @@ fn run_update(
let _ = app.emit(progress_event, "Starting backend update...");
let explicit_error = Arc::new(Mutex::new(None));
- let run_child = || {
+ // Update mutates the managed environment for its whole lifetime. 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)?;
+ // Under the gate and after the idle scan. A 805-807 rollback the last launch deferred
+ // still names the live runtime as something to undo, and updating on top of that journal
+ // has the next idle launch restoring the pre-update trees over everything installed here.
+ crate::staged_update::reconcile_before_update(&crate::diagnostics::studio_dir())?;
let (stdout, stderr) =
- spawn_update(&bin, &state, &kind).map_err(|msg| format!("spawn_update: {msg}"))?;
+ spawn_update(&bin, &state).map_err(|msg| format!("spawn_update: {msg}"))?;
let threads = stream_output(
&app,
progress_event,
@@ -448,16 +338,7 @@ fn run_update(
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());
@@ -471,21 +352,6 @@ fn run_update(
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 let Some((complete, _)) = kind.terminal_events() {
let _ = app.emit(complete, ());
@@ -595,7 +461,6 @@ pub fn stop_update(state: &UpdateState) -> Result<(), String> {
}
};
update.intentional_stop = true;
- update.staged_shell_version = None;
update.child.take()
};
@@ -726,11 +591,8 @@ mod tests {
assert_eq!(
cmd.get_args().map(OsString::from).collect::<Vec<_>>(),
vec![
- // -I here and nowhere else. This is the invocation that decides
- // which install gets rewritten, and it shipped isolated; a
- // user-site unsloth_cli answering `from unsloth_cli import app`
- // would update the wrong one. Every invocation a user could have
- // typed instead inherits, because the console script does.
+ // -I here and nowhere else: this invocation decides which install gets
+ // rewritten, and a user-site unsloth_cli would update the wrong one.
OsString::from("-X"),
OsString::from("utf8"),
OsString::from("-I"),
@@ -740,9 +602,8 @@ mod tests {
OsString::from("update")
]
);
- // The updater's PYTHONHOME / PYTHONPATH handling is asserted once, in
- // windows_update_command_still_scrubs_the_python_search_path below. This
- // test owns the program and the argument vector.
+ // PYTHONHOME / PYTHONPATH handling is asserted in
+ // windows_update_command_still_scrubs_the_python_search_path below.
std::fs::remove_dir_all(dir).unwrap();
}
@@ -757,9 +618,7 @@ mod tests {
.contains("python.exe"));
}
- // 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.
+ // Without -E the child reads PYTHONHOME and PYTHONPATH; see build_update_command.
#[test]
fn update_command_scrubs_the_python_search_path() {
let dir = std::env::temp_dir().join(format!(
@@ -787,7 +646,7 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
- // command may move with it. macOS and Linux still exec the console script.
+ // macOS and Linux still exec the console script.
#[cfg(not(windows))]
#[test]
fn posix_update_command_still_execs_the_console_script() {
@@ -808,50 +667,14 @@ mod tests {
}
}
+ // POSIX updates fail "busy" against the shell's own retained flock unless the child
+ // inherits it, so the handoff is set on every platform.
#[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() {
+ fn update_child_uses_the_parent_runtime_gate_on_every_platform() {
use std::ffi::OsStr;
let mut cmd = Command::new("unused");
- configure_runtime_gate_environment(&mut cmd, &UpdateKind::Backend);
+ configure_runtime_gate_environment(&mut cmd);
assert!(cmd.get_envs().any(|(key, value)| {
key == OsStr::new(crate::process::STUDIO_RUNTIME_GATE_HANDOFF_ENV)
@@ -859,43 +682,6 @@ mod tests {
}));
}
- #[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() {
diff --git a/tests/python/test_studio_runtime_gate.py b/tests/python/test_studio_runtime_gate.py
index a698a9193f3..2282fc20ba4 100644
--- a/tests/python/test_studio_runtime_gate.py
+++ b/tests/python/test_studio_runtime_gate.py
@@ -10,7 +10,6 @@ import os
import subprocess
import sys
import threading
-import time
from ctypes import wintypes
from pathlib import Path
from types import SimpleNamespace
@@ -102,99 +101,6 @@ 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")
-
-
@pytest.mark.skipif(os.name == "nt", reason = "POSIX flock is required")
def test_posix_runtime_gate_blocks_another_process_and_recovers(tmp_path):
script = """
diff --git a/tests/python/test_windows_installer_concurrency_guard.py b/tests/python/test_windows_installer_concurrency_guard.py
index b5d7d47147f..7e4ba220bb8 100644
--- a/tests/python/test_windows_installer_concurrency_guard.py
+++ b/tests/python/test_windows_installer_concurrency_guard.py
@@ -24,6 +24,7 @@ PREFLIGHT_MANAGED_RS = REPO_ROOT / "studio" / "src-tauri" / "src" / "preflight"
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"
+STAGED_UPDATE_RS = REPO_ROOT / "studio" / "src-tauri" / "src" / "staged_update.rs"
STUDIO_COMMAND = REPO_ROOT / "unsloth_cli" / "commands" / "studio.py"
POWERSHELLS = [shell for shell in ("pwsh", "powershell") if shutil.which(shell)]
@@ -35,11 +36,7 @@ def _extract(pattern: str, source: str) -> str:
def _run_powershell(shell: str, script: str, env: dict[str, str]) -> str:
- # Through a FILE, not -Command: these scripts carry the whole extracted helper chain, and Windows caps a command
- # line at 32767 characters.
- # Passed inline, the moment the chain grows past that every test here dies as WinError 206 "The filename or
- # extension is too long" instead of testing anything.
- # utf-8-sig because Windows PowerShell 5.1 reads a BOM-less .ps1 as ANSI.
+ # Through a FILE, not -Command: Windows caps a command line at 32767 characters. utf-8-sig, or PowerShell 5.1 reads the .ps1 as ANSI.
handle, name = tempfile.mkstemp(suffix = ".ps1")
os.close(handle)
try:
@@ -49,9 +46,7 @@ def _run_powershell(shell: str, script: str, env: dict[str, str]) -> str:
check = True,
capture_output = True,
text = True,
- # Decoded as utf-8 with replacement, not the console codepage: cp1252
- # cannot decode what PowerShell writes and the whole test then dies as
- # a UnicodeDecodeError on a byte in an error message.
+ # utf-8 with replacement: cp1252 cannot decode what PowerShell writes.
encoding = "utf-8",
errors = "replace",
env = env,
@@ -72,9 +67,7 @@ def _ps_file(directory: Path, name: str, script: str) -> str:
return str(path)
-# The chain Get-StudioFinalPath dispatches to. It used to compile the native helper inline, so a test could extract
-# it alone; extracting the dispatcher by itself now yields a body whose calls are all undefined, which reads as
-# "could not resolve" rather than as a missing helper (issue #9140).
+# The chain Get-StudioFinalPath dispatches to: extracted alone, the dispatcher yields undefined calls (#9140).
_FINAL_PATH_CHAIN = (
"Write-StudioLine",
"Test-StudioDirectoryUsable",
@@ -102,14 +95,11 @@ def _mutex_helpers(source: str) -> str:
return "\n".join(
_extract(rf" function {name} \{{.*?\n \}}\n", source)
for name in (
- # Test-StudioPathEqual reports an unresolvable identity through this, and these scripts run under
- # -ErrorActionPreference Stop, so leaving it out made the CATCH path throw CommandNotFound and every test
- # that reaches it fail for a reason that has nothing to do with what it measures. Extracted rather than
- # stubbed: it is self-contained, and a stub would keep passing if the real call ever went wrong.
+ # These scripts run under -ErrorActionPreference Stop, and Test-StudioPathEqual reports through
+ # Write-StudioLine. Extracted, not stubbed: a stub would keep passing if the real call went wrong.
"Write-StudioLine",
"Enter-StudioNamedMutex",
- # Get-StudioFinalPath is a dispatcher now: it falls back to the pure
- # PowerShell resolver when the native helper did not compile (#9140).
+ # Get-StudioFinalPath is a dispatcher: it falls back to the pure PowerShell resolver (#9140).
"Test-StudioDirectoryUsable",
"Remove-StudioStalePrivateTempDirectories",
"Get-StudioPrivateTempRoots",
@@ -172,9 +162,7 @@ def test_running_venv_process_is_reported(tmp_path: Path, shell: str):
shutil.copy2(Path(os.environ["SystemRoot"]) / "System32" / "PING.EXE", probe)
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0)
- # Long enough that the child outlives the scan itself. Windows PowerShell 5.1 pays a cold start plus a real csc.exe
- # compile of the native helper before it can look at anything, which alone can outlast a six-ping child; the process
- # would then be gone by the time the scan ran, and the test would read as "the in-use check missed it".
+ # Long enough that the child outlives the scan: PowerShell 5.1 pays a cold start plus a csc.exe compile first.
child = subprocess.Popen(
[str(probe), "-n", "120", "127.0.0.1"],
creationflags = creationflags,
@@ -222,8 +210,7 @@ def test_x86_powershell_reports_64_bit_managed_process(tmp_path: Path):
scripts.mkdir(parents = True)
probe = scripts / "guard-probe.exe"
shutil.copy2(Path(os.environ["SystemRoot"]) / "System32" / "PING.EXE", probe)
- # Long-lived: a 32-bit shell pays a WOW64 start plus an Add-Type compile, so a short probe can exit before the scan
- # runs.
+ # Long-lived: a 32-bit shell pays a WOW64 start plus an Add-Type compile.
child = subprocess.Popen(
[str(probe), "-n", "120", "127.0.0.1"],
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0),
@@ -338,10 +325,8 @@ def test_installer_ignores_command_line_and_cwd_only_path_mentions():
assert "$process.Path" not in detector
assert "Get-StudioProcessImagePath -ProcessId $process.Id" in detector
- # The same contract has to hold on every rung of that helper's fallback: a
- # confirmed image, never a command line. Its Win32_Process rung exists because a
- # host that cannot compile the native helper would otherwise find no running
- # processes and overwrite a venv Unsloth has open (issue #9140).
+ # The same contract on every rung: a confirmed image, never a command line. The Win32_Process rung
+ # exists because a host that cannot compile the native helper would overwrite a venv in use (#9140).
image = _extract(r" function Get-StudioProcessImagePath \{.*?\n \}\n", source)
assert ".CommandLine" not in image
assert "ExecutablePath" in image
@@ -948,35 +933,32 @@ 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)
+ # The guard covers the idle scan and the whole child lifetime.
+ update_call = update_source.index("crate::process::with_studio_runtime_launch_guard(")
+ update_scan = update_source.index("ensure_managed_environment_is_idle(&bin)", update_call)
+ # A deferred 805-807 rollback still names the live runtime, so it is settled before the update installs there.
+ update_legacy = update_source.index("staged_update::reconcile_before_update(", update_scan)
+ update_spawn = update_source.index("spawn_update(&bin, &state)", update_legacy)
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(
- "crate::process::with_studio_runtime_launch_guard(",
- update_wait,
- )
- exemption = update_source.index("fn mutates_live_environment(&self) -> bool {")
+ update_guard_release = update_source.index("\n });", update_wait)
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_scan_gate,
+ update_call
+ < update_scan
+ < update_legacy
+ < 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.
+ # The child inherits the gate on every platform: the POSIX shell holds its own flock around the child.
+ spawn_fn = update_source.index("fn spawn_update(")
+ spawn_gate_env = update_source.index("configure_runtime_gate_environment(&mut cmd);", spawn_fn)
+ assert spawn_fn < spawn_gate_env < update_call
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
+ handoff = update_source.index(
+ 'cmd.env(crate::process::STUDIO_RUNTIME_GATE_HANDOFF_ENV, "1");', configure_gate
+ )
+ assert "#[cfg" not in update_source[configure_gate:handoff]
def test_runtime_gate_handoff_covers_managed_children():
@@ -1003,9 +985,7 @@ def test_runtime_gate_handoff_covers_managed_children():
)
assert save < set_handoff < autostart < restore
- # The save sits above the try that now covers the whole handoff, not beside
- # the set: a finally reached before its own $hadPrevious* was assigned reads
- # an unset flag as "there was nothing here" and clears a value it never set.
+ # The save sits above the try covering the whole handoff, or a finally clears a value it never set.
setup_save = install_source.index("$previousSetupRuntimeGateHandoff =")
setup_try = install_source.index("\n try {\n $env:SKIP_STUDIO_BASE", setup_save)
setup_python = install_source.index("$env:UNSLOTH_SETUP_PYTHON =", setup_try)
@@ -1035,7 +1015,7 @@ def test_runtime_gate_handoff_covers_managed_children():
studio_source.count(
"runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()"
)
- == 5
+ == 4
)
assert (
studio_source.count(
@@ -1046,37 +1026,32 @@ def test_runtime_gate_handoff_covers_managed_children():
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")
+def test_legacy_staged_update_cleanup_runs_under_the_runtime_gate():
+ """The cleanup renames whole runtime trees, so it must not run beside anything holding the gate."""
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
+ staged_source = STAGED_UPDATE_RS.read_text(encoding = "utf-8")
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)
+ reconcile = main_source.index("staged_update::reconcile_legacy_at_launch", reconcile_gate)
assert setup < reconcile_gate < reconcile
+ # Nothing activates a stage any more: the whole directory goes, and before the rollback.
+ entry = staged_source.index("pub(crate) fn reconcile_legacy_at_launch(")
+ trash = staged_source.index("remove_stale_trash(home);", entry)
+ failed = staged_source.index("fs::remove_file(home.join(FAILED_MARKER));", trash)
+ stage = staged_source.index("discard_stage(home);", failed)
+ rollback = staged_source.index("roll_back_unconfirmed(home)", stage)
+ assert entry < trash < failed < stage < rollback
+
+ # The stage is a clone of the managed venv, so the launch renames it and unlinks off the launch path.
+ discard = staged_source.index("fn discard_stage_with(")
+ rename = staged_source.index("rename(&stage, &trash)", discard)
+ spawn = staged_source.index("std::thread::spawn", rename)
+ fallback = staged_source.index("std::thread::spawn", spawn + 1)
+ swept = staged_source.index("fs::remove_dir_all(stage)", fallback)
+ assert discard < rename < spawn < fallback < swept
+
def test_tauri_start_install_rejects_backend_conflicts_before_spawn():
source = COMMANDS_RS.read_text(encoding = "utf-8")
@@ -1096,23 +1071,12 @@ def test_tauri_start_install_rejects_backend_conflicts_before_spawn():
ids = ["mutex", "process"],
)
def test_the_extracted_helpers_can_call_everything_they_call(helpers):
- """Every installer function these harnesses reach must be in the harness.
-
- The scripts above run under -ErrorActionPreference Stop, so a helper that
- calls an installer function nobody extracted dies with CommandNotFound, and
- the test fails for a reason unrelated to what it measures. That is not
- hypothetical: Test-StudioPathEqual reports an unresolvable path identity
- through Write-StudioLine, which was missing, so both
- test_path_identity_failure_is_reported_as_unknown cases failed on Windows
- while passing nowhere they could be noticed.
-
- Runs on every platform, unlike the scripts themselves, so the harness cannot
- drift out of step again where only a Windows runner would see it.
- """
+ """Every installer function these harnesses reach must be in the harness: the scripts run under
+ -ErrorActionPreference Stop, so a missing one fails the test for an unrelated reason. Runs on
+ every platform, unlike the scripts themselves."""
source = INSTALL_PS1.read_text(encoding = "utf-8")
extracted = helpers(source)
- # Every top-level installer function, i.e. everything the harness COULD be missing. A call to a cmdlet or to a
- # function defined inside the scripts is not this test's business.
+ # Every top-level installer function, i.e. everything the harness COULD be missing.
installer_functions = set(re.findall(r"^ function ([\w-]+) \{", source, flags = re.M))
provided = set(re.findall(r"^ function ([\w-]+) \{", extracted, flags = re.M))
assert provided, "the helper extraction produced nothing"
diff --git a/tests/python/test_windows_studio_update_launcher.py b/tests/python/test_windows_studio_update_launcher.py
index d0e4c7a77aa..acfb1bfa509 100644
--- a/tests/python/test_windows_studio_update_launcher.py
+++ b/tests/python/test_windows_studio_update_launcher.py
@@ -24,7 +24,6 @@ REAL_MSVCRT = sys.modules.get("msvcrt")
@pytest.fixture
def studio(monkeypatch):
- """Load studio.py without importing the heavyweight unsloth package."""
package = types.ModuleType("unsloth_cli")
package.__path__ = [str(REPO_ROOT / "unsloth_cli")]
commands = types.ModuleType("unsloth_cli.commands")
@@ -89,10 +88,7 @@ def _configure_windows(
monkeypatch.setattr(studio, "_windows_hidden_subprocess_kwargs", lambda: {})
monkeypatch.setattr(studio, "_refresh_desktop_shortcuts", lambda **_kwargs: None)
monkeypatch.setattr(studio, "_fail_if_install_damaged", lambda *_args: None)
- # The runtime gate's process scan is Windows-only, so off Windows it never runs and nothing here noticed it was
- # unstubbed. On a real Windows host it shells out to powershell.exe through the same subprocess.run these tests
- # replace, then reads .stdout off a fake that only carries a returncode, and every test in this file dies before
- # reaching what it meant to assert.
+ # The gate's process scan is Windows-only; unstubbed it shells out through the same subprocess.run these tests replace.
monkeypatch.setattr(
studio._studio_runtime_gate,
"ensure_managed_environment_is_idle",
@@ -159,8 +155,6 @@ def test_setup_noop_preserves_launcher_and_removes_backup(monkeypatch, studio, t
def test_a_recoverable_copy_exists_while_setup_runs(monkeypatch, studio, tmp_path):
- # The canonical path is freed so the installer can publish a replacement,
- # but never without a copy to put back if it publishes nothing.
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
def setup(**_kwargs):
@@ -211,8 +205,7 @@ def test_setup_failure_restores_original_and_propagates(monkeypatch, studio, tmp
def test_setup_publishing_no_launcher_restores_it_and_succeeds(monkeypatch, studio, tmp_path):
- # The bug this transaction exists for: pip finds unsloth already current, writes no launcher, and the old updater
- # then deleted its own .deleteme and left the venv with none at all. Restoring is the right answer, not failing.
+ # The bug this exists for: pip finds unsloth current and writes no launcher, and the old updater deleted its .deleteme.
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)
monkeypatch.setattr(studio.subprocess, "run", _successful_version_run())
@@ -278,7 +271,6 @@ def test_legacy_backup_recovers_only_when_launcher_is_missing(monkeypatch, studi
legacy.write_bytes(ORIGINAL_LAUNCHER)
def setup(**_kwargs):
- # Recovered from the legacy file, then moved aside for the installer.
assert (scripts / "unsloth.exe.update-stale").read_bytes() == ORIGINAL_LAUNCHER
monkeypatch.setattr(studio, "_run_setup_script", setup)
@@ -294,7 +286,6 @@ def test_legacy_backup_recovers_only_when_launcher_is_missing(monkeypatch, studi
def test_lock_contention_exits_before_setup_or_launcher_mutation(monkeypatch, studio, tmp_path):
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
if REAL_MSVCRT is not None:
- # Exercise the real byte-range lock on Windows and the fake elsewhere.
monkeypatch.setitem(sys.modules, "msvcrt", REAL_MSVCRT)
before = launcher.read_bytes()
first = studio._WindowsLauncherUpdateTransaction()
@@ -343,16 +334,12 @@ def test_non_windows_preserves_call_order_without_launcher_operations(
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.
- """
+ """`stage` defaults to typer's truthy OptionInfo, so a plain `if stage:` would skip every in-process update."""
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))
+ monkeypatch.setattr(studio, "_refuse_staged_update", lambda: staged.append("refused"))
calls = []
monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: calls.append("setup"))
monkeypatch.setattr(
@@ -378,7 +365,6 @@ def test_an_in_process_update_does_not_stage(monkeypatch, studio, tmp_path):
def _shim(studio, payload = ORIGINAL_LAUNCHER):
- """The hardlinked PATH shim install.ps1 creates beside the managed venv."""
path = studio.STUDIO_HOME / "bin" / "unsloth.exe"
path.parent.mkdir(parents = True, exist_ok = True)
path.write_bytes(payload)
@@ -386,8 +372,7 @@ def _shim(studio, payload = ORIGINAL_LAUNCHER):
def test_a_missing_launcher_is_recovered_from_the_path_shim(monkeypatch, studio, tmp_path):
- # The old updater renamed the launcher away and then unlinked the .deleteme, so an affected install has neither.
- # install.ps1 hardlinks the shim to the same file, so it survives that unlink and can repair the launcher.
+ # The old updater left neither launcher nor .deleteme; the shim is a hardlink, so it survives.
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path, launcher = None)
_shim(studio)
monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)
@@ -399,9 +384,7 @@ def test_a_missing_launcher_is_recovered_from_the_path_shim(monkeypatch, studio,
def test_an_invalid_launcher_is_recovered_from_the_backup(monkeypatch, studio, tmp_path):
- # Recovery gated on existence rather than validity left a zero-byte launcher in place while a usable backup sat
- # beside it.
- # The old updater restored on exactly this shape (st_size == 0), so gating on exists() regressed it.
+ # Gating recovery on existence left a zero-byte launcher in place beside a usable backup.
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path, launcher = b"")
(scripts / "unsloth.exe.update-backup").write_bytes(ORIGINAL_LAUNCHER)
monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)
@@ -413,8 +396,7 @@ def test_an_invalid_launcher_is_recovered_from_the_backup(monkeypatch, studio, t
def test_no_launcher_and_no_recovery_source_still_runs_setup(monkeypatch, studio, tmp_path):
- # Refusing here would strand exactly the users the transaction exists for: the previous updater could leave no
- # launcher and no .deleteme, and before this the update simply carried on and let setup reinstall it.
+ # Refusing would strand the users this exists for: the previous updater could leave no launcher.
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path, launcher = None)
ran = []
@@ -432,7 +414,6 @@ def test_no_launcher_and_no_recovery_source_still_runs_setup(monkeypatch, studio
def test_a_backup_failure_does_not_abort_the_update(monkeypatch, studio, tmp_path):
- # A backup is a safety net, not a precondition.
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
ran = []
original = studio._WindowsLauncherUpdateTransaction._atomic_copy
@@ -442,7 +423,6 @@ def test_a_backup_failure_does_not_abort_the_update(monkeypatch, studio, tmp_pat
raise OSError("access is denied")
return original(source, destination)
- # _atomic_copy is a staticmethod, so the stand-in must not bind self either.
monkeypatch.setattr(
studio._WindowsLauncherUpdateTransaction, "_atomic_copy", staticmethod(refuse_backup)
)
@@ -456,9 +436,7 @@ def test_a_backup_failure_does_not_abort_the_update(monkeypatch, studio, tmp_pat
def test_an_existing_backup_survives_an_unvalidated_launcher(monkeypatch, studio, tmp_path):
- # A backup outlives __enter__ only when a previous run died before validating, so it holds the last launcher known
- # to run while the canonical file has passed nothing but the two-byte header check. Overwriting it here destroyed
- # the only recovery copy.
+ # A surviving backup holds the last launcher known to run; overwriting it destroyed the only recovery copy.
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path, launcher = b"MZ-broken")
backup = scripts / "unsloth.exe.update-backup"
backup.write_bytes(ORIGINAL_LAUNCHER)
@@ -476,8 +454,7 @@ def test_an_existing_backup_survives_an_unvalidated_launcher(monkeypatch, studio
def test_the_launcher_is_resolved_from_the_managed_studio_venv(monkeypatch, studio, tmp_path):
- # A pip-installed or checkout CLI drives an update of the separate managed environment, so sys.executable belongs to
- # the caller while setup.ps1 installs into STUDIO_HOME/unsloth_studio.
+ # sys.executable belongs to the caller while setup.ps1 installs into STUDIO_HOME/unsloth_studio.
scripts, caller_launcher = _configure_windows(monkeypatch, studio, tmp_path)
managed = tmp_path / "studio_home" / "unsloth_studio"
(managed / "Scripts").mkdir(parents = True)
@@ -496,9 +473,7 @@ def test_the_launcher_is_resolved_from_the_managed_studio_venv(monkeypatch, stud
def test_a_replacement_published_by_setup_is_kept(monkeypatch, studio, tmp_path):
- # The point of freeing the canonical path. uv only self-replaces its own executable, so it deletes a third-party
- # console script outright and hard-errors when the file is in use; the pip fallback then no-ops on the
- # already-satisfied bare unsloth and the upgrade is silently skipped.
+ # uv deletes a third-party console script outright and hard-errors when it is in use, after which pip skips the upgrade.
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
new_launcher = b"MZ-upgraded-launcher"
@@ -527,9 +502,7 @@ def test_an_invalid_replacement_is_restored_but_still_fails(monkeypatch, studio,
def test_a_backup_that_cannot_run_falls_back_to_the_moved_aside_copy(monkeypatch, studio, tmp_path):
- # Backups are taken after only the two-byte header check, so an interrupted
- # run can leave a PE-shaped but non-runnable one. Preferring it must not
- # strand the working launcher that this run moved aside.
+ # A PE-shaped but non-runnable backup must not strand the working launcher this run moved aside.
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
bad_backup = b"MZ-unrunnable"
(scripts / "unsloth.exe.update-backup").write_bytes(bad_backup)
@@ -547,9 +520,7 @@ def test_a_backup_that_cannot_run_falls_back_to_the_moved_aside_copy(monkeypatch
def test_a_setup_exception_restores_a_runnable_launcher(monkeypatch, studio, tmp_path):
- # Backups are taken after only the two-byte header check, so an interrupted run can leave a PE-shaped but
- # non-runnable backup. __exit__ took the first PE-shaped candidate, so that backup was installed over the
- # working launcher this run had moved aside, and it could also undo a restore validate_launcher just made.
+ # __exit__ took the first PE-shaped candidate, overwriting the working launcher and undoing a restore.
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
bad_backup = b"MZ-unrunnable"
(scripts / "unsloth.exe.update-backup").write_bytes(bad_backup)
@@ -572,9 +543,7 @@ def test_a_setup_exception_restores_a_runnable_launcher(monkeypatch, studio, tmp
def test_a_non_runnable_backup_falls_through_to_the_legacy_copy(monkeypatch, studio, tmp_path):
- # An interrupted run can leave a PE-shaped but non-runnable backup while the legacy .deleteme or the PATH shim is
- # still good. Accepting the backup on its MZ header alone and stopping there left the update failing forever with
- # the broken bytes canonical.
+ # Accepting a backup on its MZ header alone left the update failing forever with broken bytes canonical.
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path, launcher = None)
bad_backup = b"MZ-unrunnable"
(scripts / "unsloth.exe.update-backup").write_bytes(bad_backup)
@@ -593,9 +562,7 @@ def test_a_non_runnable_backup_falls_through_to_the_legacy_copy(monkeypatch, stu
def test_the_update_lock_lives_outside_the_replaceable_venv(monkeypatch, studio, tmp_path):
- # setup.ps1 removes the whole $VenvDir to rebuild a stale torch, and Windows
- # refuses a recursive delete while a handle inside it is open. A lock under
- # Scripts/ therefore broke exactly the repair path it was meant to guard.
+ # setup.ps1 removes the whole $VenvDir, and Windows refuses that while a handle inside it is open.
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
seen = {}
@@ -615,9 +582,7 @@ def test_the_update_lock_lives_outside_the_replaceable_venv(monkeypatch, studio,
def test_a_failed_move_aside_warns_that_unsloth_may_not_upgrade(
monkeypatch, studio, tmp_path, capsys
):
- # Aborting here would make an antivirus hold enough to render the environment unupdatable, which main did not do
- # either. But the cost has to be visible: uv cannot replace a launcher it could not move, and the pip fallback
- # drops --upgrade-package, so unsloth stays at its old version.
+ # The cost has to be visible: the pip fallback drops --upgrade-package, so unsloth stays at its old version.
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
ran = []
seen = {}
@@ -625,8 +590,7 @@ def test_a_failed_move_aside_warns_that_unsloth_may_not_upgrade(
real_replace = studio.os.replace
def refuse_move(source, destination):
- # Only the move aside: patching os.replace wholesale would also break _atomic_copy's backup, and the test would
- # then be passing on a compound failure rather than the one it names.
+ # Only the move aside: patching os.replace wholesale would also break the backup copy.
if str(destination).endswith(".update-stale"):
raise OSError("access is denied")
return real_replace(source, destination)
@@ -635,7 +599,6 @@ def test_a_failed_move_aside_warns_that_unsloth_may_not_upgrade(
def setup(**_kwargs):
ran.append(True)
- # Sampled here: a successful update unlinks the backup on the way out.
seen["backup"] = (scripts / "unsloth.exe.update-backup").read_bytes()
monkeypatch.setattr(studio, "_run_setup_script", setup)
@@ -651,18 +614,8 @@ def test_a_failed_move_aside_warns_that_unsloth_may_not_upgrade(
assert seen["backup"] == ORIGINAL_LAUNCHER
-# Issue #8490:
-
-
-# ── Application Control (issue #8490) ─────────────────────────────────
-#
-# Windows can deny the generated, unsigned unsloth.exe while the signed
-# python.exe beside it still runs. The launcher --version probe is then
-# impossible, and reading that as "the update broke" rolled a perfectly good
-# install back on every single update.
+# Application Control (#8490): Windows can deny the unsigned unsloth.exe while the signed python.exe runs.
def _blocked_exe_run(interpreter_result, calls = None):
- """subprocess.run where only the launcher is denied by policy."""
-
def run(argv, **kwargs):
if calls is not None:
calls.append((argv, kwargs))
@@ -693,9 +646,7 @@ def test_a_policy_blocked_launcher_falls_back_to_the_interpreter(monkeypatch, st
assert calls[0][0] == [str(launcher), "--version"]
interpreter_call = calls[1][0]
- # Spelled out rather than imported, so an edit to the constant fails here.
- # -I here and nowhere else in this module: this probe predicts the desktop updater's launch, and
- # build_update_command runs that under Isolation::Isolated with PYTHONHOME/PYTHONPATH cleared.
+ # Spelled out, so an edit to the constant fails here. -I here alone: this probe predicts build_update_command's isolated launch.
assert interpreter_call == [
str(scripts / "python.exe"),
"-X",
@@ -706,14 +657,12 @@ def test_a_policy_blocked_launcher_falls_back_to_the_interpreter(monkeypatch, st
"sys.argv[0] = 'unsloth'; from unsloth_cli import app; sys.exit(app())",
"--version",
]
- # The launcher probe gets 10s, a process start.
assert calls[0][1]["timeout"] == 10
assert calls[1][1]["timeout"] == studio._MANAGED_CLI_IMPORT_PROBE_TIMEOUT
assert calls[1][1]["timeout"] > calls[0][1]["timeout"]
def test_a_policy_block_with_a_broken_package_still_fails(monkeypatch, studio, tmp_path):
- """The fallback must not become a blanket "assume it worked"."""
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)
monkeypatch.setattr(
@@ -732,7 +681,6 @@ def test_a_policy_block_with_a_broken_package_still_fails(monkeypatch, studio, t
def test_a_policy_block_with_no_interpreter_reports_the_block(
monkeypatch, studio, tmp_path, capsys
):
- """Nothing left to ask: say what Windows said rather than inventing a cause."""
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
(scripts / "python.exe").unlink()
monkeypatch.setattr(
@@ -751,7 +699,6 @@ def test_a_policy_block_with_no_interpreter_reports_the_block(
def test_an_ordinary_launcher_oserror_is_still_a_failure(monkeypatch, studio, tmp_path):
- """Parity guard: only 1260 takes the new path, everything else is unchanged."""
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)
interpreter_calls = []
@@ -783,17 +730,11 @@ def test_the_policy_block_helper_only_matches_1260(studio):
denied.winerror = 5
assert not studio._is_application_control_block(denied)
- # POSIX OSError has no winerror at all.
assert not studio._is_application_control_block(OSError(13, "denied"))
def test_a_quarantined_away_launcher_falls_back_to_the_interpreter(monkeypatch, studio, tmp_path):
- """Quarantine removes the unsigned stub rather than denying it.
-
- There is then nothing to run and nothing to put back, and reading that as a
- broken update rolls a good one back exactly as the denial case did. The
- launcher stays gone, which is fine: nothing executes it any more.
- """
+ """Quarantine removes the stub rather than denying it: nothing to run, nothing to put back."""
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path, launcher = None)
monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)
calls = []
@@ -808,16 +749,8 @@ def test_a_quarantined_away_launcher_falls_back_to_the_interpreter(monkeypatch,
def test_only_the_updater_probe_isolates_the_interpreter(studio, tmp_path):
- """Isolation is opt-in, and exactly one caller opts in.
-
- Every other managed invocation has to stay byte-for-byte what the console
- script did, and -I implies -E and -s: PYTHONPATH, PYTHONWARNINGS,
- PYTHONHASHSEED and user site-packages all stop being honoured. That is an
- observable difference on a machine with no policy at all, so the default
- inherits and only the probe standing in for an already-isolated launch asks
- for it. Mirrors only_the_isolated_flavour_carries_the_isolation_flag in
- studio/src-tauri/src/process.rs.
- """
+ """Isolation is opt-in and exactly one caller opts in: -I implies -E and -s, dropping PYTHONPATH and
+ user site-packages. Mirrors only_the_isolated_flavour_carries_the_isolation_flag in process.rs."""
python = tmp_path / "python.exe"
inherited = studio._managed_cli_argv(python, "--version")
@@ -825,17 +758,15 @@ def test_only_the_updater_probe_isolates_the_interpreter(studio, tmp_path):
assert "-I" not in inherited
isolated = studio._managed_cli_argv(python, "--version", isolated = True)
- # -X utf8 first: -I implies -E, so PYTHONUTF8 would be discarded, while a command-line -X survives it.
+ # -X utf8 first: -I implies -E, so PYTHONUTF8 would be discarded.
assert isolated[:4] == [str(python), "-X", "utf8", "-I"]
- # Isolation is the only difference.
assert [arg for arg in isolated if arg != "-I"] == inherited
def test_a_quarantined_away_launcher_with_a_broken_package_still_fails(
monkeypatch, studio, tmp_path
):
- """Parity guard: absence excuses the launcher, never the update."""
_configure_windows(monkeypatch, studio, tmp_path, launcher = None)
monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)
monkeypatch.setattr(
@@ -851,12 +782,7 @@ def test_a_quarantined_away_launcher_with_a_broken_package_still_fails(
def test_a_restorable_launcher_is_restored_before_the_interpreter_is_asked(
monkeypatch, studio, tmp_path
):
- """Absence is only excused once recovery has failed.
-
- A healthy CLI must not let a launcher that could have been put back stay
- missing, or an ordinary no-op update on an unpoliced machine would quietly
- strip the console script.
- """
+ """Absence is only excused once recovery failed, or a no-op update would quietly strip the console script."""
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)
monkeypatch.setattr(studio.subprocess, "run", _successful_version_run())
@@ -867,13 +793,7 @@ def test_a_restorable_launcher_is_restored_before_the_interpreter_is_asked(
def test_the_package_answers_for_a_quarantined_console_script(monkeypatch, studio, tmp_path):
- """What `studio run` checks instead of the deleted stub, and only on Windows.
-
- The layout is the fallback for one specific no-verdict case, a probe that
- timed out, so that is what is simulated here. A probe that could not START
- the interpreter is a different answer and is covered separately: the re-exec
- runs that same interpreter, so the layout cannot excuse it.
- """
+ """What `studio run` checks instead of the deleted stub. An interpreter that will not start is covered separately."""
scripts = tmp_path / "Scripts"
site_packages = tmp_path / "Lib" / "site-packages"
scripts.mkdir(parents = True)
@@ -891,7 +811,6 @@ def test_the_package_answers_for_a_quarantined_console_script(monkeypatch, studi
(site_packages / "unsloth_cli").mkdir()
assert studio._managed_cli_package_present(python)
- # An editable install leaves a .pth and no unsloth_cli/ here.
(site_packages / "unsloth_cli").rmdir()
(site_packages / "unsloth-2026.8.1.dist-info").mkdir()
assert studio._managed_cli_package_present(python)
@@ -902,12 +821,7 @@ def test_the_package_answers_for_a_quarantined_console_script(monkeypatch, studi
@pytest.fixture(scope = "module")
def real_venv(tmp_path_factory):
- """A real, empty interpreter to ask, rather than a file named python.exe.
-
- Built without pip so site-packages starts genuinely empty; the layout is
- POSIX here, which is the point -- the check must come from the interpreter,
- not from guessing at Lib\\site-packages.
- """
+ """A real, empty interpreter to ask, rather than a file named python.exe."""
root = tmp_path_factory.mktemp("managed_cli_probe") / "venv"
try:
subprocess.run(
@@ -927,14 +841,7 @@ def real_venv(tmp_path_factory):
def test_orphaned_install_metadata_is_not_a_runnable_cli(monkeypatch, studio, real_venv):
- """Metadata is not an importable package, and this gate cannot accept it.
-
- An interrupted install, or an editable install whose checkout has since
- moved, leaves an ``unsloth-*.dist-info`` behind with nothing to import. This
- check stands in front of the headless-public strip of .bootstrap_password,
- so answering yes here lands exactly the lockout the gate's placement exists
- to prevent: a public Unsloth with no login page and no recovery credential.
- """
+ """Metadata is not an importable package, and this gate fronts the .bootstrap_password strip."""
python, site_packages = real_venv
windows_layout = python.parent.parent / "Lib" / "site-packages"
windows_layout.mkdir(parents = True, exist_ok = True)
@@ -948,10 +855,6 @@ def test_orphaned_install_metadata_is_not_a_runnable_cli(monkeypatch, studio, re
def test_an_importable_package_still_answers_for_the_quarantined_stub(
monkeypatch, studio, real_venv
):
- """The quarantine case this fallback exists for keeps working.
-
- Same venv as above, now with something the interpreter can actually resolve.
- """
python, site_packages = real_venv
package = site_packages / "unsloth_cli"
package.mkdir(parents = True, exist_ok = True)
@@ -966,11 +869,6 @@ def test_an_importable_package_still_answers_for_the_quarantined_stub(
@pytest.fixture
def bare_probe_venv(real_venv):
- """The module venv with any unsloth_cli left by a neighbouring test removed.
-
- These cases each install their own shape of broken package, so they cannot
- inherit one, and they must not leave one behind either.
- """
python, site_packages = real_venv
package = site_packages / "unsloth_cli"
shutil.rmtree(package, ignore_errors = True)
@@ -981,9 +879,7 @@ def bare_probe_venv(real_venv):
@pytest.mark.parametrize(
"shape, files",
[
- # An emptied directory. find_spec calls this a namespace package and returns a spec for it, so a spec lookup
- # answers yes to a venv the trampoline's `from unsloth_cli import app` cannot start. This is the shape
- # antivirus leaves when it takes the module files out from under a package it decided it disliked.
+ # An emptied directory: find_spec returns a namespace-package spec, so a spec lookup says yes to a venv that cannot start.
("an emptied package directory", {}),
# An interrupted install: the package landed, its dependencies did not.
(
@@ -1002,14 +898,7 @@ def bare_probe_venv(real_venv):
def test_a_package_the_trampoline_cannot_import_is_not_a_runnable_cli(
monkeypatch, studio, bare_probe_venv, shape, files
):
- """The gate has to fail on everything the launch would fail on.
-
- It stands in front of the headless-public strip of .bootstrap_password, so a
- yes here that the trampoline then contradicts is a public Unsloth with no
- login page and no plaintext recovery credential. Locating the package is not
- the question; importing it and getting `app` back is, which is why the probe
- runs that exact import rather than a cheaper find_spec.
- """
+ """The gate must fail on everything the launch fails on: it fronts the headless-public .bootstrap_password strip."""
python, site_packages = bare_probe_venv
package = site_packages / "unsloth_cli"
package.mkdir(parents = True)
@@ -1021,21 +910,13 @@ def test_a_package_the_trampoline_cannot_import_is_not_a_runnable_cli(
python
), f"{shape} must not pass the gate: the trampoline cannot start it"
- # Anti-vacuity: the same venv with a package that does import passes, so the assertion above is about the shape and
- # not about the fixture being broken.
+ # Anti-vacuity: the same venv with an importable package passes.
(package / "__init__.py").write_text("app = None\n", encoding = "utf-8")
assert studio._managed_cli_package_present(python)
def test_a_probe_that_cannot_start_the_interpreter_fails_closed(monkeypatch, studio, tmp_path):
- """No verdict is not the same as no problem, and the two causes differ.
-
- The re-exec this gate stands in front of runs the same interpreter, so an
- interpreter that will not start means the re-exec will not either, and the
- on-disk layout cannot say otherwise. The caller strips .bootstrap_password
- before that re-exec on a headless public launch, so passing here would leave
- a public Unsloth with no login page and no plaintext recovery credential.
- """
+ """No verdict is not no problem: the re-exec runs the same interpreter, and the caller strips .bootstrap_password first."""
scripts = tmp_path / "Scripts"
site_packages = tmp_path / "Lib" / "site-packages"
scripts.mkdir(parents = True)
@@ -1052,8 +933,7 @@ def test_a_probe_that_cannot_start_the_interpreter_fails_closed(monkeypatch, stu
monkeypatch.setattr(studio.subprocess, "run", blocked)
assert not studio._managed_cli_package_present(python)
- # A timeout is the other kind of no verdict, and it keeps the fallback: slow is not broken, a cold venv under an
- # antivirus scan is exactly this, and the re-exec has no timeout of its own to trip over.
+ # A timeout is the other no verdict and keeps the fallback: a cold venv under an antivirus scan is exactly this.
def slow(*_args, **_kwargs):
raise subprocess.TimeoutExpired(cmd = "probe", timeout = 60)
@@ -1062,14 +942,7 @@ def test_a_probe_that_cannot_start_the_interpreter_fails_closed(monkeypatch, stu
def test_the_interpreter_fallback_waits_as_long_as_the_import_probe(studio):
- """--version through the trampoline is an import, not a process start.
-
- The launcher's 10 seconds is sized for spawning a built executable. Here the
- same call has to import the whole CLI package, which is the work the import
- probe's ceiling is deliberately generous for, and under the antivirus scan
- that produced the quarantine this path exists to survive, the short ceiling
- would call a healthy update broken and roll it back once per candidate.
- """
+ """--version through the trampoline is an import, not a process start, so 10s would call a healthy update broken."""
transaction = studio._WindowsLauncherUpdateTransaction
source = inspect.getsource(transaction._interpreter_health_error)
assert "_MANAGED_CLI_IMPORT_PROBE_TIMEOUT" in source
@@ -1078,15 +951,8 @@ def test_the_interpreter_fallback_waits_as_long_as_the_import_probe(studio):
def test_a_custom_root_survives_the_launcher_being_quarantined(monkeypatch, studio, tmp_path):
- """The sentinel decides which installation every studio command manages.
-
- Only install.sh writes share/studio.conf, so on a custom-root Windows
- install the generated unsloth.exe was the only sentinel there was. Quarantine
- deletes it, root inference then falls back to ~/.unsloth/studio, and the CLI
- reads and writes the wrong tree while reporting success. The .cmd shim is
- written by the same installer for the same directory and answers the same
- question.
- """
+ """The sentinel decides which installation the CLI manages: on a custom-root Windows install the
+ generated unsloth.exe was the only one, and quarantine sent the CLI to the wrong tree."""
root = tmp_path / "custom-root"
(root / "bin").mkdir(parents = True)
monkeypatch.setattr(studio.platform, "system", lambda: "Windows")
@@ -1100,7 +966,6 @@ def test_a_custom_root_survives_the_launcher_being_quarantined(monkeypatch, stud
)
assert studio._looks_like_installer_managed_studio_home(root)
- # The launcher still answers on its own, so an install that never lost it is unaffected either way.
shim.unlink()
(root / "bin" / "unsloth.exe").write_bytes(b"MZ")
assert studio._looks_like_installer_managed_studio_home(root)
@@ -1109,8 +974,7 @@ def test_a_custom_root_survives_the_launcher_being_quarantined(monkeypatch, stud
@pytest.mark.parametrize(
"label, body",
[
- # This decides which tree the CLI manages and the directory is on PATH, so any file of that name would otherwise
- # be enough to redirect a root.
+ # This decides which tree the CLI manages and the directory is on PATH.
("a hand-rolled wrapper", b'@echo off\r\npython -c "from unsloth_cli import app" %*\r\n'),
("the marker without the call", b"@echo off\r\nrem unsloth-studio-managed-launcher\r\n"),
("an unrelated batch file", b"@echo off\r\necho hello\r\n"),
@@ -1129,7 +993,6 @@ def test_only_the_installers_own_cmd_shim_marks_a_root(monkeypatch, studio, tmp_
def test_an_oversized_cmd_shim_is_not_read_into_memory(monkeypatch, studio, tmp_path):
- """Same 8 KB ceiling Test-UnslothCmdShimFile and the uninstaller apply."""
root = tmp_path / "root"
(root / "bin").mkdir(parents = True)
shim = root / "bin" / "unsloth.cmd"
@@ -1142,7 +1005,6 @@ def test_an_oversized_cmd_shim_is_not_read_into_memory(monkeypatch, studio, tmp_
def test_posix_root_inference_is_unchanged(monkeypatch, studio, tmp_path):
- """A .cmd means nothing off Windows, and the console script still answers."""
root = tmp_path / "root"
(root / "bin").mkdir(parents = True)
(root / "bin" / "unsloth.cmd").write_bytes(
@@ -1156,22 +1018,13 @@ def test_posix_root_inference_is_unchanged(monkeypatch, studio, tmp_path):
def test_the_import_probe_performs_the_trampolines_own_import(studio):
- """A spec lookup here would answer a different question than the launch asks.
-
- Pinned as a source contract because the two failures it prevents are silent:
- an empty directory and a raising __init__ both resolve as specs, and both
- give the gate a yes the launch immediately contradicts.
- """
+ """A spec lookup answers a different question than the launch asks, and both failures are silent."""
assert "from unsloth_cli import app" in studio._MANAGED_CLI_IMPORT_PROBE
assert "find_spec" not in studio._MANAGED_CLI_IMPORT_PROBE
def test_the_import_probe_scrubs_the_cwd_exactly_as_the_trampoline_does(studio):
- """A drift here would let a checkout in the caller's cwd answer for the venv.
-
- `-c` puts the cwd on sys.path[0]; the trampoline drops it, so a probe that
- did not would report a CLI the launch cannot then import.
- """
+ """A drift here would let a checkout in the caller's cwd answer for the venv."""
scrub = (
"import sys, os; sys.path[:1] = [x for x in sys.path[:1] "
"if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; "
@@ -1183,11 +1036,7 @@ def test_the_import_probe_scrubs_the_cwd_exactly_as_the_trampoline_does(studio):
def test_a_candidate_that_vanishes_mid_copy_does_not_stop_the_next_one(
monkeypatch, studio, tmp_path
):
- """The header check and the copy open the file separately.
-
- Antivirus taking the first candidate in that gap says nothing about the rest,
- and giving up there turned a recoverable install into a failed update.
- """
+ """The header check and the copy open the file separately, so antivirus taking the first candidate says nothing about the rest."""
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path, launcher = None)
backup = scripts / "unsloth.exe.update-backup"
legacy = scripts / "unsloth.exe.deleteme"
@@ -1213,7 +1062,6 @@ def test_a_candidate_that_vanishes_mid_copy_does_not_stop_the_next_one(
def test_every_candidate_failing_is_still_an_error(monkeypatch, studio, tmp_path, capsys):
- """Parity guard: trying them all must not become swallowing them all."""
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path, launcher = None)
(scripts / "unsloth.exe.update-backup").write_bytes(b"MZ-backup")
@@ -1233,12 +1081,7 @@ def test_every_candidate_failing_is_still_an_error(monkeypatch, studio, tmp_path
def test_an_unrecoverable_launcher_keeps_its_recovery_copies(monkeypatch, studio, tmp_path):
- """Judged healthy through the interpreter is not the same as repaired.
-
- When every restore attempt failed, the copies are the only material a later
- run has. Deleting them on the way out of a "successful" update would make the
- next one unrecoverable.
- """
+ """Judged healthy through the interpreter is not repaired: the copies are the only material a later run has."""
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path, launcher = None)
backup = scripts / "unsloth.exe.update-backup"
backup.write_bytes(ORIGINAL_LAUNCHER)
@@ -1259,7 +1102,6 @@ def test_an_unrecoverable_launcher_keeps_its_recovery_copies(monkeypatch, studio
def test_a_restored_launcher_still_cleans_up(monkeypatch, studio, tmp_path):
- """Parity guard: keeping copies must not become never cleaning up."""
scripts, launcher = _configure_windows(monkeypatch, studio, tmp_path)
monkeypatch.setattr(studio, "_run_setup_script", lambda **_kwargs: None)
monkeypatch.setattr(studio.subprocess, "run", _successful_version_run())
diff --git a/unsloth_cli/_studio_stage.py b/unsloth_cli/_studio_stage.py
index a5a35c55bd7..33a4e049c0b 100644
--- a/unsloth_cli/_studio_stage.py
+++ b/unsloth_cli/_studio_stage.py
@@ -1,28 +1,27 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+"""The passive half of the 805-807 background update contract.
+
+Those shells run the INSTALLED (old) CLI with `--stage`, which clones the venv, runs this
+package's setup inside the clone and on POSIX imports `finalize_for_activation` from the staged
+tree. This wheel stages nothing, but those names must stay: stdlib only, importable under -I.
+"""
+
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"
-# Where a staged update parks the uv cache it used. The live marker is written only once
-# the stage is accepted, so an update that never activates cannot redirect the environment
-# it did not replace.
+# Where a staged update parks the uv cache it used; the live marker is written only once the
+# stage is accepted, so an update that never activates cannot redirect the environment.
UV_CACHE_MARKER = "uv-cache-dir"
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 = (
@@ -45,50 +44,12 @@ def runtime_root(studio_home: Path) -> Path:
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,
- encoding = "utf-8",
- errors = "replace",
- )
- 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
@@ -107,7 +68,19 @@ def _is_venv_python_shell_wrapper(lines: list[bytes]) -> bool:
)
-def make_relocatable(venv: Path, *, exclude_scripts: tuple[str, ...] = ()) -> int:
+def _relocatable_script(body: bytes, original: int) -> bytes:
+ """The rewritten script, never shorter than the one the installer recorded: RELOCATABLE_SHEBANG is
+ 82 bytes, so past ~68 characters of venv path the rewrite would shrink it and install_manifest.py
+ calls that damage. The padding sits between shebang and body, unread by /bin/sh."""
+ shebang = RELOCATABLE_SHEBANG.encode("utf-8")
+ deficit = original - len(shebang) - len(body)
+ if deficit <= 0:
+ return shebang + body
+ # `# ` plus the newline is 3 bytes. Longer than the original is fine; only shorter reads as damage.
+ return shebang + b"# " + b"#" * max(deficit - 3, 0) + b"\n" + body
+
+
+def make_relocatable(venv: Path) -> 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):
@@ -117,7 +90,7 @@ def make_relocatable(venv: Path, *, exclude_scripts: tuple[str, ...] = ()) -> in
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():
+ if script.is_symlink() or not script.is_file():
continue
data = script.read_bytes()
lines = data.splitlines(keepends = True)
@@ -130,15 +103,11 @@ def make_relocatable(venv: Path, *, exclude_scripts: tuple[str, ...] = ()) -> in
body = b"".join(lines[3:])
else:
continue
- script.write_bytes(RELOCATABLE_SHEBANG.encode("utf-8") + body)
+ script.write_bytes(_relocatable_script(body, len(data)))
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,
@@ -152,23 +121,6 @@ def _run(command: list[str], *, cwd: Path, env: dict[str, str]) -> subprocess.Co
)
-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"],
@@ -184,14 +136,8 @@ def console_script(venv: Path) -> Path:
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.
- """
+ """POSIX runs this file, not `python -m`, so it is the probe that counts. Windows is exempt: quarantine
+ can take the unsigned launcher stub off a working install."""
if platform.system() == "Windows":
return
script = console_script(venv)
@@ -200,7 +146,7 @@ def probe_console_script(venv: Path, env: dict[str, str]) -> None:
try:
result = _run([str(script), "-h"], cwd = venv.parent, env = env)
except OSError as exc:
- # A shebang naming a missing interpreter fails here, not with a return code: the kernel refuses the exec.
+ # A shebang naming a missing interpreter fails here, not with a return code.
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:]}")
@@ -223,87 +169,3 @@ def child_environment(root: Path) -> dict[str, str]:
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 promote_uv_cache_marker(root: Path, studio_home: Path) -> Optional[Path]:
- """Publish the staged update's cache choice to the live install.
-
- Best effort in both directions: a stage that parked nothing leaves the live marker
- alone, and a live root that cannot be written costs the next update a preference.
- """
- source = root / UV_CACHE_MARKER
- try:
- payload = source.read_bytes()
- except OSError:
- return None
- if not payload.strip():
- return None
- marker = studio_home / "cache" / UV_CACHE_MARKER
- try:
- marker.parent.mkdir(parents = True, exist_ok = True)
- # Unlinked first: a write follows a symlink and truncates its target.
- marker.unlink(missing_ok = True)
- marker.write_bytes(payload)
- except OSError:
- return None
- return marker
-
-
-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)
- # After verification: until the probes pass there is no accepted stage.
- promote_uv_cache_marker(root, studio_home)
- 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 7f7f0f9a149..418ca372610 100644
--- a/unsloth_cli/commands/studio.py
+++ b/unsloth_cli/commands/studio.py
@@ -36,41 +36,18 @@ studio_app = typer.Typer(help = "Unsloth Studio commands.")
def _enable_verbose_access_logs() -> None:
- """Restore every per-request access log by disabling the burst dedup and the
- quiet-poll heartbeat. Inherited by the spawned/re-exec'd server via the env."""
os.environ["UNSLOTH_STUDIO_ACCESS_LOG_DEDUP_MS"] = "0"
os.environ["UNSLOTH_STUDIO_ACCESS_LOG_POLL_DEDUP_MS"] = "0"
-# Resolve install root: UNSLOTH_STUDIO_HOME, then STUDIO_HOME alias, then
-# sys.prefix inference (so a direct call to <root>/bin/unsloth resolves after
-# the installer's env var has expired), then legacy ~/.unsloth/studio.
-# UNSLOTH_STUDIO_HOME wins when both env vars are set.
-# Both halves, and the 8 KB ceiling, are Test-UnslothCmdShimFile's in install.ps1 and
-# _IsUnslothCmdShim's in scripts/uninstall.ps1. Bytes, not text: the shim is written
-# without a BOM but an edited copy may carry one, and a decode error here would be
-# indistinguishable from "not ours".
+# Root order: UNSLOTH_STUDIO_HOME, STUDIO_HOME, sys.prefix, legacy ~/.unsloth/studio. Markers mirror install.ps1 / uninstall.ps1 and are matched as bytes.
_CMD_SHIM_MARKERS = (b"unsloth-studio-managed-launcher", b"from unsloth_cli import app")
_CMD_SHIM_MAX_BYTES = 8192
def _looks_like_installer_managed_studio_home(candidate: Path) -> bool:
- """Sentinel check (studio.conf or bin shim) so a dev venv named
- unsloth_studio is not misidentified as a custom Unsloth root.
-
- On Windows bin\\unsloth.cmd counts too. Only install.sh writes
- share/studio.conf, so on a custom-root Windows install the generated
- unsloth.exe is the only sentinel there is, and antivirus quarantine deletes
- it -- after which this returns False, the root falls back to
- ~/.unsloth/studio, and every `unsloth studio ...` reads and writes the wrong
- installation. The .cmd is written by the same installer for the same
- directory, so it answers the same question.
-
- It has to be OUR .cmd: this decides which tree the CLI manages, and the
- directory is on PATH, so any file of that name would otherwise be enough to
- point a custom root at itself. Same marker Test-UnslothCmdShimFile in
- install.ps1 and the uninstaller's recursive-delete guard require.
- """
+ """Sentinel (share/studio.conf, or our own bin/unsloth.cmd) so a dev venv named
+ unsloth_studio is not taken for a custom root. It must be OUR shim: the dir is on PATH."""
if (candidate / "share" / "studio.conf").is_file():
return True
if platform.system() != "Windows":
@@ -81,12 +58,6 @@ def _looks_like_installer_managed_studio_home(candidate: Path) -> bool:
def _is_managed_cmd_shim(path: Path) -> bool:
- """Whether *path* is the .cmd shim this installer generates.
-
- Read as bytes and matched on the marker line install.ps1 writes. A hand
- rolled wrapper that happens to invoke the CLI is not this, and must not be
- taken as proof of an installer-managed root.
- """
try:
if path.stat().st_size > _CMD_SHIM_MAX_BYTES:
return False
@@ -121,18 +92,13 @@ STUDIO_HOME, _STUDIO_HOME_IS_CUSTOM = _resolve_studio_home()
def _ensure_studio_env_exported() -> None:
- """Re-export UNSLOTH_STUDIO_HOME / UNSLOTH_LLAMA_CPP_PATH only for real
- custom roots so subprocesses inherit the right install. Called from each
- studio subcommand entry rather than at import time, to avoid leaking env
- state into unrelated importers (tests, --help, CLI introspection).
- """
+ """Re-export UNSLOTH_STUDIO_HOME / UNSLOTH_LLAMA_CPP_PATH for custom roots only, per
+ subcommand rather than at import, so unrelated importers see no env changes."""
if not _STUDIO_HOME_IS_CUSTOM:
return
- # Truthy-check (not setdefault) so a blank UNSLOTH_STUDIO_HOME= does not
- # suppress the inferred custom root.
+ # Truthy-check, not setdefault: a blank UNSLOTH_STUDIO_HOME= must not win.
if not os.environ.get("UNSLOTH_STUDIO_HOME"):
os.environ["UNSLOTH_STUDIO_HOME"] = str(STUDIO_HOME)
- # When override == legacy default, llama.cpp stays at ~/.unsloth/llama.cpp.
try:
_legacy_studio = (Path.home() / ".unsloth" / "studio").resolve()
_is_legacy = STUDIO_HOME.resolve() == _legacy_studio
@@ -159,12 +125,10 @@ _CLOUDFLARE_INTENT_ENV = "_UNSLOTH_CLOUDFLARE_INTENT"
def _consume_start_api_key_marker_env() -> bool:
- """Consume the one-shot readiness marker passed across an Unsloth re-exec."""
return os.environ.pop(_START_API_KEY_MARKER_ENV, None) == "1"
def _preserve_cloudflare_intent(cloudflare: Optional[bool], secure: bool) -> None:
- """Carry the user's tri-state choice across compatibility re-execs."""
if _CLOUDFLARE_INTENT_ENV in os.environ:
return
if secure or cloudflare is True:
@@ -176,13 +140,10 @@ def _preserve_cloudflare_intent(cloudflare: Optional[bool], secure: bool) -> Non
os.environ[_CLOUDFLARE_INTENT_ENV] = intent
-# __file__ is unsloth_cli/commands/studio.py -- two parents up is the package root
-# (either site-packages or the repo root for editable installs).
_PACKAGE_ROOT = Path(__file__).resolve().parent.parent.parent
def _should_hide_windows_subprocesses() -> bool:
- """Hide child console windows only for non-interactive Windows launches."""
if platform.system() != "Windows":
return False
try:
@@ -192,7 +153,6 @@ def _should_hide_windows_subprocesses() -> bool:
def _windows_hidden_subprocess_kwargs() -> dict[str, object]:
- """Return Windows-only Popen kwargs that suppress transient console windows."""
if not _should_hide_windows_subprocesses():
return {}
@@ -213,46 +173,22 @@ def _windows_hidden_subprocess_kwargs() -> dict[str, object]:
return kwargs
-# Windows materialises the `unsloth` entry point as a generated, unsigned .exe that
-# Application Control denies while the signed interpreter beside it still runs, so
-# every managed invocation goes through the interpreter (issue #8490).
-#
-# Byte-identical to WINDOWS_CLI_ENTRYPOINT in studio/src-tauri/src/process.rs and to
-# $script:UnslothCliTrampoline in install.ps1, which carries the full rationale for
-# both halves and for the deliberate absence of -I.
+# Application Control denies the unsigned unsloth.exe, so managed invocations go through the interpreter (#8490). Byte-identical to process.rs and install.ps1.
_WINDOWS_CLI_ENTRYPOINT = (
"import sys, os; sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; "
"sys.argv[0] = 'unsloth'; from unsloth_cli import app; sys.exit(app())"
)
-# Asks the managed interpreter whether the trampoline's import would succeed, by
-# performing that exact import. The sys.path[0] scrub is
-# _WINDOWS_CLI_ENTRYPOINT's, kept a separate literal because a parity test
-# literal_evals that constant; the two must agree or the probe answers for a
-# different sys.path than the launch uses.
-#
-# `from unsloth_cli import app` rather than a find_spec, deliberately. find_spec
-# locates without executing, which sounds like the lighter question and is the
-# wrong one: it answers True for an empty unsloth_cli/ directory (a namespace
-# package), for a package whose __init__ raises, and for one whose dependencies
-# an interrupted install never fetched. Every one of those is a venv the
-# trampoline cannot start, and this probe gates the headless-public strip of
-# .bootstrap_password, so a false pass there is a public Unsloth with no login
-# page and no plaintext recovery credential. Paying the import is what makes the
-# probe's answer the launch's answer.
+# The trampoline's exact import (find_spec passes for an empty unsloth_cli), with the sys.path[0] scrub a parity test literal_evals.
_MANAGED_CLI_IMPORT_PROBE = (
"import sys, os; sys.path[:1] = [x for x in sys.path[:1] if getattr(sys.flags, 'safe_path', False) or x not in ('', os.getcwd())]; "
"from unsloth_cli import app; sys.exit(0)"
)
-# Seconds, and generous: this is a bare interpreter start plus the CLI package
-# import, and it can run from cold on a machine whose antivirus is scanning the
-# venv it just quarantined a file out of. The caller treats a timeout as "no
-# verdict" rather than as a missing package, so overrunning it is not fatal.
+# Generous: cold interpreter start plus package import. A timeout means "no verdict", not failure.
_MANAGED_CLI_IMPORT_PROBE_TIMEOUT = 60
-# CreateProcess refuses a program blocked by an Application Control policy with
-# ERROR_ACCESS_DISABLED_BY_POLICY, which Python surfaces as OSError.winerror.
+# ERROR_ACCESS_DISABLED_BY_POLICY, surfaced by Python as OSError.winerror.
_ERROR_ACCESS_DISABLED_BY_POLICY = 1260
@@ -261,30 +197,14 @@ def _managed_cli_argv(
*args: str,
isolated: bool = False,
) -> List[str]:
- """argv that runs the managed `unsloth` CLI through *python*.
-
- -X utf8 rather than PYTHONUTF8 so the encoding holds even for a caller that
- scrubs the environment. -X utf8 precedes -I because -I implies -E, which
- would discard PYTHONUTF8 but cannot touch a command-line -X.
-
- *isolated* mirrors the Isolation enum in studio/src-tauri/src/process.rs and
- carries the same rule: the default is inherit, because -I implies -E and -s
- and so drops PYTHONPATH, PYTHONWARNINGS, PYTHONHASHSEED and user
- site-packages that the console script honoured, an observable difference on
- machines with no policy at all. Only a caller that must reproduce an
- already-isolated launch asks for it, and today that is the desktop updater's
- health probe, matching build_update_command's Isolation::Isolated.
- """
+ """argv that runs the managed `unsloth` CLI through *python*. -X utf8 precedes -I because -I
+ implies -E. *isolated* mirrors Isolation in process.rs; the default inherits."""
flags = ["-X", "utf8", "-I"] if isolated else ["-X", "utf8"]
return [str(python), *flags, "-c", _WINDOWS_CLI_ENTRYPOINT, *args]
def _is_application_control_block(error: OSError) -> bool:
- """True when Windows refused to start a program because a policy blocks it.
-
- Distinct from a missing or corrupt executable: nothing ran, so the failure
- says nothing about the program itself.
- """
+ """True when Windows refused to start a program by policy: nothing ran."""
return getattr(error, "winerror", None) == _ERROR_ACCESS_DISABLED_BY_POLICY
@@ -315,16 +235,8 @@ def _studio_runtime_launch_guard(*, inherited: bool = False, wait: bool = False)
def _stream_for_subprocess(stream):
- """Return *stream* if it has a real OS file descriptor, else None.
-
- subprocess.run on Windows refuses to inherit std handles unless
- they're passed explicitly (otherwise close_fds=True forces
- bInheritHandles=False, and a CREATE_NO_WINDOW child ends up with
- no stdio at all). When sys.stdout / sys.stderr is a real fd-backed
- stream we want to hand it through; when it's been captured by a
- test harness (pytest's capsys, an in-memory wrapper, etc) we fall
- back to None so subprocess uses its default.
- """
+ """Return *stream* if it has a real OS fd, else None: Windows will not inherit std handles
+ unless passed explicitly, and a test-captured stream has no fd."""
if stream is None:
return None
try:
@@ -339,7 +251,6 @@ def _display_host_for_bind(run_mod, host: str) -> str:
def _network_share_host_for_bind(run_mod, host: str) -> str:
- """Return the LAN-facing host, with a fallback for older backends."""
resolver = getattr(run_mod, "_network_share_host_for_bind", None)
if resolver is None:
return _display_host_for_bind(run_mod, host)
@@ -357,9 +268,8 @@ def _is_wildcard_bind(host: str) -> bool:
def _openable_host_for_bind(run_mod, host: str) -> str:
- """The host for a URL we tell the user to open: the LAN address when one
- resolves, else loopback. A wildcard bind with no LAN address (WSL NAT,
- loopback-only) must never be printed as-is; no browser can open it."""
+ """Host to print in a URL: the LAN address when one resolves, else loopback. A
+ wildcard bind must never be printed as-is; no browser can open it."""
share_host = _network_share_host_for_bind(run_mod, host)
if _is_wildcard_bind(share_host):
return _loopback_bind_host_for(host)
@@ -424,7 +334,6 @@ def _emit_run_cloudflare_notice(
def _studio_venv_python() -> Optional[Path]:
- """Return the studio venv Python binary, or None if not set up."""
if platform.system() == "Windows":
p = STUDIO_HOME / "unsloth_studio" / "Scripts" / "python.exe"
else:
@@ -433,15 +342,8 @@ def _studio_venv_python() -> Optional[Path]:
def _managed_cli_site_packages_layout(python: Path) -> bool:
- """On-disk hint that the venv holding *python* still carries the CLI.
-
- Weaker than the import probe below and only used when the probe could not be
- run at all: an empty ``unsloth_cli/`` or an orphaned dist-info left by an
- interrupted install answers yes here without being importable.
-
- The dist-info is accepted alongside the package directory because an
- editable install of the checkout leaves a .pth and no unsloth_cli/ here.
- """
+ """On-disk hint that the venv still carries the CLI. Weaker than the import probe: an empty
+ unsloth_cli/ or an orphaned dist-info passes here."""
site_packages = python.parent.parent / "Lib" / "site-packages"
if (site_packages / "unsloth_cli").is_dir():
return True
@@ -449,28 +351,8 @@ def _managed_cli_site_packages_layout(python: Path) -> bool:
def _managed_cli_package_present(python: Path) -> bool:
- """Whether the venv holding *python* can still import the package the CLI runs.
-
- Windows only, and only asked when the console script is gone. The generated
- unsloth.exe is what proves a CLI on POSIX, but on Windows nothing launches it
- any more (issue #8490) and antivirus quarantine deletes the unsigned stub
- while leaving the environment perfectly able to run.
-
- Asked of the interpreter rather than of site-packages, because the two are
- not the same claim. What Windows launches is the trampoline's
- ``from unsloth_cli import app``, so an orphaned ``unsloth-*.dist-info`` (a
- moved editable checkout, an interrupted install) or an empty ``unsloth_cli/``
- directory is metadata, not a runnable CLI. It matters here specifically:
- this gate stands in front of the headless-public strip of
- .bootstrap_password, so passing a venv that then fails to import is the one
- outcome the gate's placement exists to prevent -- a public Unsloth with no
- login page and no plaintext recovery credential.
-
- The probe runs the trampoline's own ``from unsloth_cli import app`` rather
- than a cheaper spec lookup (see _MANAGED_CLI_IMPORT_PROBE for why the cheaper
- one answers a different question), with the same sys.path[0] scrub applied so
- an ``unsloth_cli`` directory in the caller's cwd cannot answer for the venv.
- """
+ """Whether the venv holding *python* can still import the package the CLI runs. Windows only,
+ and asked of the interpreter, since this gate fronts the .bootstrap_password strip."""
if platform.system() != "Windows":
return False
try:
@@ -478,41 +360,21 @@ def _managed_cli_package_present(python: Path) -> bool:
[str(python), "-X", "utf8", "-c", _MANAGED_CLI_IMPORT_PROBE],
capture_output = True,
timeout = _MANAGED_CLI_IMPORT_PROBE_TIMEOUT,
- # Same as every other managed-interpreter probe here: a non-interactive
- # Windows launch must not flash a console window (issue #8490's sibling).
+ # A non-interactive Windows launch must not flash a console window (#8490).
**_windows_hidden_subprocess_kwargs(),
)
except subprocess.TimeoutExpired:
- # Slow is not broken. A cold venv under an antivirus scan can take longer
- # than the probe waits, and the re-exec this gate stands in front of has
- # no timeout at all, so it would still come up. Fall back to the on-disk
- # layout rather than aborting an install that works -- the failure this
- # whole fallback exists to remove.
+ # Timeout is not failure: the untimed re-exec would still come up, so fall back to the on-disk layout.
return _managed_cli_site_packages_layout(python)
except (OSError, subprocess.SubprocessError):
- # No verdict for a different reason: the interpreter would not start at
- # all (missing, or denied by an Application Control policy). The re-exec
- # runs THAT interpreter, so it is going to fail the same way, and the
- # on-disk layout cannot say otherwise. Fail closed, because the caller
- # strips .bootstrap_password on a headless public launch before it
- # re-execs: passing here would leave a public Unsloth with no login page
- # and no plaintext recovery credential, which is worse than telling the
- # user to re-run setup.
+ # The re-exec runs that same interpreter. Fail closed: the caller strips .bootstrap_password first.
return False
return probe.returncode == 0
def _hsa_override_gfx_arch(value: Optional[str]) -> Optional[str]:
- """gfx arch named by an HSA_OVERRIDE_GFX_VERSION value, or None if unreadable.
-
- libhsakmt (topology.c) reads it as a major.minor.stepping triple
- (``sscanf(envvar, "%u.%u.%u%c") != 3`` rejects anything else) and the target
- name concatenates the stepping in hex, which is why 9.0.10 is gfx90a:
- 11.0.0 -> gfx1100, 11.5.1 -> gfx1151.
-
- Kept in sync with _hsa_override_gfx_arch in studio/install_python_stack.py and
- in install.sh.
- """
+ """gfx arch named by an HSA_OVERRIDE_GFX_VERSION value, or None if unreadable. Kept in sync
+ with _hsa_override_gfx_arch in studio/install_python_stack.py and install.sh."""
if not value:
return None
# [0-9] rather than str.isdigit()/\d, both of which accept non-ASCII digits.
@@ -526,13 +388,8 @@ def _hsa_override_gfx_arch(value: Optional[str]) -> Optional[str]:
def _torch_requires_rocm_metapackage(venv_dir: Path) -> bool:
- """Whether the installed torch actually resolves through the ``rocm`` meta-package.
-
- AMD's per-gfx wheels depend on it; the generic pytorch.org ROCm wheels vendor their
- own runtime and depend on nothing, so after a switch between them the meta-package is
- left behind describing a family with no bearing on what torch loads. Unknown shapes
- answer False: refusing to arbitrate leaves the environment untouched.
- """
+ """Whether the installed torch actually resolves through the ``rocm`` meta-package: the generic
+ pytorch.org wheels vendor their own runtime, so after a switch it is orphaned."""
for sp_pattern in ("lib/python*/site-packages", "Lib/site-packages"):
for sp in venv_dir.glob(sp_pattern):
for info in sp.glob("torch-*.dist-info"):
@@ -548,8 +405,7 @@ def _torch_requires_rocm_metapackage(venv_dir: Path) -> bool:
for line in text.splitlines():
if not line.lower().startswith("requires-dist:"):
continue
- # `Requires-Dist: rocm[libraries,devel]==7.13.0` and plain `rocm` both
- # count; `rocm-sdk-core` does not, it is a component not the arbiter.
+ # Plain `rocm` and `rocm[libraries,devel]` both count; `rocm-sdk-core` is a component, not the arbiter.
if re.search(r"requires-dist:\s*rocm(?![-_a-z0-9])", line, re.IGNORECASE):
return True
return False
@@ -557,37 +413,17 @@ def _torch_requires_rocm_metapackage(venv_dir: Path) -> bool:
def _installed_rocm_single_arch(venv_dir: Path) -> Optional[str]:
- """gfx arch the ROCm runtime in *venv_dir* ACTIVELY carries kernels for, or None.
-
- AMD's per-gfx index ships one runtime distribution per architecture,
- ``rocm-sdk-libraries-<family>``, and the torch beside it holds code objects for
- that family alone. Which one is live has to come from the ``rocm`` meta-package,
- whose ``Requires-Dist`` names the family AMD's torch resolved (verified on
- repo.amd.com/rocm/whl/gfx1151: ``rocm-sdk-libraries-gfx1151==7.13.0; extra ==
- "libraries"``). Globbing for a ``rocm_sdk_libraries_gfx*`` directory instead
- would read an ORPHAN: ``rocm`` upgrades in place across a family switch while the
- superseded runtime keeps its own distribution name and is never uninstalled, so a
- venv that has changed families holds both. Same reasoning and hazard as
- _installed_rocm_wheel_family in studio/install_python_stack.py.
-
- None means "do not act": no ``rocm``, unreadable metadata, more than one family
- named, or a MULTI-arch family such as gfx120x-all, whose runtime carries kernels
- for several ISAs and so contradicts no override.
- """
- # The bare `rocm` metadata only describes a LIVE install while torch still resolves
- # through it. Switching from AMD's per-gfx index to a generic pytorch.org one does not
- # uninstall it: the generic wheels vendor their own ROCm libraries and depend on no
- # meta-package, so `rocm` is orphaned and pip never removes it. Reading it then would
- # name the OLD family and clear an override the generic wheels may be the only reason
- # the GPU works at all.
+ """gfx arch the ROCm runtime in *venv_dir* ACTIVELY carries kernels for, or None. Read from the
+ `rocm` meta-package: globbing for rocm_sdk_libraries_gfx* would read an ORPHAN. None also
+ covers a MULTI-arch family such as gfx120x-all, which contradicts no override."""
+ # Only a LIVE install while torch resolves through it: the generic pytorch.org wheels orphan `rocm`, which would then name the OLD family.
if not _torch_requires_rocm_metapackage(venv_dir):
return None
_metadata: Optional[Path] = None
for sp_pattern in ("lib/python*/site-packages", "Lib/site-packages"):
for sp in venv_dir.glob(sp_pattern):
for info in sp.glob("rocm-*.dist-info"):
- # rocm-sdk-core and rocm-sdk-libraries-* also start "rocm-"; only the
- # bare `rocm` meta-package arbitrates.
+ # rocm-sdk-* also start "rocm-"; only the bare meta-package arbitrates.
if (
re.fullmatch(r"rocm-[^-]+\.dist-info", info.name)
and (info / "METADATA").is_file()
@@ -608,42 +444,23 @@ def _installed_rocm_single_arch(venv_dir: Path) -> Optional[str]:
if _m:
_families.add(_m.group(1).lower())
if len(_families) != 1:
- return None # nothing to arbitrate with, or two runtimes and no tie-break
+ return None
_family = _families.pop()
- # Single ISA only: gfx120x-all style families cover several architectures, so an
- # override naming one of them is contradicted by nothing.
+ # Single ISA only: a gfx120x-all family contradicts no override.
return _family if re.fullmatch(r"gfx[0-9a-f]+", _family) else None
def _clear_hsa_override_contradicting_install(venv_dir: Path) -> Optional[str]:
- """Drop an HSA_OVERRIDE_GFX_VERSION no installed kernel can satisfy (#7331).
-
- libhsakmt (topology.c) writes the variable's major.minor.stepping straight into
- the KFD node's EngineId and ROCr names the agent from that, so the override
- decides the ISA every later process sees. Against per-gfx wheels, which hold code
- objects for one architecture, an override naming a different one leaves the
- runtime asking for kernels the install does not contain and every launch fails on
- the first allocation, exactly as before the routing fix.
-
- install.sh clears it for the one launch it performs itself, but that unset dies
- with the installer: `unsloth studio update` runs install_python_stack.py as a
- child (studio/setup.sh:1444) and every later launch inherits the user's shell
- instead. This is the chokepoint the exec, the Windows Popen and the in-process
- paths all pass through.
-
- Keyed on the INSTALL, never on a hardware probe: on a generic multi-arch index
- there is nothing to contradict and the override is often the only thing making
- the GPU usable. Returns the installed arch when the variable was dropped.
- """
+ """Drop an HSA_OVERRIDE_GFX_VERSION no installed kernel can satisfy (#7331): against per-gfx
+ wheels it fails every launch, and install.sh's unset dies with the installer, so this is the
+ chokepoint every path shares. Keyed on the INSTALL, never a hardware probe."""
raw = os.environ.get("HSA_OVERRIDE_GFX_VERSION")
- # Windows ROCm ignores the variable entirely, so there is nothing to correct.
if not raw or platform.system() == "Windows":
return None
arch = _installed_rocm_single_arch(venv_dir)
if arch is None:
return None
named = _hsa_override_gfx_arch(raw)
- # Unreadable: libhsakmt rejects it too, so it is not this spoof to undo.
if named is None or named == arch:
return None
os.environ.pop("HSA_OVERRIDE_GFX_VERSION", None)
@@ -651,14 +468,7 @@ def _clear_hsa_override_contradicting_install(venv_dir: Path) -> Optional[str]:
def _clear_hsa_override_before_launch(silent: bool = False) -> Optional[str]:
- """Run the #7331 spoof clear for whichever entry point is about to launch.
-
- Every launch needs it, not just plain ``unsloth studio``: the group callback
- returns early once a subcommand is named, and ``unsloth run`` is bound straight
- to ``studio_run``, so both would otherwise reach llama-server and the backend
- with the contradicting override still set. Idempotent, so chained entry points
- are free to call it twice.
- """
+ """Run the #7331 spoof clear for whichever entry point is about to launch. Idempotent."""
_venv = STUDIO_HOME / "unsloth_studio"
_arch = _clear_hsa_override_contradicting_install(
Path(sys.prefix) if sys.prefix.startswith(str(_venv)) else _venv
@@ -674,17 +484,9 @@ def _clear_hsa_override_before_launch(silent: bool = False) -> Optional[str]:
def _find_run_py() -> Optional[Path]:
- """Find studio/backend/run.py.
-
- No CWD dependency — works from any directory.
- Since studio/ is now a proper package (has __init__.py), it lives in
- site-packages after pip install, right next to unsloth_cli/.
- """
- # 1. Relative to __file__ (site-packages or editable repo root)
run_py = _PACKAGE_ROOT / "studio" / "backend" / "run.py"
if run_py.is_file():
return run_py
- # 2. Unsloth venv's site-packages (Linux + Windows layouts)
for pattern in (
"lib/python*/site-packages/studio/backend/run.py",
"Lib/site-packages/studio/backend/run.py",
@@ -695,11 +497,8 @@ def _find_run_py() -> Optional[Path]:
def _install_state(deep: bool = False) -> dict:
- """verify_install() result for this install root.
-
- STUDIO_HOME is an extra search root so a CLI installed outside the managed
- venv still inspects the venv the desktop app launches.
- """
+ """verify_install() result for this root; STUDIO_HOME is an extra search root so a CLI outside
+ the managed venv still inspects the venv the desktop app launches."""
return _studio_deps.install_state(
extra_roots = (STUDIO_HOME / "unsloth_studio",),
deep = deep,
@@ -710,13 +509,8 @@ _RUN_MODULE = None
def _load_run_module():
- """Import studio.backend.run without relying on package resolution.
-
- `studio update` can leave a partial ``site-packages/studio/backend/``
- tree (plugin build artefacts only). That shadowed tree wins over an
- editable install and breaks ``from studio.backend.run import ...``.
- Loading by file path sidesteps the conflict.
- """
+ """Import studio.backend.run by file path: `studio update` can leave a partial
+ site-packages/studio/backend/ tree that shadows an editable install."""
global _RUN_MODULE
if _RUN_MODULE is not None:
return _RUN_MODULE
@@ -727,7 +521,6 @@ def _load_run_module():
loaded = sys.modules.get("studio.backend.run")
if loaded is not None:
- # __file__ can be None for namespace packages from partial trees.
loaded_path = Path(getattr(loaded, "__file__", None) or "").resolve()
if loaded_path == run_py.resolve():
_RUN_MODULE = loaded
@@ -748,29 +541,16 @@ def _load_run_module():
def _find_setup_script(repo_root: Optional[Path] = None) -> Optional[Path]:
- """Find studio/setup.sh or studio/setup.ps1.
-
- No CWD dependency — works from any directory.
-
- `repo_root` is the explicit --local checkout, when there is one. Its setup
- script has to win: the scripts build the frontend under their own
- $SCRIPT_DIR, and the editable install of `repo_root` removes the installed
- tree that the installed copy's script would have built into. studio/frontend
- /dist is gitignored, so a fresh checkout would then have no frontend at all.
- """
+ """Find studio/setup.sh or studio/setup.ps1, from any CWD. *repo_root* is the --local checkout
+ and its script must win, since the editable install removes the tree the installed one builds into."""
name = "setup.ps1" if platform.system() == "Windows" else "setup.sh"
- # 0. The checkout the caller actually asked to install from. No fallback:
- # dropping back to the installed copy's script is the exact behaviour
- # this branch exists to stop, so a checkout without one is unusable
- # rather than a reason to use somebody else's.
+ # No fallback: reaching for the installed copy's script is what this branch prevents.
if repo_root is not None:
s = repo_root / "studio" / name
return s if s.is_file() else None
- # 1. Relative to __file__ (site-packages or editable repo root)
s = _PACKAGE_ROOT / "studio" / name
if s.is_file():
return s
- # 2. Unsloth venv's site-packages
for pattern in (
f"lib/python*/site-packages/studio/{name}",
f"Lib/site-packages/studio/{name}",
@@ -780,25 +560,17 @@ def _find_setup_script(repo_root: Optional[Path] = None) -> Optional[Path]:
return None
-# Mirror in studio/backend/run.py argparse + backend denylist test;
-# bumping the cap in one place only desyncs.
+# Mirrored in studio/backend/run.py argparse and the backend denylist test; bump both.
_PARALLEL_MIN = 1
_PARALLEL_MAX = 64
-_PARALLEL_DEFAULT_RUN = 4 # pre-PR hardcoded for `unsloth studio run`
-# New Chat leaves the previous conversation generating and the admission queue caps decodes at
-# the slot count, so at 1 every extra chat queues. _slots_that_fit_on_gpu() may cut it back.
+_PARALLEL_DEFAULT_RUN = 4
+# At 1 every extra chat queues behind the generating one. _slots_that_fit_on_gpu() may cut it back.
_PARALLEL_DEFAULT_PLAIN = 4
def _resolve_secure(secure: bool, not_secure: bool) -> bool:
- """Reconcile the deprecated --not-secure alias with --secure/--no-secure.
-
- Typer parses --secure and --not-secure as independent options, so the alias
- cannot lean on Click's last-wins ordering the way --secure/--no-secure do.
- Restore that ordering from argv: --not-secure only forces secure off when it
- is the last of the secure flags on the command line, matching the backend's
- BooleanOptionalAction.
- """
+ """Reconcile the deprecated --not-secure alias with --secure/--no-secure. Typer parses them as
+ independent options, so last-wins ordering is restored from argv to match the backend."""
if not not_secure:
return secure
last_secure = max(
@@ -813,12 +585,8 @@ def _resolve_secure(secure: bool, not_secure: bool) -> bool:
def _iter_editable_studio_source_roots(venv_dir: Path):
- """Yield repo roots from setuptools `__editable___*_finder.py` files in
- *venv_dir*'s site-packages whose MAPPING includes a `studio` entry.
-
- Returns the parent dir of the mapped `studio` package (i.e. the repo
- root), so callers can append `/studio/...` to reach any subdir.
- """
+ """Yield repo roots from setuptools `__editable___*_finder.py` MAPPINGs naming `studio`, as the
+ parent of the mapped package."""
import ast
import re
@@ -829,9 +597,7 @@ def _iter_editable_studio_source_roots(venv_dir: Path):
src = finder.read_text(encoding = "utf-8")
except (OSError, UnicodeDecodeError):
continue
- # Tolerate single- or multi-line dict literals; [^}]* still
- # rejects nested dicts, which the setuptools template never
- # emits for editable installs.
+ # [^}]* still rejects nested dicts, which the setuptools template never emits.
m = re.search(r"^MAPPING\s*(?::[^=]*)?=\s*(\{[^}]*\})", src, re.M | re.S)
if not m:
continue
@@ -839,8 +605,7 @@ def _iter_editable_studio_source_roots(venv_dir: Path):
mapping = ast.literal_eval(m.group(1))
except (SyntaxError, ValueError):
continue
- # Defensive: literal_eval can return a set / list / None if the
- # matched literal is not a dict (regex captures `{...}`).
+ # literal_eval can return a set / list / None: the regex only captures `{...}`.
if not isinstance(mapping, dict):
continue
studio_pkg = mapping.get("studio")
@@ -849,17 +614,8 @@ def _iter_editable_studio_source_roots(venv_dir: Path):
def _find_frontend_dist() -> Optional[Path]:
- """Locate a built `studio/frontend/dist` (containing index.html).
-
- Probes (in order): package-local default, installer venv site-packages,
- editable source roots referenced from the installer venv. Returns None
- if nothing servable is found, so callers can decide to error or proceed
- in `--api-only` mode.
-
- Fixes the silent 404 when another `unsloth` on PATH shadows the
- installer's binary and points `_PACKAGE_ROOT` at a site-packages copy
- that never received a vite build.
- """
+ """Locate a built `studio/frontend/dist`, or None so callers can fall back to --api-only.
+ Editable source roots are probed too, so a shadowing `unsloth` on PATH cannot win."""
candidates: List[Path] = [_PACKAGE_ROOT / "studio" / "frontend" / "dist"]
venv_dir = STUDIO_HOME / "unsloth_studio"
for pattern in (
@@ -883,13 +639,10 @@ def _find_frontend_dist() -> Optional[Path]:
return None
-# ── helpers for `unsloth studio run` ────────────────────────────────
-
_direct_http_opener = None
def _direct_urlopen(request, timeout):
- """Open a process-local URL without proxies or redirects."""
global _direct_http_opener
if _direct_http_opener is None:
@@ -912,7 +665,6 @@ def _wait_for_server(
timeout: int = 30,
request_host: str = "127.0.0.1",
) -> bool:
- """Poll ``GET /api/health`` until the server responds 200 or *timeout* expires."""
import urllib.request
import urllib.error
@@ -930,12 +682,8 @@ def _wait_for_server(
def _create_api_key_inprocess(name: str) -> str:
- """Create an API key via direct storage call (no HTTP needed).
-
- Bypasses the ``must_change_password`` gate that blocks HTTP
- ``POST /api/auth/api-keys`` on fresh installs. Safe because the
- CLI already has filesystem access to ``~/.unsloth/studio``.
- """
+ """Create an API key via direct storage call, bypassing the ``must_change_password`` gate that
+ blocks HTTP POST /api/auth/api-keys on fresh installs."""
storage = _load_backend_auth_storage()
raw_key, _row = storage.create_api_key(
@@ -955,7 +703,6 @@ def _load_backend_auth_storage():
storage_py = auth_dir / "storage.py"
loaded = sys.modules.get("auth.storage")
if loaded is not None:
- # __file__ can be None for namespace packages from partial trees.
loaded_path = Path(getattr(loaded, "__file__", None) or "").resolve()
if loaded_path == storage_py.resolve():
return loaded
@@ -988,11 +735,9 @@ def _write_auth_secret(path: Path, secret: str) -> None:
os.chmod(tmp_path, 0o600)
except OSError:
pass
- # newline pins LF: text mode writes CRLF on Windows, and `$(cat ...)`
- # strips the LF but leaves the CR glued to the credential.
+ # newline pins LF: text mode writes CRLF and `$(cat ...)` leaves the CR on the credential.
with os.fdopen(fd, "w", encoding = "utf-8", newline = "\n") as f:
fd = -1
- # Newline so `cat` doesn't run it into the shell prompt; readers strip.
f.write(secret + "\n")
os.replace(tmp_path, path)
except Exception:
@@ -1012,9 +757,7 @@ def _connect_auth_db() -> sqlite3.Connection:
conn = sqlite3.connect(auth_dir / "auth.db")
# A live server writes this DB while the CLI runs; the default lock wait is zero.
conn.execute("PRAGMA busy_timeout=5000")
- # Mirror backend storage.get_connection: this path can create auth/ and
- # auth.db (the pre-exposure gate writes here first), and sqlite3.connect
- # makes the DB 0644 under a 022 umask. Keep both private.
+ # sqlite3.connect makes a new DB 0644 under a 022 umask; keep auth/ and auth.db private.
for _path, _mode in ((auth_dir, 0o700), (auth_dir / "auth.db", 0o600)):
try:
os.chmod(_path, _mode)
@@ -1173,17 +916,9 @@ def _create_desktop_secret_in_cli() -> str:
def _launch_publishes_tunnel(
*, cloudflare: Optional[bool], host: str, secure: bool, api_only: bool
) -> bool:
- """Whether this launch will publish Unsloth through the Cloudflare tunnel.
-
- CLI mirror of run.py's _cloudflare_tunnel_should_start, minus the Colab case
- (Colab launches never come through this CLI path). --secure implies the
- tunnel; --cloudflare only tunnels non-api-only wildcard binds.
-
- Kept separate from the deliberately wider _should_prompt_password_change: the
- guards keyed off THIS one exist because a headless tunnel launch strips
- .bootstrap_password and could lock the admin out, and a raw wildcard bind
- never strips, so widening them would add failure modes that protect nothing.
- """
+ """Whether this launch will publish Unsloth through the Cloudflare tunnel. Kept separate from
+ the wider _should_prompt_password_change, whose guards exist because a headless tunnel launch
+ strips .bootstrap_password."""
if secure:
return True
if cloudflare is not True:
@@ -1194,12 +929,6 @@ def _launch_publishes_tunnel(
def _bind_is_wildcard(host: str) -> bool:
- """Whether this bind really is every interface, rather than one address.
-
- Only used to word the prompt. `_launch_publishes_tunnel` already called
- `is_wildcard_host` on this launch, so its getaddrinfo for a non-literal host
- is not a new cost here.
- """
from unsloth_cli._tool_policy import is_wildcard_host
return is_wildcard_host(host)
@@ -1207,33 +936,10 @@ def _bind_is_wildcard(host: str) -> bool:
def _should_prompt_password_change(
*, cloudflare: Optional[bool], host: str, secure: bool, api_only: bool
) -> bool:
- """Whether this launch puts Unsloth where someone else can reach it.
-
- CLI mirror of run.py's gate, minus the Colab case (Colab launches never come
- through this CLI path). --secure implies the tunnel; --cloudflare only
- tunnels non-api-only wildcard binds.
-
- A raw non-loopback bind counts too, but only with a terminal attached. It is
- reachable by the whole network (and the internet on a machine with a public
- address) while starting no tunnel, so it previously got no prompt, no warning
- and no strip: the seeded admin password stayed live and was served in the page.
-
- is_external_host, NOT is_wildcard_host. The backend classifies exposure with
- auth/bootstrap_timeout._is_exposed_bind, which counts anything that is not one
- of the three loopback aliases; wildcard is a strict subset. The narrower test
- meant `unsloth studio -H 192.168.1.50`, an ordinary LAN bind, skipped the
- parent prompt and prompted in the re-exec'd child instead, and against an
- OLDER studio-venv child (supported by the mixed-version path, and with no
- backend gate) it prompted nowhere at all and served the seeded password. It is
- also cheaper: a frozenset lookup rather than getaddrinfo.
-
- The interactivity condition is what keeps this safe to ship. Everything
- downstream is calibrated to publishing a public URL: it refuses to launch when
- the deadline is disabled and it deletes .bootstrap_password, which would break
- the long-running containers that are the common use of -H 0.0.0.0. Headless
- raw binds therefore keep today's behaviour on the bootstrap deadline; only a
- launch with a human present is asked to set a password.
- """
+ """Whether this launch puts Unsloth where someone else can reach it. is_external_host, NOT
+ is_wildcard_host: the narrower test let an ordinary LAN bind reach an older child that served
+ the seeded password. A raw bind counts only with a terminal attached, since downstream deletes
+ .bootstrap_password and would break -H 0.0.0.0 containers."""
if secure:
return True
if not host or api_only:
@@ -1247,36 +953,19 @@ def _should_prompt_password_change(
def _prompt_streams_interactive() -> bool:
- """The prompt needs a real terminal for input and for the masked echo."""
try:
return sys.stdin.isatty() and sys.stderr.isatty()
except (AttributeError, ValueError):
return False
-# How long a raw-bind prompt waits for the FIRST keystroke before launching
-# anyway; once someone is typing there is no deadline. 30s because the launches
-# that reach here unwatched allocate a pty and never read it (`docker run -dt`,
-# `tmux new -d`, CI runners) and need to bind promptly: a longer stall can trip a
-# healthcheck into a restart loop, while 30s stays inside a default Docker
-# HEALTHCHECK start period and is ample for anyone actually watching. Mirrors run.py.
+# Wait for the FIRST keystroke only. 30s stays inside a default Docker HEALTHCHECK start period.
_UNATTENDED_PROMPT_SECONDS = 30.0
def _prompt_owns_the_terminal() -> bool:
- """Whether this process may DRIVE the terminal, not merely see one.
-
- A backgrounded shell job (`unsloth studio -H 0.0.0.0 &`) inherits the
- terminal so isatty() is True, but read_masked calls termios.tcsetattr and
- POSIX SIGTTOUs a background process group that does; the default action stops
- the process, freezing the launch instead of starting it -- the one thing
- widening this gate to raw binds must not do. Only the raw-bind branch
- consults this; a tunnel keeps failing closed rather than quietly proceeding.
-
- True on any doubt (no job control, no controlling terminal, no fileno):
- nothing can stop us there, so the isatty answer stands. Mirror of run.py's
- _prompt_owns_the_terminal -- keep the two in sync.
- """
+ """Whether this process may DRIVE the terminal, not merely see one: a backgrounded job passes
+ isatty() but read_masked's tcsetattr SIGTTOUs it and freezes the launch. True on any doubt."""
try:
return os.tcgetpgrp(sys.stdin.fileno()) == os.getpgrp()
except (AttributeError, OSError, ValueError):
@@ -1284,12 +973,8 @@ def _prompt_owns_the_terminal() -> bool:
def _bootstrap_deadline_active() -> bool:
- """Whether the backend's bootstrap shutdown deadline will arm.
-
- Mirror of studio/backend/auth/bootstrap_timeout.py bootstrap_timeout_seconds:
- unset/blank/malformed UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT falls back to the 1h
- default (a typo must not remove protection); 0 or negative disables it.
- """
+ """Whether the backend's bootstrap shutdown deadline will arm. Mirror of
+ studio/backend/auth/bootstrap_timeout.py: malformed falls back to the 1h default, 0 disables."""
raw = os.environ.get("UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT", "").strip()
if not raw:
return True
@@ -1299,18 +984,13 @@ def _bootstrap_deadline_active() -> bool:
return True
-# Set by the parent once it has put the prompt in front of this terminal and got
-# nothing, so the re-exec'd child does not repeat the wait.
+# Set by the parent after an unanswered prompt so the re-exec'd child does not repeat the wait.
_UNATTENDED_PROMPT_DONE_ENV = "UNSLOTH_STUDIO_UNATTENDED_PROMPT_DONE"
def _deadline_sentence() -> str:
- """Say what will actually happen, not what usually happens.
-
- UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT=0 disables the shutdown entirely, and this is
- the sentence an operator acts on, so promising a deadline that will never arm
- is worse than saying nothing.
- """
+ """Say what will actually happen: BOOTSTRAP_TIMEOUT=0 arms no deadline, and promising one an
+ operator acts on is worse than saying nothing."""
if _bootstrap_deadline_active():
return (
"Unsloth shuts down after the bootstrap deadline "
@@ -1325,7 +1005,6 @@ def _deadline_sentence() -> str:
def _generate_reset_password() -> str:
- """Readable 4-word passphrase; the user has to type this one back in."""
try:
import diceware
return diceware.get_passphrase(
@@ -1342,13 +1021,8 @@ def _cli_update_password(
*,
revoke_api_keys: bool = False,
) -> None:
- """CLI mirror of backend update_password + change-password route effects.
-
- One transaction: rehash, rotate the JWT secret, clear must_change_password,
- revoke refresh tokens (PR #6651 finding), drop the desktop secret, and (for a
- reset) the API keys the old credential could have minted. File cleanup happens
- after commit; a failed unlink must not roll the change back.
- """
+ """CLI mirror of backend update_password + change-password effects, in one transaction. File
+ cleanup runs after commit, so it cannot roll back."""
password_salt, password_hash = _hash_password(new_password)
with conn:
conn.execute(
@@ -1371,12 +1045,7 @@ def _cli_update_password(
try:
stale_path.unlink(missing_ok = True)
except OSError as exc:
- # The hash is already committed, so a failed unlink must NOT roll the
- # change back. But a locked-yet-writable file (Windows AV, read-only
- # auth dir) must be truncated: otherwise its stale plaintext survives
- # and generate_bootstrap_password() would re-validate this revoked
- # credential if auth.db is ever recreated. Mirrors backend
- # clear_bootstrap_password().
+ # The hash is committed, so a failed unlink must not roll back, but a locked-yet-writable file must be truncated or its plaintext re-validates the credential.
try:
stale_path.write_text("", encoding = "utf-8")
cleared = True
@@ -1398,15 +1067,9 @@ def _cli_update_password(
def _apply_supplied_password_before_launch(supplied_password: "str | None") -> None:
- """Non-interactively set the INITIAL admin password (from --password /
- UNSLOTH_STUDIO_PASSWORD / stdin) before the server binds, while the account
- still has its auto-generated bootstrap password.
-
- Only ever sets the FIRST password: an already-set one is a hard error (an
- override would be an auth bypass on a public launch), and an invalid value
- fails closed. Runs in the parent before any re-exec so the secret never
- crosses to the child argv.
- """
+ """Non-interactively set the INITIAL admin password before the server binds. Only ever the
+ FIRST one: an override would be an auth bypass, and the parent runs it so the secret never
+ crosses to child argv."""
if not supplied_password:
return
try:
@@ -1453,8 +1116,7 @@ def _apply_supplied_password_before_launch(supplied_password: "str | None") -> N
_cli_update_password(conn, DEFAULT_ADMIN_USERNAME, supplied_password)
typer.echo(f"Password updated for '{DEFAULT_ADMIN_USERNAME}'.", err = True)
except (OSError, sqlite3.Error) as exc:
- # Any DB failure fails closed (typer.Exit is not caught here, so the
- # deliberate Exit(1) branches above propagate unchanged).
+ # Fail closed on any DB failure (typer.Exit from the branches above propagates).
typer.echo(
f"Error: --password could not update the Unsloth auth database ({exc}); not starting.",
err = True,
@@ -1465,15 +1127,8 @@ def _apply_supplied_password_before_launch(supplied_password: "str | None") -> N
def _strip_seeded_bootstrap_password_or_exit(*, context: str) -> None:
- """Remove the seeded plaintext bootstrap password before a public re-exec.
-
- Version-independent protection: a re-exec'd child of ANY version (including an
- old studio-venv predating the pre-bind gate) then reads None instead of
- injecting the default credential into the public page. must_change_password
- stays set, so the login page still forces a change and the timer still arms.
- Removal IS the protection, so if it fails (locked file, read-only auth dir)
- fail closed rather than publish it.
- """
+ """Remove the seeded plaintext bootstrap password before a public re-exec, so a child of ANY
+ version reads None. Removal IS the protection, so a failed removal fails closed."""
bootstrap_file = STUDIO_HOME / "auth" / BOOTSTRAP_PASSWORD_FILE
try:
bootstrap_file.unlink(missing_ok = True)
@@ -1493,26 +1148,14 @@ def _strip_seeded_bootstrap_password_or_exit(*, context: str) -> None:
def _require_servable_frontend_or_exit(
*, frontend: Optional[Path], api_only: bool, cloudflare: Optional[bool], host: str, secure: bool
) -> Optional[Path]:
- """Fail closed BEFORE the pre-exposure gate if a public UI launch has no
- login page to change the seeded password.
-
- The gate strips the seeded .bootstrap_password on a headless public launch,
- so if the child then cannot serve the login page the admin is locked out
- (must_change_password=1, no file, no UI) until `unsloth studio reset-password`.
- The login page is the ONLY in-band way to change the seeded password, so a
- public non-api-only launch must have a servable dist before the strip.
-
- Returns the dist to serve: a user-supplied --frontend (validated to contain
- index.html) or the auto-resolved built dist. Returns `frontend` unchanged for
- non-public or --api-only launches (no login page needed).
- """
+ """Fail closed BEFORE the pre-exposure gate if a public UI launch has no login page: the gate
+ strips .bootstrap_password, and the login page is the only in-band way to change it."""
if api_only or not _launch_publishes_tunnel(
cloudflare = cloudflare, host = host, secure = secure, api_only = api_only
):
return frontend
if frontend is not None:
- # A user-supplied dist is not vetted by _find_frontend_dist, so verify it
- # can serve the login page; else `--frontend /bad/path` bypasses the guard.
+ # A user-supplied dist is not vetted, so `--frontend /bad/path` would otherwise bypass the guard.
if (Path(frontend) / "index.html").is_file():
return frontend
typer.echo(
@@ -1523,7 +1166,6 @@ def _require_servable_frontend_or_exit(
err = True,
)
raise typer.Exit(1)
- # _find_frontend_dist only returns a path that already contains index.html.
resolved = _find_frontend_dist()
if resolved is not None:
return resolved
@@ -1539,15 +1181,8 @@ def _require_servable_frontend_or_exit(
def _validate_inproc_backend_before_strip(
*, cloudflare: Optional[bool], host: str, secure: bool, api_only: bool
) -> None:
- """In-venv (in-process) analogue of the re-exec launcher check.
-
- In-venv there is no re-exec, so the backend is imported in-process only AFTER
- the gate. On the headless public path the gate strips the seeded
- .bootstrap_password, so a broken venv that fails at import would leave
- must_change_password=1 with no password to log in. Import the backend up front
- on that path and exit cleanly if broken, before anything is stripped.
- Headless-only so an interactive prompt is not delayed behind the import.
- """
+ """In-venv analogue of the re-exec launcher check: import the backend before the gate strips
+ .bootstrap_password. Headless only, so no prompt waits on the import."""
if not _launch_publishes_tunnel(
cloudflare = cloudflare, host = host, secure = secure, api_only = api_only
):
@@ -1567,18 +1202,8 @@ def _validate_inproc_backend_before_strip(
def _tunnel_binary_confirmed_unavailable() -> bool:
- """True only if cloudflared is provably unavailable (found nowhere on PATH or
- in the Unsloth cache AND the download failed), so the tunnel cannot start.
-
- Used on the --secure path (loopback bind, so the tunnel is the ONLY public
- exposure) to skip stripping the seeded recovery password before a public URL
- that will never come up. Loads the stdlib-only cloudflare_tunnel helper by
- file path so the check runs in the parent, before the strip.
-
- Returns False on ANY uncertainty: a possible credential leak outweighs a
- recoverable lockout, so the caller keeps the strip unless the tunnel is
- provably dead.
- """
+ """True only if cloudflared is provably unavailable, so --secure can keep the seeded recovery
+ password. False on ANY uncertainty: a leak outweighs a recoverable lockout."""
run_py = _find_run_py()
if run_py is None:
return False
@@ -1586,10 +1211,7 @@ def _tunnel_binary_confirmed_unavailable() -> bool:
tunnel_py = backend_dir / "cloudflare_tunnel.py"
if not tunnel_py.is_file():
return False
- # ensure_cloudflared() lazily imports utils.paths.storage_roots to resolve the
- # Unsloth bin cache. The outer CLI hasn't added studio/backend to sys.path yet,
- # so that import would fail and return None (a false "unavailable" that wrongly
- # refuses --secure). Add the backend dir so the cache path resolves as in the child.
+ # ensure_cloudflared() imports utils.paths lazily; without studio/backend on sys.path it returns a false "unavailable" that wrongly refuses --secure.
added_backend_path = False
try:
if str(backend_dir) not in sys.path:
@@ -1612,17 +1234,8 @@ def _tunnel_binary_confirmed_unavailable() -> bool:
def _child_self_suppresses(*, in_studio_venv: bool, child_run_py: Optional[Path]) -> bool:
- """True when the child that will serve Unsloth is provably THIS install's
- backend, whose pre-bind gate sets app.state.suppress_bootstrap_injection and
- so never serves the seeded credential publicly -- even with .bootstrap_password
- on disk. The parent-side strip is then unnecessary and can be skipped to avoid
- a lockout if the tunnel never comes up, keeping the file for LOCAL recovery.
-
- True iff we run in-process here, or the re-exec target is the outer install's
- own run.py (identity match). False on ANY doubt -- a studio-venv console script
- or a venv run.py that may predate the gate -- so the strip stays in force
- wherever an old child is possible.
- """
+ """True when the child serving Unsloth is provably THIS install's backend, which suppresses the
+ seeded credential, so the strip can be skipped. False on ANY doubt."""
if in_studio_venv:
return True
if child_run_py is None:
@@ -1642,60 +1255,31 @@ def _enforce_password_change_before_exposure(
api_only: bool,
child_self_suppresses: bool = False,
) -> None:
- """Force a terminal password change before the first public (tunnel) exposure.
-
- When the launch will start the tunnel and the admin still has its
- auto-generated bootstrap password, ask for a new one in the terminal (masked,
- confirmed) before any server or tunnel exists. Committing here, in the parent,
- keeps the password off argv/env and an older studio-venv child sees it
- immediately. Without a terminal, warn and fall back to the bootstrap shutdown
- timer (~1h, UNSLOTH_STUDIO_BOOTSTRAP_TIMEOUT).
- """
+ """Force a terminal password change before the first public (tunnel) exposure. Committing in the
+ parent keeps it off argv/env; without a terminal, fall back to the bootstrap shutdown timer."""
if not _should_prompt_password_change(
cloudflare = cloudflare, host = host, secure = secure, api_only = api_only
):
return
- # Only a tunnel launch is genuinely "a public Cloudflare URL"; a raw bind is
- # the LAN behind a NAT router, or the internet on a cloud box. Use the real
- # predicate, not `cloudflare is True`: a non-secure tunnel only starts for a
- # wildcard host, so `--cloudflare -H 192.168.1.50` starts none and is reached
- # through the raw bind instead. Naming the wrong one in the one message the
- # operator is meant to act on trains people to ignore it.
+ # Use the real predicate, not `cloudflare is True`: a non-secure tunnel only starts for a wildcard host.
tunnel_will_start = _launch_publishes_tunnel(
cloudflare = cloudflare, host = host, secure = secure, api_only = api_only
)
if not tunnel_will_start and os.environ.get(_UNATTENDED_PROMPT_DONE_ENV):
- # An outer CLI already sat at this terminal for the full deadline and
- # nobody typed. `unsloth studio run` re-execs into the studio venv and
- # re-enters this gate, so without this the SAME unattended pty is waited
- # on again: 30s becomes 60s before the backend gate even gets its turn,
- # long enough to trip a startup watchdog. The parent committed the default
- # admin before setting this, so there is nothing left to do. Peeked, never
- # popped: run.py consumes it, and popping here would hand the backend a
- # fresh 30s wait. Never for a tunnel, which fails closed -- a marker from
- # an earlier raw-bind attempt must not buy a public URL a free pass.
+ # The outer CLI already waited out this terminal. Peeked, never popped (run.py consumes it); never for a tunnel, which fails closed.
return
if tunnel_will_start:
exposure = "on a public Cloudflare URL"
elif _bind_is_wildcard(host):
exposure = "on every network interface"
else:
- # A concrete bind (`-H 192.168.1.50`, `-H myhost.local`) listens on that
- # address ONLY, so "every network interface" is untrue; the gate widened to
- # is_external_host and routes these here too. Name what the operator typed.
+ # A concrete bind listens on that address only, so "every network interface" is untrue.
exposure = f"at {host}, which other machines on the network can reach"
- # Before public exposure we must PROVE the admin password is no longer the
- # seeded default. If we cannot (auth DB won't open, or a fresh admin cannot be
- # seeded + committed below), an old studio-venv child could regenerate a fresh
- # bootstrap credential and serve it; stripping a file we can't vouch for cannot
- # stop a regeneration. So those cases fail closed, as does a failure after the
- # user typed a new password.
+ # Before public exposure we must PROVE the password is not the seeded default; an old child could regenerate one. Unprovable fails closed.
try:
conn = _connect_auth_db()
except (OSError, sqlite3.Error) as exc:
- # Cannot open the auth DB, so cannot confirm a committed admin exists.
- # Refuse rather than risk a child serving the default login; a transient
- # lock clears on retry.
+ # Cannot confirm a committed admin exists; a transient lock clears on retry.
typer.echo(
f"Error: refusing to expose Unsloth {exposure}: could "
f"not open the Unsloth auth database ({exc}) to confirm the admin "
@@ -1708,16 +1292,10 @@ def _enforce_password_change_before_exposure(
try:
try:
_ensure_cli_default_admin(conn)
- # Persist a freshly seeded admin before we might re-exec: the INSERT is
- # otherwise uncommitted and rolls back on conn.close(). If the seed or
- # commit fails, no admin is committed, so a re-exec'd OLD child finds
- # none, regenerates a fresh bootstrap password + file, and serves THAT
- # -- stripping cannot stop a regeneration. Can't prove a committed
- # admin, so fail closed.
+ # Persist a freshly seeded admin before any re-exec: uncommitted it rolls back on close and an OLD child would regenerate its own.
conn.commit()
except (OSError, sqlite3.Error) as exc:
- # Best-effort remove any half-written seed file (its row rolled back);
- # the launch is refused regardless.
+ # Best-effort remove any half-written seed file; the launch is refused regardless.
try:
(STUDIO_HOME / "auth" / BOOTSTRAP_PASSWORD_FILE).unlink(missing_ok = True)
except OSError:
@@ -1740,13 +1318,9 @@ def _enforce_password_change_before_exposure(
).fetchone()
except (OSError, sqlite3.Error) as exc:
if child_self_suppresses:
- # Could not read must_change back, but the child is this install's
- # own backend and suppresses the injection, so nothing serves the
- # seeded credential; proceed without stripping.
+ # The child suppresses the injection, so nothing serves the seeded credential.
return
- # The admin is committed above, so an old child finds it and won't
- # regenerate; we just couldn't read must_change back. Strip the seeded
- # file so nothing serves it, failing closed if the strip itself fails.
+ # The admin is committed, so an old child will not regenerate; strip anyway and fail closed.
typer.echo(
f"Warning: could not read the Unsloth admin state back ({exc}); "
"removing the seeded bootstrap password before public exposure.",
@@ -1757,8 +1331,7 @@ def _enforce_password_change_before_exposure(
if not row or not row[2]:
return
if not _prompt_streams_interactive():
- # Only proceed headless if the bootstrap shutdown deadline will protect
- # the launch: it never arms for api-only, and TIMEOUT=0 disables it.
+ # Only proceed headless if the bootstrap deadline protects the launch: it never arms for api-only, and TIMEOUT=0 disables it.
if api_only or not _bootstrap_deadline_active():
typer.echo(
"Error: refusing to publish Unsloth on a public Cloudflare "
@@ -1772,13 +1345,7 @@ def _enforce_password_change_before_exposure(
)
raise typer.Exit(1)
if child_self_suppresses:
- # The child is this install's own backend, whose pre-bind gate sets
- # app.state.suppress_bootstrap_injection, so the seeded credential
- # is never served publicly even with the file on disk. Skip the
- # strip: unnecessary here, and it would lock the user out if the
- # tunnel never comes up (e.g. a --secure loopback whose tunnel
- # fails). Keep the file for LOCAL recovery; must_change stays set
- # and the deadline arms.
+ # The child is this install's own backend and never serves the seeded credential publicly, so skip the strip and keep the file for LOCAL recovery.
typer.echo(
"Warning: Unsloth is being exposed publicly while the admin "
"account still uses its auto-generated bootstrap password. The "
@@ -1790,13 +1357,7 @@ def _enforce_password_change_before_exposure(
err = True,
)
return
- # The strip permanently removes the only plaintext recovery credential.
- # On --secure the bind is loopback, so the tunnel is the ONLY public
- # exposure: if cloudflared is provably unavailable no public URL can
- # start, so stripping would just lock the user out. Refuse with the
- # credential preserved. (A wildcard --cloudflare bind is public
- # regardless of the tunnel, so it still strips below, as does any
- # uncertainty.)
+ # On --secure the bind is loopback, so with cloudflared provably unavailable stripping the only recovery credential would just lock the user out.
if secure and _tunnel_binary_confirmed_unavailable():
typer.echo(
"Error: refusing to expose Unsloth: the Cloudflare tunnel binary "
@@ -1808,12 +1369,7 @@ def _enforce_password_change_before_exposure(
err = True,
)
raise typer.Exit(1)
- # Mixed-version safety: an OLD studio-venv child (predating this gate)
- # has no pre-bind suppression and would read the seeded credential back
- # from disk and inject it into the public HTML until the deadline.
- # Delete the file here, in the parent, so a fresh child of ANY version
- # reads None. must_change_password stays set, so the login page still
- # forces a change and the timer still arms; only the on-disk copy goes.
+ # An OLD studio-venv child would serve the seeded credential from disk, so delete it here in the parent; must_change_password stays set.
_strip_seeded_bootstrap_password_or_exit(context = "no terminal to change it")
typer.echo(
"Warning: Unsloth is being exposed publicly while the admin account "
@@ -1832,11 +1388,7 @@ def _enforce_password_change_before_exposure(
_pbkdf2_hex(candidate, password_salt.encode("utf-8")), password_hash
)
- # Ctrl+C aborts a TUNNEL launch and only a tunnel launch; on a raw bind it
- # declines the prompt and the launch continues, because that launch worked
- # before this gate existed. Saying "abort" there would leave an operator
- # believing they stopped a server that is in fact up on the network with
- # the auto-generated password.
+ # Ctrl+C aborts a TUNNEL launch only; on a raw bind it declines the prompt, because that launch worked before this gate existed.
refusal = (
"Ctrl+C to abort."
if tunnel_will_start
@@ -1849,12 +1401,7 @@ def _enforce_password_change_before_exposure(
try:
new_password = _password_prompt.prompt_new_password(
_is_current_password,
- # A raw bind must never block a launch that used to start. A
- # detached pty (`tmux new -d`, `docker run -dt`) passes every
- # isatty and process-group test yet nobody will ever type, so an
- # undeadlined read waits forever and no server starts; fall back
- # to the bootstrap deadline it already had. A tunnel keeps waiting
- # and fails closed rather than publish a public URL unprompted.
+ # A raw bind must never block a launch that used to start: a detached pty passes every isatty test yet nobody types. A tunnel fails closed.
first_key_timeout = None if tunnel_will_start else _UNATTENDED_PROMPT_SECONDS,
)
except _password_prompt.PromptUnattended:
@@ -1865,12 +1412,7 @@ def _enforce_password_change_before_exposure(
"with `unsloth studio reset-password`.",
err = True,
)
- # The child gate sees the SAME unattended terminal and would wait its
- # own deadline again: 30s becomes 60s, or 90 on the `studio run` path
- # that re-enters this gate after re-exec, long enough to trip a startup
- # watchdog into the restart loop the deadline exists to avoid. Tell the
- # child the terminal has been tried. A direct `python run.py` sets
- # nothing, so it keeps its own backstop.
+ # Tell the child the terminal has been tried, or it waits its own deadline on the same pty and can trip a startup watchdog.
os.environ[_UNATTENDED_PROMPT_DONE_ENV] = "1"
return
except (KeyboardInterrupt, EOFError):
@@ -1882,11 +1424,7 @@ def _enforce_password_change_before_exposure(
err = True,
)
raise typer.Exit(1)
- # A raw bind is not a publication: it worked before the prompt
- # existed, so Ctrl+C returns it to that rather than refusing to start.
- # run.py's gate makes the same choice, and this mirror is what actually
- # runs for `unsloth studio -H 0.0.0.0`, so disagreeing here would make
- # run.py's warn-and-proceed unreachable.
+ # A raw bind is not a publication, so Ctrl+C returns it to pre-prompt behaviour, as run.py's gate does.
typer.echo(
"\nWarning: password change aborted, so Unsloth is starting with "
"the auto-generated admin password on a bind that is reachable "
@@ -1918,7 +1456,6 @@ def _load_model_via_http(
timeout: int = 600,
request_host: str = "127.0.0.1",
) -> dict:
- """POST to ``/api/inference/load`` using the API key for auth."""
import json
import urllib.request
import urllib.error
@@ -1960,10 +1497,8 @@ def _load_model_via_http(
try:
body = json.loads(resp.read())
except ValueError:
- body = None # truncated padded reply; rejected below
- # A slow load commits its 200 before it finishes and pads the body, so a late
- # failure arrives in-band; raise it as the HTTPError this function already turns
- # into the RuntimeError the caller reports. A truncated body is no report at all.
+ body = None
+ # A slow load commits its 200 early and pads the body, so a late failure arrives in-band.
return require_completed_padded_body(url, raise_for_deferred_error(url, body))
except urllib.error.HTTPError as exc:
body = exc.read().decode(errors = "replace")
@@ -1983,9 +1518,6 @@ def _format_context_length_line(load_result: dict) -> Optional[str]:
return f" Context length: {value_int} tokens"
-# ── unsloth studio (server) ──────────────────────────────────────────
-
-
@studio_app.callback(invoke_without_command = True)
def studio_default(
ctx: typer.Context,
@@ -2064,14 +1596,11 @@ def studio_default(
"process list and shell history. Rotate later with `unsloth studio reset-password`.",
),
):
- """Launch the Unsloth Studio server."""
- # Back-compat: --not-secure is a deprecated alias for --no-secure.
+ # --not-secure is a deprecated alias for --no-secure.
secure = _resolve_secure(secure, not_secure)
- # Runs before every subcommand (run/setup/update/...).
_ensure_studio_env_exported()
if ctx.invoked_subcommand is not None:
- # Typer doesn't forward parent options to subcommands, so
- # `unsloth studio --parallel N run ...` would silently drop N.
+ # Typer does not forward parent options, so `unsloth studio --parallel N run` would drop N.
if parallel != _PARALLEL_DEFAULT_PLAIN:
typer.echo(
f"Error: --parallel on `unsloth studio` applies to the "
@@ -2082,7 +1611,6 @@ def studio_default(
err = True,
)
raise typer.Exit(2)
- # Same for --cloudflare/--no-cloudflare: it would not reach the subcommand.
if cloudflare is not None:
_cf_flag = "--cloudflare" if cloudflare else "--no-cloudflare"
typer.echo(
@@ -2093,7 +1621,6 @@ def studio_default(
err = True,
)
raise typer.Exit(2)
- # Same for --secure: it would not reach the subcommand.
if secure:
typer.echo(
f"Error: --secure on `unsloth studio` applies to the "
@@ -2103,7 +1630,6 @@ def studio_default(
err = True,
)
raise typer.Exit(2)
- # Same for --verbose: it would not reach the subcommand.
if verbose:
typer.echo(
f"Error: --verbose on `unsloth studio` applies to the "
@@ -2113,7 +1639,6 @@ def studio_default(
err = True,
)
raise typer.Exit(2)
- # Same for --enable-tools/--disable-tools: it would not reach the subcommand.
if enable_tools is not None:
_tool_flag = "--enable-tools" if enable_tools else "--disable-tools"
typer.echo(
@@ -2133,7 +1658,6 @@ def studio_default(
err = True,
)
raise typer.Exit(2)
- # Same for --api-only: dropping it here would silently serve the UI.
if api_only:
typer.echo(
f"Error: --api-only on `unsloth studio` applies to the "
@@ -2143,7 +1667,6 @@ def studio_default(
err = True,
)
raise typer.Exit(2)
- # Same for --password: it applies to the plain-server path only.
if password:
typer.echo(
f"Error: --password on `unsloth studio` applies to the "
@@ -2181,8 +1704,7 @@ def studio_default(
host = _normalize_wildcard_bind_host(host)
_require_unambiguous_ephemeral_bind(host, port)
- # --verbose restores the per-request access logs that are suppressed by
- # default (plain-server path; the `run` subcommand has its own --verbose).
+ # --verbose restores the per-request access logs suppressed by default.
if verbose:
_enable_verbose_access_logs()
if disable_dns_pinning:
@@ -2190,15 +1712,10 @@ def studio_default(
else:
os.environ.setdefault("UNSLOTH_STUDIO_DISABLE_DNS_PINNING", "0")
- # Use the studio venv if present and not already in it. Resolve the child
- # launcher BEFORE the gate: a headless gate strips the seeded
- # .bootstrap_password, so aborting afterward (venv/run.py missing) would leave
- # must_change_password=1 with no password to log in.
+ # Resolve the child launcher BEFORE the gate: a headless gate strips the seeded password, so aborting afterwards leaves no way to log in.
studio_venv_dir = STUDIO_HOME / "unsloth_studio"
in_studio_venv = sys.prefix.startswith(str(studio_venv_dir))
- # Before any of the three launch paths below, and before the environment is handed
- # to a child: an override contradicting single-arch wheels makes every kernel launch
- # fail, and the installer's own unset cannot reach a launch it does not perform (#7331).
+ # Before the env reaches a child: an override contradicting single-arch wheels fails every kernel launch, and install.sh's unset cannot reach here (#7331).
_clear_hsa_override_before_launch(silent = silent)
studio_python = run_py = None
resolved_frontend = frontend
@@ -2208,10 +1725,7 @@ def studio_default(
if not (studio_python and run_py):
typer.echo("Unsloth Studio not set up. Run install.sh first.")
raise typer.Exit(1)
- # A public UI launch must have a servable login page BEFORE the gate can
- # strip the seeded .bootstrap_password, or the child has no way to change
- # it. Also returns the resolved dist so the child serves a real build
- # regardless of where its __file__ lands (fixes the shadowed silent 404).
+ # A public UI launch needs a servable login page before the gate strips the seeded password.
resolved_frontend = _require_servable_frontend_or_exit(
frontend = resolved_frontend,
api_only = api_only,
@@ -2219,17 +1733,11 @@ def studio_default(
host = host,
secure = secure,
)
- # Non-public / api-only launches skip that validation but still forward an
- # explicitly resolved dist for the same silent-404 reason.
+ # Non-public / api-only launches still forward a resolved dist, for the same silent 404.
if resolved_frontend is None and not api_only:
resolved_frontend = _find_frontend_dist()
else:
- # Already in the studio venv: no re-exec, served in-process below. On the
- # headless public path the gate strips the seeded .bootstrap_password, so
- # validate BOTH FIRST -- else a bad dist or broken venv fails only after
- # the strip (must_change_password=1, no password to log in). Frontend check
- # first (cheap); the backend import is headless-only so an interactive
- # prompt is not delayed behind it.
+ # In the studio venv there is no re-exec: validate frontend and backend BEFORE the headless gate strips the seeded password.
resolved_frontend = _require_servable_frontend_or_exit(
frontend = resolved_frontend,
api_only = api_only,
@@ -2241,18 +1749,9 @@ def studio_default(
cloudflare = cloudflare, host = host, secure = secure, api_only = api_only
)
- # A supplied --password / UNSLOTH_STUDIO_PASSWORD / stdin sets the initial
- # admin password here in the parent, before the gate and any re-exec, so the
- # secret never reaches the child argv; strip the env var so a re-exec'd child
- # can't re-read it. The interactive gate below then no-ops.
_apply_supplied_password_before_launch(_password_prompt.resolve_supplied_password(password))
os.environ.pop(_password_prompt.SUPPLIED_PASSWORD_ENV, None)
- # Public (tunnel) exposure with the seeded default password: force a terminal
- # password change first, before any re-exec or server exists. The child is
- # self-suppressing when we serve in-process or re-exec this install's own
- # run.py (its pre-bind gate suppresses the injection), so the gate can skip
- # the destructive strip.
_enforce_password_change_before_exposure(
cloudflare = cloudflare,
host = host,
@@ -2277,38 +1776,27 @@ def studio_default(
"--parallel",
str(parallel),
]
- # Forward the frontend dist resolved before the gate (skipped in
- # --api-only, which serves no UI).
if resolved_frontend is not None:
args.extend(["--frontend", str(resolved_frontend)])
if silent:
args.append("--silent")
if api_only:
args.append("--api-only")
- # Forward polarity explicitly: _find_run_py can fall back to an older
- # run.py (--cloudflare defaulted on), so an unset default must not let a
- # mixed install silently re-enable the tunnel. --secure implies it, so
- # forward nothing then.
+ # Explicit polarity: an older run.py defaults --cloudflare on, so an unset default must not re-enable the tunnel on a mixed install.
if cloudflare is True:
args.append("--cloudflare")
elif not secure:
args.append("--no-cloudflare")
args.append("--secure" if secure else "--no-secure")
- # Forward an explicit tool policy; None -> run.py leaves it unset (tools on).
if enable_tools is True:
args.append("--enable-tools")
elif enable_tools is False:
args.append("--disable-tools")
- # On Windows os.execvp keeps the parent alive, so Ctrl+C
- # would orphan the child; use Popen+wait instead.
+ # On Windows os.execvp keeps the parent alive and Ctrl+C would orphan the child.
if sys.platform == "win32":
import subprocess as _sp
- # Hand our std handles to the child: without them CREATE_NO_WINDOW
- # gives the backend its own hidden console and `unsloth studio > log`
- # captures nothing -- the same trap noted at the setup.ps1 call below.
- # Omitting stdin does not withhold it (subprocess still fills it from
- # GetStdHandle); that would need stdin = DEVNULL.
+ # Without our std handles, CREATE_NO_WINDOW gives the backend a hidden console and `unsloth studio > log` captures nothing.
with _studio_runtime_launch_guard(inherited = runtime_gate_handoff):
proc = _sp.Popen(
args,
@@ -2319,7 +1807,6 @@ def studio_default(
try:
rc = proc.wait()
except KeyboardInterrupt:
- # Child handles its own signal; let it finish.
rc = proc.wait()
if rc != 0:
typer.echo(
@@ -2360,16 +1847,13 @@ def studio_default(
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:
if run_mod._shutdown_event is not None:
- # Event.wait() with no timeout blocks at C-level on Linux
- # and swallows SIGINT; loop with a 1s timeout instead.
+ # Event.wait() with no timeout blocks at C level on Linux and swallows SIGINT.
while not run_mod._shutdown_event.is_set():
run_mod._shutdown_event.wait(timeout = 1)
else:
@@ -2382,19 +1866,15 @@ def studio_default(
getattr(run_mod, "_wait_for_server_shutdown", lambda: None)()
-# ── unsloth studio run ───────────────────────────────────────────────
-
-
def _split_repo_variant(model_arg: str) -> tuple[str, Optional[str]]:
- """Split ``org/name:variant`` into ``(repo, variant)``; mirrors
- llama.cpp's ``-hf <repo>:<quant>``. Local paths, Windows drives,
- and ids without ``:`` pass through verbatim."""
+ """Split ``org/name:variant`` into ``(repo, variant)``; mirrors llama.cpp's
+ ``-hf <repo>:<quant>``. Local paths, Windows drives and ids without ``:`` pass through."""
s = model_arg.strip()
if not s:
return s, None
if s.startswith(("/", "./", "../", "~")) or s == ".":
return s, None
- # Windows drive letter (e.g. "C:\path"): colon is a path separator.
+ # Windows drive letter: the colon is a path separator.
if len(s) >= 2 and s[1] == ":" and s[0].isalpha():
return s, None
if ":" not in s:
@@ -2402,17 +1882,14 @@ def _split_repo_variant(model_arg: str) -> tuple[str, Optional[str]]:
repo, _, variant = s.rpartition(":")
if not repo or not variant:
return s, None
- # Quant labels never contain a slash; `foo:bar/baz` isn't repo:variant.
+ # Quant labels never contain a slash; `foo:bar/baz` is not repo:variant.
if "/" in variant:
return s, None
return repo, variant
def _expand_attached_np_short() -> None:
- # Click clusters `-np8` as `-n -p 8` (-p = --port), dropping the parallel
- # value. Split to `-np <N>` so typer's alias matches. Stops at `--`;
- # accepts signed/junk forms so typer reports a clean error against `-np`.
- # Kept in lockstep with the backend `_flag_name` recogniser.
+ # Click clusters `-np8` as `-n -p 8`, dropping the value. Lockstep with the backend `_flag_name`.
i = 0
while i < len(sys.argv):
tok = sys.argv[i]
@@ -2433,15 +1910,14 @@ def _expand_attached_np_short() -> None:
def _consume_legacy_short_aliases(
args: List[str], aliases: tuple[str, ...], current: Optional[str], canonical: str
) -> tuple[Optional[str], List[str]]:
- """Pop exact-match legacy shorts (`-m`/`-hfr`/`-f`) from args;
- leave clusters (`-mg`/`-fa`/...) for the llama-server tail. Inline
- `-x=value` form also accepted."""
+ """Pop exact-match legacy shorts (`-m`/`-hfr`/`-f`) from args, leaving clusters
+ (`-mg`/`-fa`) for the llama-server tail. Inline `-x=value` accepted."""
out: List[str] = []
value = current
i, n = 0, len(args)
while i < n:
tok = args[i]
- if tok == "--": # end of options; tail is raw payload.
+ if tok == "--":
out.extend(args[i:])
break
name, sep, inline = tok.partition("=")
@@ -2452,7 +1928,7 @@ def _consume_legacy_short_aliases(
if value is not None:
raise typer.BadParameter(f"{name} conflicts with {canonical} already provided")
if sep:
- if inline == "": # `-m=` would become --model '' (Path('')='.').
+ if inline == "":
raise typer.BadParameter(f"{name} requires a non-empty value")
value = inline
i += 1
@@ -2468,7 +1944,6 @@ def _consume_legacy_short_aliases(
return value, out
-# Help panels so `unsloth run --help` groups options instead of one long list.
_RUN_PANEL_MODEL = "Model"
_RUN_PANEL_SERVER = "Server & network"
_RUN_PANEL_TOOLS = "Tool calls"
@@ -2489,9 +1964,7 @@ def run(
"--model",
"-hf",
"--hf-repo",
- # `-m` / `-hfr` removed (Click would cluster `-mg`/`-md`/...).
- # Exact-match `-m`/`-hfr` still work via the legacy shim below.
- # `-hf` stays (multi-char shorts don't cluster).
+ # `-m` / `-hfr` removed (Click clusters `-mg`/`-md`); the legacy shim still takes exact matches.
rich_help_panel = _RUN_PANEL_MODEL,
help = (
"Model path or HF repo. Accepts llama.cpp-style "
@@ -2558,7 +2031,6 @@ def run(
),
port: int = typer.Option(8888, "--port", "-p", rich_help_panel = _RUN_PANEL_SERVER),
host: str = typer.Option("127.0.0.1", "--host", "-H", rich_help_panel = _RUN_PANEL_SERVER),
- # `-f` removed (clustered `-fa`/`-fit*`); studio_default keeps it.
frontend: Optional[Path] = typer.Option(None, "--frontend", rich_help_panel = _RUN_PANEL_SERVER),
api_only: bool = typer.Option(
False,
@@ -2732,41 +2204,26 @@ def run(
):
"""Start Unsloth, load a model, print an API key -- one-liner server.
- Unknown flags pass through to llama-server (GGUF only). Unsloth
- rejects managed flags with HTTP 400: model identity, network
- (--host/--port/--path/--api-prefix/--reuse-port), auth/TLS
- (--api-key/--ssl-*), single-model UI (--ui/--models-*/--webui),
- and parallel slots (use --parallel above). Full denylist in
- studio/backend/core/inference/llama_server_args.py. Other knobs
- (-c, -ngl, --jinja, --flash-attn, -t, ...) pass through and
- last-wins-override Unsloth's auto-set value.
+ Unknown flags pass through to llama-server (GGUF only). Unsloth rejects managed flags with
+ HTTP 400: model identity, network, auth/TLS, single-model UI, and parallel slots (use
+ --parallel). Full denylist in studio/backend/core/inference/llama_server_args.py.
- Example:
unsloth studio run --model unsloth/Qwen3-1.7B-GGUF --gguf-variant UD-Q4_K_XL
- unsloth studio run --model unsloth/Qwen3-1.7B-GGUF --temperature 0.7 --seed 42 --parallel 8
- unsloth studio run --model some-model --chat-template-file /path/to/tpl.jinja
+ unsloth studio run --model unsloth/Qwen3-1.7B-GGUF --temperature 0.7 --parallel 8
unsloth studio run --model unsloth/Qwen3-27B-GGUF --gguf-variant Q8_0 --tensor-parallel
"""
- # A newer outer CLI can re-exec into an older Unsloth venv; pass this signal via
- # env so an older child ignores it instead of treating it as a llama-server arg.
+ # Passed via env, so an older re-exec target ignores it instead of treating it as a llama-server arg.
inherited_start_api_key_marker = _consume_start_api_key_marker_env()
start_api_key_marker = start_api_key_marker or inherited_start_api_key_marker
runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()
- # The group callback returns before its own clear once a subcommand is named, and
- # `unsloth run` is bound straight here, so this path has to do it itself or
- # llama-server and the backend start with the contradicting override (#7331).
+ # The group callback returns before its own clear once a subcommand is named, so this path must clear the override itself (#7331).
_clear_hsa_override_before_launch(silent = bool(silent))
- # Back-compat: --not-secure is a deprecated alias for --no-secure.
secure = _resolve_secure(secure, not_secure)
_preserve_cloudflare_intent(cloudflare, secure)
extra_llama_args: List[str] = list(ctx.args) if ctx.args else []
- # Tool-call healing/nudging are read from the env at backend import. Resolve here
- # (before any re-exec/import) so the in-venv child inherits the decision. When the
- # flag is omitted, respect a value the parent already set (e.g. `unsloth start`
- # forwards its choice via the env) and otherwise apply the default: healing on,
- # nudging on for a CLI-launched server.
+ # Read from the env at backend import, so resolve before any re-exec; an omitted flag keeps a value the parent forwarded.
_healing_disabled = (
os.environ.get("UNSLOTH_DISABLE_TOOL_CALL_HEALING") == "1"
if tool_call_healing is None
@@ -2778,10 +2235,7 @@ def run(
elif "UNSLOTH_TOOL_CALL_NUDGE" not in os.environ:
os.environ["UNSLOTH_TOOL_CALL_NUDGE"] = "1"
- # Sampling overrides: the backend resolver reads UNSLOTH_SAMPLING_* to hard-pin a field
- # (winning over both the client and the per-model recommendation). Only write a flag that
- # was set explicitly so an omitted flag inherits any value the parent forwarded (e.g.
- # `unsloth start`) and, when nothing is set, leaves the per-model recommendation in charge.
+ # UNSLOTH_SAMPLING_* hard-pins a field over client and per-model recommendation, so only write flags set explicitly.
for _sampling_env, _sampling_value in (
("UNSLOTH_SAMPLING_TEMPERATURE", temperature),
("UNSLOTH_SAMPLING_TOP_P", top_p),
@@ -2793,9 +2247,7 @@ def run(
if _sampling_value is not None:
os.environ[_sampling_env] = str(_sampling_value)
- # Set before any re-exec so the in-venv server inherits it via the env.
- # `run --verbose` used to pass through to llama-server (its own -v); keep
- # that by forwarding --log-verbose so we add Unsloth logs without dropping it.
+ # Set before any re-exec. --log-verbose keeps llama-server's own -v passthrough working.
if verbose:
_enable_verbose_access_logs()
if not any(a in ("--verbose", "-v", "--log-verbose") for a in extra_llama_args):
@@ -2805,8 +2257,7 @@ def run(
else:
os.environ.setdefault("UNSLOTH_STUDIO_DISABLE_DNS_PINNING", "0")
- # Promote legacy exact `-m`/`-hfr`/`-f` back into typer params;
- # clusters stay in extras.
+ # Promote legacy exact `-m`/`-hfr`/`-f` back into typer params; clusters stay in extras.
model, extra_llama_args = _consume_legacy_short_aliases(
extra_llama_args,
("-m", "-hfr"),
@@ -2830,8 +2281,7 @@ def run(
)
raise typer.Exit(2)
- # 0. Parse llama.cpp `repo:variant` in --model; error if also paired
- # with --gguf-variant and they disagree.
+ # Parse llama.cpp `repo:variant`; error if it disagrees with --gguf-variant.
parsed_repo, embedded_variant = _split_repo_variant(model)
if embedded_variant:
if gguf_variant and gguf_variant != embedded_variant:
@@ -2867,11 +2317,7 @@ def run(
host = _normalize_wildcard_bind_host(host)
_require_unambiguous_ephemeral_bind(host, port)
- # Tool policy does not depend on the bind: tools default on everywhere
- # (--secure is a loopback tunnel; the operator owns a raw bind). With no flag
- # this stays None, so the default applies without becoming an override and a
- # request's own enable_tools: false is honored. Resolve here so the re-exec'd
- # child inherits the same decision.
+ # Tool policy does not depend on the bind. None applies the default without becoming an override, so a request's enable_tools: false is honored.
from unsloth_cli._tool_policy import is_external_host, resolve_tool_policy
enable_tools = resolve_tool_policy(
@@ -2881,10 +2327,6 @@ def run(
silent = silent,
)
- # 1. Re-exec into the studio venv (same pattern as studio_default). Resolve
- # the child launcher BEFORE the gate: a headless gate strips the seeded
- # .bootstrap_password, so aborting afterward (venv/entry point missing) would
- # leave must_change_password=1 with no password to log in.
studio_venv_dir = STUDIO_HOME / "unsloth_studio"
in_studio_venv = sys.prefix.startswith(str(studio_venv_dir))
studio_bin = None
@@ -2894,24 +2336,13 @@ def run(
if not studio_python:
typer.echo("Unsloth Studio not set up. Run install.sh first.")
raise typer.Exit(1)
- # Re-exec via the studio venv's `unsloth` console-script. Windows ships it as
- # unsloth.exe, so the bare name is never a file there and `unsloth run` aborted
- # with "venv missing 'unsloth' entry point" on a perfectly good install.
- #
- # On Windows the file is no longer what gets launched (see the launch_head
- # below) and no longer the only thing that proves a CLI: quarantine deletes
- # the stub and leaves the environment able to run, so the installed package
- # answers for it.
+ # Re-exec via the studio venv's console script. On Windows quarantine deletes the stub from a working venv, so the package answers for it.
studio_bin = studio_python.parent / (
"unsloth.exe" if platform.system() == "Windows" else "unsloth"
)
if not studio_bin.is_file() and not _managed_cli_package_present(studio_python):
typer.echo("Unsloth venv missing 'unsloth' entry point. Re-run: unsloth studio setup")
raise typer.Exit(1)
- # `run` serves the same Unsloth UI (unless --api-only); a public launch must
- # have a servable login page BEFORE the gate strips the seeded password, or
- # the child has no way to change it. Validate here and forward the resolved
- # dist so a shadowed child that can't self-resolve one still serves it.
resolved_frontend = _require_servable_frontend_or_exit(
frontend = frontend,
api_only = api_only,
@@ -2920,10 +2351,6 @@ def run(
secure = secure,
)
else:
- # In-venv (in-process) run: validate the servable frontend and importable
- # backend before the headless gate strips the seeded password. Frontend
- # check first (cheap); backend import is headless-only so a prompt isn't
- # delayed.
resolved_frontend = _require_servable_frontend_or_exit(
frontend = frontend,
api_only = api_only,
@@ -2935,18 +2362,10 @@ def run(
cloudflare = cloudflare, host = host, secure = secure, api_only = api_only
)
- # A supplied --password / UNSLOTH_STUDIO_PASSWORD / stdin sets the initial
- # admin password here in the parent, before the gate and any re-exec, so the
- # secret never reaches the child argv; strip the env var so a re-exec'd child
- # can't re-read it. The interactive gate below then no-ops.
_apply_supplied_password_before_launch(_password_prompt.resolve_supplied_password(password))
os.environ.pop(_password_prompt.SUPPLIED_PASSWORD_ENV, None)
- # Public (tunnel) exposure with the seeded default password: force a terminal
- # password change first, before any re-exec or server exists. The re-exec here
- # runs the studio venv's `unsloth` console script (a possibly-OLD child), so it
- # is NOT provably self-suppressing -- only the in-process case is, and the
- # strip stays in force otherwise.
+ # Before any re-exec or server exists. This re-exec runs a possibly-OLD console script, so it is NOT provably self-suppressing.
_enforce_password_change_before_exposure(
cloudflare = cloudflare,
host = host,
@@ -2958,11 +2377,7 @@ def run(
)
if not in_studio_venv:
- # Windows launches the child through the venv interpreter rather than the
- # console script it just validated: Application Control blocks the
- # generated unsloth.exe on some machines, and the signed python.exe beside
- # it is not blocked. POSIX keeps execing the script directly, which is what
- # the os.execvp below needs anyway.
+ # Application Control blocks the generated unsloth.exe on some machines but not the signed python.exe beside it.
launch_head = (
_managed_cli_argv(studio_python) if sys.platform == "win32" else [str(studio_bin)]
)
@@ -2989,34 +2404,24 @@ def run(
args.extend(["--speculative-type", speculative_type])
if spec_draft_n_max is not None:
args.extend(["--spec-draft-n-max", str(spec_draft_n_max)])
- # Forward the explicit polarity; a future default flip on one
- # layer must not silently invert behaviour for the other.
+ # Explicit polarity: a future default flip on one layer must not invert the other.
args.append("--load-in-4bit" if load_in_4bit else "--no-load-in-4bit")
- # Forward the frontend resolved before the gate, not just a user-supplied
- # one: the parent may have found a built dist the shadowed child cannot,
- # and stripping without forwarding it would abort the child at frontend
- # setup (lockout).
+ # Not just a user-supplied dist: the parent may have found a build the shadowed child cannot, and the child would abort (lockout).
if resolved_frontend is not None:
args.extend(["--frontend", str(resolved_frontend)])
if api_only:
args.append("--api-only")
if silent:
args.append("--silent")
- # Forward the resolved tool policy so the child doesn't re-resolve. None
- # forwards neither flag: the child then leaves the policy unset too.
if enable_tools is True:
args.append("--enable-tools")
elif enable_tools is False:
args.append("--disable-tools")
- # Forward --yes only if the user passed it; resolution no longer prompts.
if yes:
args.append("--yes")
- # Typer claims --parallel outside ctx.args; without this the
- # child reverts to its default and silently drops the value.
+ # Typer claims --parallel outside ctx.args; without this the child reverts to its default.
args.extend(["--parallel", str(parallel)])
- # Always forward explicit polarity: a mixed-version studio venv whose old
- # default was --cloudflare-on must not silently re-enable the tunnel.
- # --secure implies it, so forward nothing then.
+ # Explicit polarity: a mixed-version studio venv whose old default was cloudflare-on must not re-enable the tunnel.
if cloudflare is True:
args.append("--cloudflare")
elif not secure:
@@ -3025,7 +2430,6 @@ def run(
args.append("--tensor-parallel" if tensor_parallel else "--no-tensor-parallel")
if verbose:
args.append("--verbose")
- # llama-server pass-through extras → child ctx.args → load payload.
if extra_llama_args:
args.extend(extra_llama_args)
@@ -3046,18 +2450,13 @@ def run(
else:
os.execvp(str(studio_bin), args)
finally:
- # execvp doesn't return on success; restore env after a Windows wait or a failed launch.
os.environ.pop(_START_API_KEY_MARKER_ENV, None)
- # ── 2. Start server (always suppress built-in banner) ─────────────
with _studio_deps.studio_backend_imports("unsloth studio"):
run_mod = _load_run_module()
run_server = run_mod.run_server
- # Match the route handlers' import path: run.py adds studio/backend/ to
- # sys.path, so they import as `state.tool_policy`. Set this before
- # run_server() starts uvicorn; once sockets are bound, routes can be hit.
- # run_server() applies the same pair; both calls are idempotent.
+ # Match the route handlers' import path and set it before uvicorn binds; run_server() applies the same pair, idempotently.
from state.tool_policy import set_tool_policy, set_tool_policy_default
set_tool_policy_default(True)
@@ -3071,23 +2470,15 @@ def run(
llama_parallel_slots = parallel,
cloudflare = cloudflare,
secure = secure,
- # Headless serving prints its own URL/API-key banner; the Tauri-only
- # TAURI_PORT line would corrupt that machine-parseable output.
emit_tauri_port = False,
- # We read the bound port back below, so a fallback past another Unsloth is
- # safe here and keeps side-by-side model runs working.
abort_if_own_studio = False,
)
- # Forward the frontend validated before the gate (in-venv path).
if resolved_frontend is not None:
run_kwargs["frontend_path"] = resolved_frontend
with _studio_runtime_launch_guard(inherited = runtime_gate_handoff):
app = run_server(**run_kwargs)
actual_port = getattr(app.state, "server_port", port) or port
- # Steps 3-5 can abort (health timeout, model-load error, or Ctrl+C during the
- # slow load); tear the server and its children (llama-server, cloudflared) down
- # on any abort so they never orphan.
from studio.backend.run import _graceful_shutdown, _server
try:
@@ -3095,21 +2486,16 @@ def run(
if not isinstance(request_host, str) or not request_host:
typer.echo("Error: server did not expose its bound address.", err = True)
raise typer.Exit(1)
- # 3. Wait for server health.
if not silent:
typer.echo("Starting Unsloth Studio...")
if not _wait_for_server(actual_port, request_host = request_host):
typer.echo("Error: server did not become healthy within 30 seconds.", err = True)
raise typer.Exit(1)
- # 4. Create API key in-process.
api_key = _create_api_key_inprocess(api_key_name)
if start_api_key_marker:
- # `unsloth start` reads this key from a private 0600 log to authenticate
- # download-progress polling; the normal `unsloth run` output is unchanged.
typer.echo(f"UNSLOTH_START_API_KEY: {api_key}")
- # 5. Load model via HTTP.
if not silent:
typer.echo(f"Loading model: {model}...")
try:
@@ -3139,20 +2525,14 @@ def run(
display_variant = f" ({gguf_variant})" if gguf_variant else ""
context_length_line = _format_context_length_line(result)
- # 6. Print banner.
- # Keep the public host for reachability, but print a LAN or loopback URL.
display_host = _display_host_for_bind(run_mod, host)
base_host = _openable_host_for_bind(run_mod, host)
base_url = f"http://{_url_host(base_host)}:{actual_port}"
sdk_base_url = f"{base_url}/v1"
- # run_server started the tunnel during the silent run above (wildcard or --secure).
_cf_url = getattr(app.state, "cloudflare_url", None)
- # --secure: examples must use the public tunnel URL, not the loopback address.
if secure and _cf_url:
sdk_base_url = f"{_cf_url}/v1"
- # Orange so the tool-policy notice stands out; printed under
- # --silent / --yes too so the policy is never invisible.
_tool_notice_fg = (217, 119, 87)
_is_external = is_external_host(host)
if enable_tools is False:
@@ -3216,7 +2596,6 @@ def run(
typer.echo(""" -d '{"input": "Hello", "stream": true}'""")
typer.echo("")
else:
- # Silent still prints URL + API key + tool-status policy.
if secure and _cf_url:
typer.echo(f"URL: {_cf_url}")
typer.echo(f"Local: {base_url}")
@@ -3228,7 +2607,6 @@ def run(
typer.echo(f"API Key: {api_key}")
typer.secho(_tool_notice, fg = _tool_notice_fg, bold = True)
- # 7. Wait for Ctrl+C.
try:
if run_mod._shutdown_event is not None:
while not run_mod._shutdown_event.is_set():
@@ -3243,18 +2621,13 @@ def run(
getattr(run_mod, "_wait_for_server_shutdown", lambda: None)()
-# ── unsloth studio stop ───────────────────────────────────────────────
-
_PID_FILE = STUDIO_HOME / "studio.pid"
PID_FILE_GLOB = "studio-*.pid"
def _pid_alive(pid: int) -> bool:
- """Return True if a process with ``pid`` exists.
-
- ``os.kill(pid, 0)`` raises OSError (WinError 87) for every pid on Windows,
- so use ``tasklist`` there and the signal-0 probe elsewhere.
- """
+ """Return True if a process with ``pid`` exists. os.kill(pid, 0) raises WinError 87 for
+ every pid on Windows, so use tasklist there."""
if sys.platform == "win32":
try:
out = subprocess.run(
@@ -3266,7 +2639,7 @@ def _pid_alive(pid: int) -> bool:
timeout = 10,
).stdout
except Exception:
- # Can't determine -- assume alive; taskkill no-ops if already gone.
+ # Cannot determine; assume alive, taskkill no-ops if already gone.
return True
return f'"{int(pid)}"' in out
try:
@@ -3279,7 +2652,6 @@ def _pid_alive(pid: int) -> bool:
def _parse_pid_record(text: str) -> "tuple[int, float | None] | None":
- """Parse ``pid`` / optional ``create_time`` from PID file contents."""
lines = text.splitlines()
if not lines or not lines[0].strip().isdigit():
return None
@@ -3301,7 +2673,6 @@ def _parse_pid_record(text: str) -> "tuple[int, float | None] | None":
def _read_pid_record(path: Path) -> "tuple[int, float | None] | None":
- """Parse ``pid`` / optional ``create_time`` from a PID file."""
try:
text = path.read_text(encoding = "utf-8")
except (OSError, UnicodeDecodeError):
@@ -3310,11 +2681,8 @@ def _read_pid_record(path: Path) -> "tuple[int, float | None] | None":
def _unlink_quietly(path: Path) -> None:
- """Drop a record without letting one bad file end the loop.
-
- An undeletable record must not stop us reaching the other servers -- that is
- the orphan this command exists to prevent.
- """
+ """Drop a record without letting one bad file end the loop: an undeletable record must
+ not stop us reaching the other servers."""
try:
path.unlink(missing_ok = True)
except OSError as e:
@@ -3322,7 +2690,6 @@ def _unlink_quietly(path: Path) -> None:
def _report_unreadable(paths: "list[Path]") -> None:
- """Say which servers we could not reach, since `stop` is about to exit 1."""
names = ", ".join(sorted(p.name for p in paths))
typer.echo(
f"Could not read {len(paths)} PID file(s): {names}. A server recorded "
@@ -3335,17 +2702,9 @@ def _report_unreadable(paths: "list[Path]") -> None:
def _pid_file_entries(
unreadable: "list[Path] | None" = None,
) -> "list[tuple[int, list[float | None], list[Path]]]":
- """(pid, create_times, files) per recorded server, including the legacy studio.pid.
-
- Paths that could not be read are appended to `unreadable` when given, so the
- caller can tell "nothing is running" apart from "something is running and we
- could not see it".
-
- Grouped by PID: a server writes both its per-port file and studio.pid, and
- signalling twice would hit the SIG_DFL the first SIGTERM installs, hard-killing
- it mid-shutdown. Every recorded time is kept -- a stale file and a live server
- can share a PID, and the stale one must not veto the live one.
- """
+ """(pid, create_times, files) per recorded server, including the legacy studio.pid. Grouped by
+ PID: a second SIGTERM would hard-kill a server mid-shutdown. Every recorded time is kept, so a
+ stale file cannot veto a live server."""
by_pid: "dict[int, tuple[list[float | None], list[Path]]]" = {}
try:
paths = sorted(STUDIO_HOME.glob(PID_FILE_GLOB)) + [_PID_FILE]
@@ -3359,9 +2718,7 @@ def _pid_file_entries(
try:
text = path.read_text(encoding = "utf-8")
except (OSError, UnicodeDecodeError) as e:
- # Unreadable is not the same as invalid. A root-owned record, or one
- # caught mid-write, still belongs to a live server, and deleting it
- # strands that server -- the bug this command exists to fix.
+ # Unreadable is not invalid: a root-owned or mid-write record still belongs to a live server.
typer.echo(f"Cannot read PID file {path.name}: {e}", err = True)
if unreadable is not None:
unreadable.append(path)
@@ -3379,20 +2736,8 @@ def _pid_file_entries(
def _pid_is_studio_server(pid: int, created_times: "Sequence[float | None]" = ()) -> bool:
- """False only when a recorded start time proves this PID is a different process.
-
- Any recorded time matching is enough -- a stale record must not veto a live
- server that reused the PID. Records with no time at all (a legacy studio.pid,
- or a server started without psutil) cannot be checked, so they are trusted:
- the old `stop` signalled with no checks at all, and skipping a live server is
- the orphan bug this exists to fix.
-
- An untimed record sitting *alongside* a timed one carries no information, so
- it must not cancel the timed one either. Every current server writes both a
- timed per-port record and an untimed studio.pid, so letting the untimed half
- win made this check inert exactly where it matters and let `stop` SIGTERM an
- unrelated process that had inherited the PID.
- """
+ """False only when a recorded start time proves this PID is a different process. Untimed records
+ are trusted and must not cancel a timed one: every server writes both."""
known = [c for c in created_times if c is not None]
if not known:
return True
@@ -3405,7 +2750,6 @@ def _pid_is_studio_server(pid: int, created_times: "Sequence[float | None]" = ()
def _signal_stop(pid: int) -> "str | None":
- """SIGTERM (or taskkill) the pid. Returns an error string, or None on success."""
import signal as _signal
if pid < 2:
@@ -3425,16 +2769,13 @@ def _signal_stop(pid: int) -> "str | None":
@studio_app.command()
def stop():
- """Stop every running Unsloth Studio server for this STUDIO_HOME.
-
- The port fallback can leave more than one running, so stop them all.
- """
+ """Stop every running Unsloth Studio server for this STUDIO_HOME. The port fallback can leave
+ more than one running."""
unreadable: "list[Path]" = []
entries = _pid_file_entries(unreadable)
if not entries:
if unreadable:
- # Reporting success here would be a lie: the records we could not
- # read are kept, and the servers behind them are still serving.
+ # Reporting success would be a lie: the servers behind the unreadable records are still serving.
_report_unreadable(unreadable)
raise typer.Exit(1)
typer.echo("No running Unsloth server found (no PID file).")
@@ -3484,12 +2825,7 @@ def stop():
raise typer.Exit(1)
-# ── unsloth studio setup / update ─────────────────────────────────────
-
-
def _wait_for_windows_setup_process(process) -> int:
- """Reap setup and its descendants before a runtime-gate owner can unwind."""
-
try:
return process.wait()
except BaseException:
@@ -3505,8 +2841,7 @@ def _wait_for_windows_setup_process(process) -> int:
**_windows_hidden_subprocess_kwargs(),
)
except BaseException:
- # taskkill interrupted or unavailable: hold the gate until setup
- # exits naturally rather than exposing a live mutator.
+ # taskkill interrupted or unavailable: hold the gate until setup exits naturally.
pass
while process.poll() is None:
try:
@@ -3516,56 +2851,36 @@ def _wait_for_windows_setup_process(process) -> int:
raise
-# -NoProfile below drops $PSDefaultParameterValues wholesale, and on a corporate host a profile
-# entry such as 'Invoke-WebRequest:Proxy' may be the only route to the VC++ runtime and the uv
-# installer setup.ps1 downloads. install.ps1 hands over the keys it kept; a standalone update
-# has no installer above it, so the probe below asks a short-lived PowerShell that DOES load
-# the profile.
-
-# Markers unlikely in a banner, and fixed so both sides agree.
+# -NoProfile drops $PSDefaultParameterValues, which may hold the only proxy out of a corporate host; a standalone update has no installer to hand it over.
_PROXY_PROBE_BEGIN = "<<UNSLOTH_PROXY_DEFAULTS>>"
_PROXY_PROBE_END = "<</UNSLOTH_PROXY_DEFAULTS>>"
_PS_PROXY_PROBE = (
"$ErrorActionPreference = 'SilentlyContinue'; "
- # Windows PowerShell 5.1 writes REDIRECTED output in the console code page while this
- # process decodes UTF-8, so a non-ASCII proxy value came back with replacement characters,
- # still parsed as JSON, and handed setup a proxy that does not work.
+ # PowerShell 5.1 writes redirected output in the console code page, so a non-ASCII proxy value came back mangled but still parsed as JSON.
"try { [Console]::OutputEncoding = "
"New-Object System.Text.UTF8Encoding $false } catch { }; "
"try { $OutputEncoding = [Console]::OutputEncoding } catch { }; "
"$PSModuleAutoLoadingPreference = 'All'; "
- # Launched -NoProfile, with the caller's profiles dot-sourced by name instead, because left
- # to itself this process loads the CONSOLEHOST profile -- an unrelated host's for a caller
- # in the VS Code console. $PROFILE is fully populated under -NoProfile (the paths are
- # computed, not loaded), so naming them is exact.
+ # Dot-sourced by name, or this process loads the CONSOLEHOST profile. $PROFILE is populated under -NoProfile.
"$__unslothHostProfileName = $env:_UNSLOTH_PS_HOST_PROFILE; "
- # All-users first, PowerShell's own startup order: a machine-managed proxy lives in
- # AllUsersAllHosts on a domain-joined box, and the user's profile only overrides it by
- # running last.
+ # All-users first, PowerShell's own startup order, so a user profile overrides it by running last.
"try { $__unslothProfiles = @($PROFILE.AllUsersAllHosts); "
- # ONLY the caller's host profile, and only when the caller could be identified: sourcing
- # every Microsoft.*_profile.ps1 in the directory ran profiles for hosts nobody was using,
- # which can print, clobber $PSDefaultParameterValues, or exit before the record is written.
+ # ONLY the caller's host profile: other hosts' profiles can print, clobber the table, or exit.
"if ($__unslothHostProfileName) { "
"$__unslothProfiles += (Join-Path (Split-Path -Parent $PROFILE.AllUsersCurrentHost) "
"$__unslothHostProfileName) }; "
"$__unslothProfiles += $PROFILE.AllUsersCurrentHost; "
"$__unslothProfiles += $PROFILE.CurrentUserAllHosts; "
- # ADDED, never substituted: TERM_PROGRAM=vscode is set by every VS Code integrated terminal,
- # not only the PowerShell extension's own host, so a plain pwsh terminal there loads
- # Microsoft.PowerShell_profile.ps1 and substitution missed the proxy it actually has.
+ # ADDED, never substituted: TERM_PROGRAM=vscode is set by every VS Code terminal, so substitution missed a plain pwsh terminal's proxy.
"if ($__unslothHostProfileName) { "
"$__unslothProfiles += (Join-Path (Split-Path -Parent $PROFILE.CurrentUserCurrentHost) "
"$__unslothHostProfileName) }; "
- # Current-host profile LAST.
"$__unslothProfiles += $PROFILE.CurrentUserCurrentHost; "
"foreach ($__unslothProfile in ($__unslothProfiles | Select-Object -Unique)) { "
"if ($__unslothProfile -and (Test-Path -LiteralPath $__unslothProfile -PathType Leaf)) { "
"try { . $__unslothProfile } catch { } } } } catch { }; "
- # Re-pinned, because setting [Console]::OutputEncoding is an ordinary profile customization
- # that overrides the pin above. The parent decodes this stream as UTF-8, so a console left
- # on a legacy code page corrupts the framed record and the proxy URI with it.
+ # Re-pinned: a profile may set [Console]::OutputEncoding, and the parent decodes UTF-8.
"try { [Console]::OutputEncoding = "
"New-Object System.Text.UTF8Encoding $false } catch { }; "
"try { $OutputEncoding = [Console]::OutputEncoding } catch { }; "
@@ -3576,19 +2891,13 @@ _PS_PROXY_PROBE = (
"$v = $PSDefaultParameterValues[$k]; "
"if ($v -is [uri]) { $out[$k] = $v.AbsoluteUri } "
"elseif ($v -is [string] -or $v -is [bool]) { $out[$k] = $v } "
- # A script block is the supported form for a DYNAMIC default -- e.g.
- # { [uri]$env:CORP_PROXY } -- evaluated per call by Invoke-WebRequest. Evaluate here and
- # serialize the RESULT: executable code must not cross the handoff.
+ # A script block is the supported DYNAMIC default; serialize the RESULT, since executable code must not cross the handoff.
"elseif ($v -is [scriptblock]) { try { $r = & $v; "
"if ($r -is [uri]) { $out[$k] = $r.AbsoluteUri } "
"elseif ($r -is [string] -or $r -is [bool]) { $out[$k] = $r } } catch { } } } }; "
- # $out already holds copies, so the profile's table is now only a hazard:
- # ConvertTo-Json:AsArray = $true is a legitimate setting that turns this record into a JSON
- # array, which the reader rejects for not being a dictionary.
+ # $out holds copies, and ConvertTo-Json:AsArray = $true would make this record an array.
"$PSDefaultParameterValues = @{}; "
- # FRAMED, not bare: the profile is free to print a banner or a MOTD, and that output
- # arriving ahead of the JSON made the parse throw. Module-qualified, as with the uv lookup:
- # an alias named ConvertTo-Json or Write-Output would otherwise reshape the frame.
+ # FRAMED and module-qualified: a profile banner made the parse throw, and an alias could reshape the frame.
f"if ($out.Count -gt 0) {{ "
f"Microsoft.PowerShell.Utility\\Write-Output '{_PROXY_PROBE_BEGIN}'; "
f"$out | Microsoft.PowerShell.Utility\\ConvertTo-Json -Compress; "
@@ -3596,8 +2905,7 @@ _PS_PROXY_PROBE = (
)
-# What the CALLER's host names its own CurrentUserCurrentHost profile, when we can tell. An
-# unidentifiable host gets no extra profile rather than someone else's.
+# What the CALLER's host names its own profile; an unidentifiable host gets none.
_HOST_PROFILE_BY_TERM_PROGRAM = {"vscode": "Microsoft.VSCode_profile.ps1"}
@@ -3606,24 +2914,17 @@ def _caller_host_profile_name() -> Optional[str]:
return _HOST_PROFILE_BY_TERM_PROGRAM.get(term_program)
-# Windows PowerShell's own module directory, under %SystemRoot%.
_WINDOWS_PS_MODULE_DIR = r"System32\WindowsPowerShell\v1.0\Modules"
_WINDOWS_PS_HOSTS = frozenset({"powershell.exe", "powershell", "powershell_ise.exe"})
def _fold_module_entry(entry: str) -> str:
- """A PSModulePath entry reduced to a comparable form (separator and case insensitive)."""
return entry.replace("/", "\\").rstrip("\\").casefold()
def _windows_powershell_module_path(current: str) -> Optional[str]:
- """``current`` with Windows PowerShell's own module directory first, or None to leave it be.
-
- PowerShell 7 strips its module paths only when IT launches powershell.exe, so reached through
- this Python process the child keeps them in FRONT and resolves 5.1's own modules to the
- PowerShell 7 copies. A profile that imports one then throws while it is dot-sourced and the
- proxy it was going to publish is lost. Same repair as install.ps1, applied per probed host:
- pwsh needs none, because PowerShell 7 prefixes its own paths on startup."""
+ """``current`` with Windows PowerShell's own module directory first, or None to leave it be: a
+ 5.1 child started from Python would otherwise resolve its modules to the PowerShell 7 copies."""
root = os.environ.get("SystemRoot")
if not root:
return None
@@ -3647,8 +2948,7 @@ def _profile_probe_env(host: str = "") -> dict:
if platform.system() == "Windows" and _fold_module_entry(host).rsplit("\\", 1)[-1] in (
_WINDOWS_PS_HOSTS
):
- # os.environ upper-cases keys on Windows, so the copy is keyed PSMODULEPATH: reading
- # "PSModulePath" misses the caller's value and adds a second, case-differing entry.
+ # os.environ upper-cases keys on Windows, so read PSMODULEPATH or a second, case-differing entry appears.
key = next((k for k in env if k.upper() == "PSMODULEPATH"), "PSModulePath")
reordered = _windows_powershell_module_path(env.get(key, ""))
if reordered:
@@ -3657,7 +2957,6 @@ def _profile_probe_env(host: str = "") -> dict:
def _framed_probe_record(stdout: str) -> Optional[str]:
- """The JSON between the markers, or None. Tolerates anything the profile printed."""
start = stdout.find(_PROXY_PROBE_BEGIN)
if start < 0:
return None
@@ -3669,17 +2968,8 @@ def _framed_probe_record(stdout: str) -> Optional[str]:
def _profile_probe_hosts() -> list[str]:
- r"""The PowerShell hosts whose profile to ask, most likely caller first.
-
- The two editions keep SEPARATE profiles, so both are asked and the caller's edition goes
- first, its value winning on merge.
-
- The caller is inferred from PSModulePath, which every host exports: Windows PowerShell's
- points at ``...\WindowsPowerShell\v1.0\Modules`` and pwsh's at ``...\PowerShell\7\Modules``.
- By ORDER, not by absence, since a machine can have both trees on PSModulePath at once and
- each host puts its OWN module directory first. Neither present, or both at the same
- position: keep the default order rather than guess.
- """
+ r"""The PowerShell hosts whose profile to ask, caller first. Inferred from PSModulePath by
+ ORDER, not absence, since both trees can be present; ambiguous keeps the default order."""
hosts = ["pwsh.exe", "powershell.exe"]
module_path = os.environ.get("PSModulePath", "").lower()
windows_at = module_path.find("windowspowershell")
@@ -3689,34 +2979,18 @@ def _profile_probe_hosts() -> list[str]:
return [host for host in hosts if shutil.which(host)]
-# Annotations below are quoted: this module has no `from __future__ import annotations`, and on
-# Python 3.9 evaluating `str | list[str]` at def time raises TypeError, taking the CLI import
-# with it.
+# Quoted annotations: Python 3.9 evaluates `str | list[str]` at def time and raises TypeError.
-# The whole profile probe's budget, shared across however many hosts are tried.
_PROFILE_PROBE_TIMEOUT_SECONDS = 20.0
def _probe_profile_proxy_defaults(powershell: "str | list[str]") -> Optional[str]:
- """The caller's profile proxy defaults as JSON, or None.
-
- install.ps1 hands these over in the environment, but a standalone `unsloth studio update`
- has no installer above it and a PowerShell variable does not reach this Python process. So
- ask for it, in a throwaway process whose only job is to print the table.
-
- Several hosts may be given: their answers are MERGED, earlier hosts winning per key.
-
- Best effort. A slow, interactive or broken profile costs one timeout and the child proceeds
- as it does today."""
+ """The caller's profile proxy defaults as JSON, or None. Several hosts MERGE, earlier hosts
+ winning per key. Best effort: a broken profile costs one timeout."""
hosts = [powershell] if isinstance(powershell, str) else list(powershell)
- # ONE budget for the whole probe, not one per host: with both editions installed, two hung
- # profiles would otherwise stall every standalone update for twice the stated cost.
+ # ONE budget for the whole probe: two hung profiles must not double the stated cost.
deadline = time.monotonic() + _PROFILE_PROBE_TIMEOUT_SECONDS
merged: dict = {}
- # $PSDefaultParameterValues keys are case-INSENSITIVE, so "Invoke-WebRequest:Proxy" and
- # "invoke-webrequest:proxy" are one entry to PowerShell and two to a Python dict. Only the
- # first spelling seen is handed on, or the prelude would replay both and let the
- # lower-priority host's land last.
claimed: dict = {}
seen_keys: set = set()
for host in hosts:
@@ -3737,10 +3011,7 @@ def _probe_profile_proxy_defaults(powershell: "str | list[str]") -> Optional[str
env = _profile_probe_env(host),
capture_output = True,
text = True,
- # text=True alone decodes with the locale codec and STRICT errors, so a UTF-8
- # profile banner on an ANSI console raised UnicodeDecodeError -- neither
- # OSError nor SubprocessError, so it escaped the handler below and took the
- # update down.
+ # text=True decodes with the locale codec and STRICT errors, and that UnicodeDecodeError is neither OSError nor SubprocessError.
encoding = "utf-8",
errors = "replace",
timeout = remaining,
@@ -3752,16 +3023,12 @@ def _probe_profile_proxy_defaults(powershell: "str | list[str]") -> Optional[str
if not payload:
continue
try:
- # Validated, not trusted: the framing finds the record, this confirms it is one, so
- # nothing hands the child a string ConvertFrom-Json throws on.
parsed = json.loads(payload)
except ValueError:
continue
if not isinstance(parsed, dict) or not parsed:
continue
- # Per CMDLET, not per key: pairing the earlier host's Proxy with the later host's
- # ProxyUseDefaultCredentials would offer the user's Windows credentials to a proxy whose
- # own profile never asked for that. A cmdlet is claimed whole by the first host.
+ # Per CMDLET, not per key: pairing one host's Proxy with another's ProxyUseDefaultCredentials would offer Windows credentials to a proxy that never asked.
for key, value in parsed.items():
if not isinstance(key, str):
continue
@@ -3781,12 +3048,7 @@ def _probe_profile_proxy_defaults(powershell: "str | list[str]") -> Optional[str
def _cmdlet_claimed_elsewhere(cmdlet: str, claimed: dict, source: object) -> bool:
- """Whether another host already owns the cmdlet family ``cmdlet`` belongs to.
-
- A literal comparison is not enough: the command half of a $PSDefaultParameterValues key may
- be a wildcard, and PowerShell applies such an entry to every cmdlet it matches. Overlap in
- either direction claims the family.
- """
+ """Whether another host already owns the cmdlet family ``cmdlet`` belongs to. The command"""
for owned, owner in claimed.items():
if owner is source:
continue
@@ -3797,21 +3059,14 @@ def _cmdlet_claimed_elsewhere(cmdlet: str, claimed: dict, source: object) -> boo
@functools.lru_cache(maxsize = 512)
def _patterns_can_overlap(left: str, right: str) -> bool:
- """Whether any command name matches BOTH wildcard patterns.
-
- Two patterns can share matches without either matching the other as a STRING (Invoke-Web* and
- *-WebRequest both apply to Invoke-WebRequest), so the languages are intersected rather than
- string-matched -- otherwise a host's Start-Bits* entry swallowed the other host's unrelated
- Invoke-Web* one. A character class is not decided, only assumed to overlap: that is the
- conservative answer, and no cmdlet name is written that way.
- """
+ """Whether any command name matches BOTH wildcard patterns: two can share matches without
+ matching each other as strings, so the languages are intersected."""
if "[" in left or "[" in right:
return True
@functools.lru_cache(maxsize = None)
def walk(i: int, j: int) -> bool:
- # Both patterns are consumed in step, except at a '*', which may absorb one more
- # character from the other side or match nothing at all.
+ # Both patterns are consumed in step, except at '*', which may absorb one more character or none.
if i == len(left):
return all(char == "*" for char in right[j:])
if j == len(right):
@@ -3830,10 +3085,7 @@ def _patterns_can_overlap(left: str, right: str) -> bool:
_PS_PROXY_DEFAULTS_PRELUDE = (
"$__unslothProxyDefaults = $env:_UNSLOTH_PS_PROXY_DEFAULTS; "
- # Read once, then GONE from the environment: a profile proxy can carry credentials
- # (http://user:secret@proxy is the ordinary corporate form) and every native process setup
- # starts would otherwise inherit it. Needed only by this session's
- # $PSDefaultParameterValues, which is not inherited.
+ # Read once, then GONE: a profile proxy can carry credentials every native process would inherit.
"Remove-Item Env:_UNSLOTH_PS_PROXY_DEFAULTS -ErrorAction SilentlyContinue; "
"if ($__unslothProxyDefaults) { try { "
"(ConvertFrom-Json $__unslothProxyDefaults).PSObject.Properties | ForEach-Object { "
@@ -3846,8 +3098,8 @@ _UV_CACHE_METADATA_SUFFIXES = (".lock", ".msgpack", ".http", ".rev")
def _uv_cache_has_packages(cache_dir: Path) -> bool:
- """wheels-* is metadata only on uv 0.10, so counting any file reads a cache that was
- merely resolved against as warm. Same rule as install.sh:_configure_uv_cache."""
+ """wheels-* is metadata only on uv 0.10, so counting any file reads a merely-resolved cache
+ as warm. Same rule as install.sh:_configure_uv_cache."""
try:
buckets = [
entry
@@ -3855,8 +3107,6 @@ def _uv_cache_has_packages(cache_dir: Path) -> bool:
if entry.name.startswith(_UV_CACHE_BUCKETS) and entry.is_dir()
]
except (OSError, ValueError):
- # ValueError too: an embedded NUL builds a Path fine and then raises out of
- # scandir, aborting an update over a file that is only advisory.
return False
for bucket in buckets:
for _root, _dirs, files in os.walk(bucket):
@@ -3870,7 +3120,6 @@ def _uv_cache_has_packages(cache_dir: Path) -> bool:
def _uv_platform_cache_dir() -> Optional[Path]:
- """install.sh:646's fallback, for when uv cannot be asked: that is not "no cache"."""
if platform.system() == "Windows":
local_app_data = (os.environ.get("LOCALAPPDATA") or "").strip()
return Path(local_app_data) / "uv" / "cache" if local_app_data else None
@@ -3881,26 +3130,19 @@ def _uv_platform_cache_dir() -> Optional[Path]:
return Path(home) / ".cache" / "uv" if home else None
-# uv's boolish spelling. Anything outside it is a value uv refuses to run on, which is
-# not "no cache" either.
+# uv's boolish spelling. Anything outside it is a value uv refuses to run on.
_UV_TRUE = ("1", "true", "yes", "on")
def _uv_no_cache_requested() -> bool:
- """uv --no-cache caches in a temporary directory and discards it on exit, so the
- probe would report that throwaway, --no-cache outranks --cache-dir anyway, and
- recording it would aim later updates at a cache that never existed."""
+ """uv --no-cache caches in a temporary directory and discards it, outranks --cache-dir,
+ and recording it would aim later updates at a cache that never existed."""
return (os.environ.get("UV_NO_CACHE") or "").strip().lower() in _UV_TRUE
def _uv_default_cache_dir(cwd: Optional[Path] = None) -> Optional[Path]:
- """Asked of uv, not reconstructed, so uv.toml and UV_CONFIG_FILE count.
-
- Asked from where setup will ask it, too. Both setup scripts change into their own
- directory before the dependency pass (studio/setup.sh:1788), and uv discovers
- uv.toml and pyproject.toml from its working directory, so probing in the caller's
- would answer for whatever project the user happens to be standing in.
- """
+ """Asked of uv, not reconstructed, so uv.toml and UV_CONFIG_FILE count, and asked from where
+ setup will ask it, since uv discovers uv.toml from its working directory."""
uv = shutil.which("uv")
if not uv:
return _uv_platform_cache_dir()
@@ -3911,27 +3153,21 @@ def _uv_default_cache_dir(cwd: Optional[Path] = None) -> Optional[Path]:
cwd = str(cwd) if cwd is not None else None,
capture_output = True,
text = True,
- # UnicodeDecodeError is a ValueError, so the handler below would not catch it.
encoding = "utf-8",
errors = "replace",
env = child_env,
timeout = 30,
- # Creation flags are not inherited from a hidden desktop update.
**_windows_hidden_subprocess_kwargs(),
)
except Exception:
- # Best effort: not knowing costs a preference, never the update.
return _uv_platform_cache_dir()
if result.returncode != 0:
# A malformed uv.toml beside the CALLER fails this, though setup.sh runs uv elsewhere.
return _uv_platform_cache_dir()
- # Not stripped: a name may end in a space, and uv reports it verbatim.
lines = [line for line in (result.stdout or "").splitlines() if line.strip()]
if not lines:
return _uv_platform_cache_dir()
- # uv answers a relative cache-dir with the relative spelling, against its own working
- # directory, and resolves a relative UV_WORKING_DIR after starting where this probe
- # did. No expanduser: uv makes a literal "~" directory, not one in $HOME.
+ # uv answers a relative cache-dir against its own working directory. No expanduser: uv makes a literal "~" directory.
probe_cwd = str(cwd) if cwd is not None else os.getcwd()
working = os.environ.get("UV_WORKING_DIR")
base = os.path.join(probe_cwd, working) if working else probe_cwd
@@ -3939,45 +3175,30 @@ def _uv_default_cache_dir(cwd: Optional[Path] = None) -> Optional[Path]:
def _recorded_install_uv_cache() -> Optional[Path]:
- """The cache the installer used, as it recorded it.
-
- Content cannot tell a Studio cache the installer filled from one holding a single
- wheel the running backend dropped there (wheel_utils.py:405), since install.sh:705
- points it there even in shared mode. Absent, the caller falls back to content.
- """
+ """The cache the installer used, as it recorded it. Content cannot tell a Studio cache the
+ installer filled from one holding a single wheel the backend dropped there."""
try:
- # utf-8-sig: Windows PowerShell 5.1 writes `-Encoding utf8` WITH a BOM.
- # surrogateescape: a POSIX path may not be UTF-8, and U+FFFD would name nothing.
recorded = (STUDIO_HOME / "cache" / "uv-cache-dir").read_text(
encoding = "utf-8-sig", errors = "surrogateescape"
)
except OSError:
return None
- # One record, one trailing delimiter, everything before it the path: splitting on
- # lines would take a POSIX path containing a newline for several. Not otherwise
- # stripped, since a path may end or begin with a space; blank means unset.
+ # One record, one trailing delimiter, path before it: splitting on lines would break a path containing a newline.
if recorded.endswith("\n"):
recorded = recorded[:-1]
if recorded.endswith("\r"):
recorded = recorded[:-1]
if not recorded.strip():
return None
- # No expanduser, as in the probe: uv treats a tilde as an ordinary path segment.
return Path(os.path.abspath(recorded))
def _backfill_uv_cache_marker(env: Optional[dict]) -> None:
- """Record the cache this update used, for installs whose installer never did.
-
- Those reach the content fallback, which goes stale the moment the backend drops one
- wheel into the Studio cache and both caches look warm. Writing the choice down once
- setup has succeeded closes that, and likewise for a marker whose cache was emptied.
- """
+ """Record the cache this update used, for installs whose installer never did; otherwise they
+ stay on the content fallback, which goes stale once the backend drops a wheel in."""
if (os.environ.get("UV_CACHE_DIR") or "").strip():
- # One run's value. Only an installer's own choice becomes a marker.
return
if _uv_no_cache_requested():
- # Setup cached nothing that outlived it, so there is no choice to record.
return
chosen = (env or {}).get("UV_CACHE_DIR")
if not chosen:
@@ -3987,21 +3208,16 @@ def _backfill_uv_cache_marker(env: Optional[dict]) -> None:
return
stage_root = (os.environ.get(_studio_stage.STAGE_ROOT_ENV) or "").strip()
if stage_root:
- # STUDIO_HOME names the LIVE install here and the stage can still be rejected,
- # so the choice is parked and _studio_stage.stage promotes it on acceptance.
- # Dropping it instead left desktop-only installs on the content fallback.
+ # A 805-807 desktop shell ran the OLD CLI with --stage and it is running this setup inside its stage, so park the choice for its stage() to promote.
marker = Path(stage_root) / _studio_stage.UV_CACHE_MARKER
else:
marker = STUDIO_HOME / "cache" / "uv-cache-dir"
try:
marker.parent.mkdir(parents = True, exist_ok = True)
- # Unlinked first: a write follows a symlink and truncates its target.
marker.unlink(missing_ok = True)
- # fsencode: an undecodable path arrives as surrogates, and encoding those
- # raises UnicodeEncodeError, which is not an OSError.
+ # fsencode: an undecodable path arrives as surrogates and raises UnicodeEncodeError, not OSError.
marker.write_bytes(os.fsencode(f"{chosen}\n"))
except (OSError, ValueError):
- # ValueError covers UnicodeError, for a path fsencode still cannot render.
pass
@@ -4011,27 +3227,20 @@ def _with_studio_uv_cache(env: Optional[dict], cwd: Optional[Path] = None) -> Op
if (os.environ.get("UV_CACHE_DIR") or "").strip():
return env
if _uv_no_cache_requested():
- # --no-cache outranks --cache-dir, so naming one changes nothing.
return env
studio_cache = STUDIO_HOME / "cache" / "uv"
recorded = _recorded_install_uv_cache()
if recorded is not None and _uv_cache_has_packages(recorded):
# Only while it holds something: a marker for an emptied cache loses to a warm one.
return {**(env or os.environ), "UV_CACHE_DIR": str(recorded)}
- # No marker, so this install predates it and content is all there is, and content
- # cannot settle it: install.sh:705 points the running backend at the Studio cache even
- # in shared mode, so one on-demand wheel warms it. uv's default is what such an install
- # has been updating from all along, and it cannot record its way out of a wrong guess.
+ # No marker, and content cannot settle it: one on-demand wheel warms the Studio cache even in shared mode, so use uv's default.
default_cache = _uv_default_cache_dir(cwd)
if default_cache is not None and _uv_cache_has_packages(default_cache):
- # Named, not re-resolved: a blank inherited value reaches uv as
- # `--cache-dir ''` and exits 2.
return {**(env or os.environ), "UV_CACHE_DIR": str(default_cache)}
return {**(env or os.environ), "UV_CACHE_DIR": str(studio_cache)}
def _run_setup_script(*, verbose: bool = False, repo_root: Optional[Path] = None) -> None:
- """Find and run the studio setup/update script."""
script = _find_setup_script(repo_root)
if not script:
if repo_root is not None:
@@ -4044,37 +3253,25 @@ def _run_setup_script(*, verbose: bool = False, repo_root: Optional[Path] = None
raise typer.Exit(1)
env = {**os.environ, "UNSLOTH_VERBOSE": "1"} if verbose else None
- # Where setup will run uv from, which differs by platform: setup.sh changes into its
- # own directory (setup.sh:1788), setup.ps1 never does and hands install_python_stack.py
- # the cwd it inherited from here (setup.ps1:5191).
+ # Where setup runs uv from: setup.sh cds into its own directory, setup.ps1 keeps this cwd.
setup_cwd = None if platform.system() == "Windows" else script.parent
env = _with_studio_uv_cache(env, cwd = setup_cwd)
if platform.system() == "Windows":
- # Resolved, not bare: the gate that runs immediately before this in setup() and update()
- # had to stop trusting PATH for exactly this reason (#9440), and the Popen below has no
- # OSError handler, so a bare name here just moves the same WinError 2 one frame later.
+ # Resolved, not bare: PATH is not trusted here (#9440) and the Popen below has no OSError handler.
powershell = _studio_runtime_gate.resolve_windows_powershell()
powershell_args = [powershell]
- # PRESENCE, not truthiness: install.ps1 publishes this around the handoff and sets it to
- # "{}" when it found no proxy, so treating that as "nobody handed anything over" would
- # send an installer launch off to reload the profiles it deliberately discarded.
+ # PRESENCE, not truthiness: install.ps1 sets this to "{}" when it found no proxy, and reloading the profiles it discarded would undo that.
if os.environ.get("_UNSLOTH_PS_PROXY_DEFAULTS") is None:
probed = _probe_profile_proxy_defaults(_profile_probe_hosts() or [powershell])
if probed:
env = {**(env or os.environ), "_UNSLOTH_PS_PROXY_DEFAULTS": probed}
- # -NoProfile unconditionally, not just on the hidden branch: install.ps1 hands off to
- # exactly here from a console where stdout is a tty, so the hidden branch does not fire
- # and a profile that aliases uv or python would break setup.ps1.
+ # -NoProfile unconditionally: install.ps1 hands off from a tty console, and a profile aliasing uv or python would break setup.ps1.
powershell_args.append("-NoProfile")
if _should_hide_windows_subprocesses():
- # Match install.rs: avoid the Hidden/Bypass detection pair.
- # CREATE_NO_WINDOW below already hides the console.
+ # Match install.rs: avoid the Hidden/Bypass detection pair; CREATE_NO_WINDOW below already hides the console.
powershell_args.extend(["-NoLogo", "-NonInteractive"])
- # Use -Command + `*>&1` (not -File) so setup.ps1's Write-Host output
- # (Information stream #6) merges into stdout. -File drops it when
- # stdout is a pipe, e.g. `unsloth studio update --local 2>&1 | tee`.
- # Single-quote escaping handles paths containing apostrophes.
+ # -Command + `*>&1` (not -File) so setup.ps1's Write-Host output merges into stdout; -File drops it when stdout is a pipe. Single quotes are doubled for paths with apostrophes.
script_pwsh_literal = str(script).replace("'", "''")
powershell_args.extend(
[
@@ -4084,13 +3281,7 @@ def _run_setup_script(*, verbose: bool = False, repo_root: Optional[Path] = None
f"{_PS_PROXY_DEFAULTS_PRELUDE}& '{script_pwsh_literal}' *>&1",
]
)
- # Explicitly hand std handles to the child so CI tee sees setup.ps1's
- # output. On Windows, subprocess.Popen defaults to close_fds=True
- # (bInheritHandles=False); combined with CREATE_NO_WINDOW the child
- # has no console and no inherited handles, so Write-Host writes to
- # nothing. Passing stdout/stderr makes Python mark the std handles
- # inheritable via PROC_THREAD_ATTRIBUTE_HANDLE_LIST. Empty update.log
- # on windows-latest CI was the smoking gun (runs 25533694490/25534292239).
+ # Popen defaults to close_fds=True on Windows, so with CREATE_NO_WINDOW the child has no console and Write-Host writes to nothing.
process = subprocess.Popen(
powershell_args,
env = env,
@@ -4106,23 +3297,16 @@ def _run_setup_script(*, verbose: bool = False, repo_root: Optional[Path] = None
if returncode != 0:
raise typer.Exit(returncode)
- # Only now: a cache that did not get through setup is not one to record.
_backfill_uv_cache_marker(env)
-# The refresh re-runs the installer with --shortcuts-only, fetched rather than shipped
-# so a launcher fix reaches users without waiting for a release.
+# Fetched rather than shipped, so a launcher fix reaches users without waiting for a release.
_INSTALLER_URL_BASH = "https://unsloth.ai/install.sh"
_INSTALLER_URL_PWSH = "https://unsloth.ai/install.ps1"
-# unsloth.ai 301s to raw.githubusercontent.com, so both are in the chain. Anywhere
-# else, or plain http, is refused rather than followed.
_INSTALLER_FETCH_HOSTS = frozenset({"unsloth.ai", "raw.githubusercontent.com"})
_INSTALLER_FETCH_TIMEOUT = 30
-# install.sh is ~250KB; the cap just stops an unbounded body from being buffered.
_INSTALLER_MAX_BYTES = 8 * 1024 * 1024
-# The flag this code passes, so an installer without it cannot serve the request.
-# Internal names would be tighter but can be renamed in a perfectly good installer,
-# and a false negative here skips every wheel-based refresh until new Python ships.
+# The flag this code passes: internal names would be tighter but can be renamed, and a false negative skips every refresh.
_INSTALLER_MARKERS = {
"install.sh": (b"--shortcuts-only",),
"install.ps1": (b"--shortcuts-only",),
@@ -4130,14 +3314,11 @@ _INSTALLER_MARKERS = {
def _is_allowed_installer_url(url: str) -> bool:
- """https on a known host. Applied to the first request and to every redirect."""
split = urllib.parse.urlsplit(url)
return split.scheme == "https" and split.hostname in _INSTALLER_FETCH_HOSTS
class _InstallerRedirectHandler(urllib.request.HTTPRedirectHandler):
- """Keep the installer fetch on the unsloth.ai -> raw.githubusercontent chain."""
-
def redirect_request(self, req, fp, code, msg, headers, newurl):
if not _is_allowed_installer_url(newurl):
raise urllib.error.URLError(f"refused installer redirect to {newurl}")
@@ -4145,32 +3326,18 @@ class _InstallerRedirectHandler(urllib.request.HTTPRedirectHandler):
def _build_installer_opener() -> urllib.request.OpenerDirector:
- """A private opener, so the redirect chain can be checked before it is followed.
-
- urlopen() would instead use whatever install_opener() put in place. Carrying those
- handlers over was tried and abandoned: OpenerDirector.add_handler() assigns
- handler.parent, so sharing them repoints the installed opener at this one and
- breaks every later urlopen() in the process, and copying them does not help either
- because the default HTTPSHandler here already answers first. Proxy environment
- variables and the system trust store still work, since build_opener() sets up both.
- The residue is a machine whose proxy auth or CA lives in a programmatically
- installed opener: its refresh is skipped, which the update survives, rather than
- silently pulling the installer through an unchecked path.
- """
+ """A private opener, so the redirect chain can be checked before it is followed. The installed
+ opener cannot be reused: add_handler assigns handler.parent and would repoint it at this one."""
return urllib.request.build_opener(_InstallerRedirectHandler)
def _looks_like_installer(body: Optional[bytes], installer_name: str) -> bool:
- """Cheap shape check before a fetched installer is executed.
-
- Not a trust check -- the hosts above are trusted. It stops a captive-portal page or
- an HTTP error body from being piped into bash when something in between answers.
- """
+ """Cheap shape check before a fetched installer is executed. Not a trust check: it stops a
+ captive-portal page or an error body from being piped into bash."""
if not body or len(body) < 512:
return False
head = body.lstrip()[:256].lower()
- # `<#` opens PowerShell comment-based help, which is a perfectly ordinary way for
- # install.ps1 to start, so match the actual markup rather than any leading "<".
+ # `<#` opens PowerShell comment-based help, an ordinary start for install.ps1.
if not head.startswith(b"<#") and (
head.startswith((b"<!doctype", b"<html", b"<head", b"<?xml", b"<body"))
or b"<html" in head
@@ -4191,15 +3358,12 @@ def _fetch_installer(installer_name: str, *, verbose: bool = False) -> Optional[
request = urllib.request.Request(url, headers = {"User-Agent": "unsloth-studio-update"})
with opener.open(request, timeout = _INSTALLER_FETCH_TIMEOUT) as response:
body = response.read(_INSTALLER_MAX_BYTES + 1)
- # read(amt) does not check Content-Length; only a further read() does,
- # raising IncompleteRead. Without it a transfer cut off mid-file still
- # carries the markers and would be piped into bash half-written.
+ # read(amt) does not check Content-Length; only a further read() raises IncompleteRead on a truncated transfer.
if len(body) <= _INSTALLER_MAX_BYTES:
body += response.read()
except (
urllib.error.URLError,
- # IncompleteRead / a malformed proxy response raises at the HTTP framing layer,
- # which is neither URLError nor OSError, so it would abort an already-done update.
+ # Raised at the HTTP framing layer, which is neither URLError nor OSError.
http.client.HTTPException,
TimeoutError,
OSError,
@@ -4220,8 +3384,8 @@ def _fetch_installer(installer_name: str, *, verbose: bool = False) -> Optional[
def _installer_script_candidates(installer_name: str) -> List[Path]:
- """Source-tree installers, which outrank the network because `update --local` is
- testing its own installer, so fetching over the top of it would be wrong."""
+ """Source-tree installers, which outrank the network because `update --local` is testing
+ its own installer."""
candidates: List[Path] = []
local_repo = (os.environ.get("STUDIO_LOCAL_REPO") or "").strip()
if local_repo:
@@ -4234,12 +3398,8 @@ def _installer_script_candidates(installer_name: str) -> List[Path]:
def _installers_on_disk(candidates: Sequence[Path]) -> List[Path]:
- """Every candidate that exists, not just the first.
-
- The pre-refactor loop probed and launched in one pass, so a candidate that could
- not be launched left the next one to try before the network was reached. Returning
- only the first match would quietly drop that second chance.
- """
+ """Every candidate that exists, not just the first: an unlaunchable candidate must still
+ leave the next one to try before the network is reached."""
found: List[Path] = []
for candidate in candidates:
try:
@@ -4267,8 +3427,7 @@ def _refresh_desktop_shortcuts(*, verbose: bool = False) -> None:
if is_windows:
ps_argv: List[str] = [_studio_runtime_gate.resolve_windows_powershell()]
- # -NoProfile unconditionally, as in _run_setup_script above: gating it on the hidden
- # branch left the visible console path, where a profile is exactly what IS loaded.
+ # -NoProfile unconditionally, as in _run_setup_script: the visible console path loads a profile.
ps_argv.append("-NoProfile")
if _should_hide_windows_subprocesses():
# Avoid the same Hidden/Bypass detection pair as setup above;
@@ -4291,13 +3450,8 @@ def _refresh_desktop_shortcuts(*, verbose: bool = False) -> None:
def _run_installer_bash(script: Path, args: Sequence[str], env: dict) -> bool:
- """False when the interpreter could not be launched, so the caller can fall back.
-
- The pre-refactor candidate loop caught that OSError and carried on to the next
- candidate and then to the network, silently. Returning False keeps a machine that
- cannot spawn bash for the checkout on exactly that path instead of ending the
- refresh early.
- """
+ """False when the interpreter could not be launched, so the caller can fall back to the
+ next candidate and then the network instead of ending the refresh early."""
try:
result = subprocess.run(["bash", str(script), *args], env = env, check = False)
except OSError:
@@ -4336,20 +3490,9 @@ def _run_installer_ps1(
def _run_fetched_installer_ps1(
installer: bytes, args: Sequence[str], ps_argv: Sequence[str], env: dict
) -> None:
- """Run a fetched install.ps1 from a tempfile.
-
- -File rather than `-Command -`: stdin is decoded with [Console]::InputEncoding
- (CP1252/OEM on most Windows boxes), which mangles install.ps1's box-drawing chars,
- while -File honours the BOM written below. The args go after the path so the
- installer's own `Install-UnslothStudio @args` at EOF receives them, which is why
- this no longer rewrites that line. The prefix gives AV/EDR engines (and anyone
- grepping temp) a clear identity.
-
- Creating and writing that file is its own failure mode: a full disk, a read-only or
- missing %TEMP%, or AV holding the handle. Those raise OSError, and the refresh runs
- after the package update has already succeeded, so they are reported and skipped
- rather than allowed to abort the command.
- """
+ """Run a fetched install.ps1 from a tempfile. -File rather than `-Command -`: stdin decoding
+ mangles install.ps1's box-drawing chars, and args go after the path so `Install-UnslothStudio
+ @args` receives them. A tempfile that cannot be written is reported and skipped."""
try:
ps1_fd, ps1_path = tempfile.mkstemp(prefix = "unsloth-studio-refresh-", suffix = ".ps1")
except OSError as exc:
@@ -4393,27 +3536,18 @@ def setup(
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)
- # Duplicate-metadata repair can reinstall unsloth even when the
- # installer set SKIP_STUDIO_BASE. Free and preserve the running Windows
- # launcher exactly as the direct update path does.
+ # Duplicate-metadata repair can reinstall unsloth even under SKIP_STUDIO_BASE, so free the running Windows launcher.
with _WindowsLauncherUpdateTransaction() as launcher_update:
_run_setup_script(verbose = verbose)
launcher_update.validate_launcher()
def _fail_if_install_damaged(package_name: str = "unsloth") -> None:
- """Refuse to call an update successful when the tree it produced is damaged.
-
- pip considers a distribution with intact metadata already satisfied, so an
- update reinstalls nothing when a package's FILES are damaged: it prints
- "Unsloth Studio Installed", exits 0, and the backend then dies at boot. That
- is the shape behind "just re-run the installer", and it is only actionable
- if the update says so.
- """
+ """Refuse to call an update successful when the tree it produced is damaged: pip treats intact
+ metadata as satisfied, so the update exits 0 and the backend dies at boot."""
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.
+ # This CLI is not in the venv the update wrote, so its file list describes the wrong tree.
return
managed_names = (package_name, "unsloth-zoo")
managed_conflicts = _studio_deps.installed_metadata_conflicts(names = managed_names)
@@ -4456,21 +3590,7 @@ def _fail_if_install_damaged(package_name: str = "unsloth") -> None:
typer.echo("An update cannot repair these. pip sees intact package metadata and", err = True)
typer.echo("reinstalls nothing, so Unsloth will keep failing to start. Reinstall", err = True)
typer.echo("over the top:", err = True)
- # Carry a custom root into the command. The shim is a bare symlink and
- # _ensure_studio_env_exported only sets os.environ for this process, so the
- # shell that runs this line has no UNSLOTH_STUDIO_HOME: an unqualified
- # reinstall would build a fresh ~/.unsloth/studio and leave the damaged
- # install exactly as broken as it was.
- # And carry the recorded install mode. install.sh derives SKIP_TORCH only
- # from its own flag or UNSLOTH_NO_TORCH and passes that value into setup, so
- # a plain reinstall over a GGUF-only install downloads the whole PyTorch
- # stack. Only added when the record says True: recorded_no_torch() returns
- # None when nothing recorded the mode, and None must never be read as False.
- #
- # No root argument: the manifest and marker live in the VENV, not the
- # install root, and recorded_no_torch defaults to Path(sys.prefix). Passing
- # STUDIO_HOME would look one directory too high, find nothing, and silently
- # never fire. The early return above guarantees sys.prefix is that venv.
+ # Carry the custom root and the recorded install mode, or the reinstall builds a fresh ~/.unsloth/studio and pulls the whole PyTorch stack. No root argument: recorded_no_torch reads the VENV.
no_torch = False
try:
_manifest = _studio_deps.load_install_manifest_module()
@@ -4485,8 +3605,7 @@ def _fail_if_install_damaged(package_name: str = "unsloth") -> None:
prefix += "$env:UNSLOTH_NO_TORCH = '1'; "
typer.echo(f" {prefix}irm https://unsloth.ai/install.ps1 | iex", err = True)
else:
- # The assignments go before `sh`, not before `curl`: that is the form
- # install.sh documents, and it is sh that reads them.
+ # The assignments go before `sh`, not before `curl`: that is the form install.sh documents.
env = ""
if _STUDIO_HOME_IS_CUSTOM:
env = f"UNSLOTH_STUDIO_HOME={shlex.quote(str(STUDIO_HOME))} "
@@ -4494,23 +3613,10 @@ def _fail_if_install_damaged(package_name: str = "unsloth") -> None:
env += "UNSLOTH_NO_TORCH=1 "
typer.echo(f" curl -fsSL https://unsloth.ai/install.sh | {env}sh", err = True)
typer.echo("", err = True)
- # The installer installs the current requirement sets; it does not prune or
- # reinstall anything outside them. So a package left over from an older
- # release, or added by hand, is not repaired by the command above and would
- # otherwise report the same damage forever. Say what to do in that case
- # rather than scoping the scan, which would risk passing over real damage.
+ # The installer installs only the current requirement sets, so a leftover package is not repaired by the command above.
typer.echo("If a package above is still listed after that, the installer does not", err = True)
typer.echo("manage it. Repair it directly, or remove it if nothing needs it:", err = True)
- # --no-deps: without it pip resolves the damaged package's dependency graph
- # and --force-reinstall would replace pinned runtime packages too, which can
- # swap the installed CUDA/ROCm torch build for a default one while repairing
- # an unrelated orphan. The installer's own targeted repairs pair the two for
- # the same reason. The interpreter path is quoted because a custom root may
- # contain spaces, and on Windows a quoted command needs the call operator.
- # <package>==<version> rather than a bare name: --force-reinstall reinstalls
- # even when the package is already up to date, so an unpinned name fetches
- # the newest release and silently upgrades an orphan whose consumers may
- # depend on the older one. --no-deps does not protect against that.
+ # --no-deps, or --force-reinstall could swap the installed CUDA/ROCm torch build; <package>==<version>, or it upgrades the orphan its consumers pinned.
_spec = "<package>==<installed version>"
if platform.system() == "Windows":
_py = str(Path(sys.executable)).replace("'", "''")
@@ -4544,39 +3650,24 @@ def update(
False,
"--stage",
hidden = True,
- help = "Prepare the update in a copy of the environment without touching the live one.",
+ help = "Accepted for 805-807 desktop shells, which get a refusal. Background staging is gone.",
),
):
"""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.
+ # Re-export UNSLOTH_STUDIO_HOME so the refresh subprocess resolves the same install root.
_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.
+ # `is True`, not truthiness: an in-process caller that omits it gets a truthy OptionInfo sentinel.
if stage is True:
- _stage_update(local = local, package = package, verbose = verbose, verify = verify)
+ _refuse_staged_update()
return
staging = _studio_stage.is_staging()
- # Ensure SKIP_STUDIO_BASE is not inherited from a parent install.ps1 session
+ # Do not inherit SKIP_STUDIO_BASE from a parent install.ps1 session.
os.environ.pop("SKIP_STUDIO_BASE", None)
os.environ["STUDIO_PACKAGE_NAME"] = package
repo_root: Optional[Path] = None
if local:
os.environ["STUDIO_LOCAL_INSTALL"] = "1"
- # Pass the repo root explicitly so install_python_stack.py doesn't
- # have to guess from SCRIPT_DIR (which may be inside site-packages).
- # Deriving it from __file__ only holds while this CLI runs from a
- # checkout. Once an update has installed unsloth into the venv
- # non-editably, parents[2] IS site-packages, and uv rejects it with
- # "does not appear to be a Python project: neither 'setup.py' nor
- # 'pyproject.toml' found" -- which is what a second `update --local`
- # hit on Windows, where the first update replaces the editable install.
- # Absolutise the override: setup.sh does `cd "$SCRIPT_DIR"` before it
- # runs install_python_stack.py, so a relative STUDIO_LOCAL_REPO would
- # be re-resolved against studio/ (no pyproject.toml) and hand uv back
- # the very error this guard exists to replace. .strip()/.expanduser()
- # match the handling in _refresh_desktop_shortcuts.
+ # Explicit repo root: __file__ holds only from a checkout, and once unsloth is installed non-editably parents[2] IS site-packages, which uv rejects.
_explicit = (os.environ.get("STUDIO_LOCAL_REPO") or "").strip()
repo_root = (
Path(_explicit).expanduser().resolve()
@@ -4590,10 +3681,7 @@ def update(
typer.echo("", err = True)
typer.echo(" Point at a checkout:", err = True)
if platform.system() == "Windows":
- # PowerShell has no `VAR=value command` prefix form: it parses
- # the assignment as a command name and fails to find it. This
- # guard fires on the Windows update path, so the POSIX spelling
- # would be unusable for most of the people who see it.
+ # PowerShell has no `VAR=value command` prefix form, and this guard fires on the Windows path.
typer.echo(
" $env:STUDIO_LOCAL_REPO='C:\\path\\to\\unsloth'; "
"unsloth studio update --local",
@@ -4611,29 +3699,23 @@ def update(
else:
os.environ["STUDIO_LOCAL_INSTALL"] = "0"
os.environ.pop("STUDIO_LOCAL_REPO", None)
- # main gained a runtime gate around setup; this branch replaced the
- # rename-to-.deleteme helpers with the launcher transaction. Both apply:
- # the gate keeps a second Unsloth process off the venv, the transaction
- # keeps the launcher recoverable across the setup it wraps.
+ # The gate keeps a second Unsloth process off the venv; the transaction keeps the launcher recoverable across setup.
runtime_gate_handoff = _studio_runtime_gate.consume_runtime_gate_handoff()
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.
+ # Constructed after the idle scan (pinned by test_studio_runtime_gate).
launcher_transaction = _WindowsLauncherUpdateTransaction()
if staging:
- # A staged run writes no launcher; there is nothing to keep recoverable.
+ # A staged run writes no launcher.
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.
+ # Runs even with --no-verify: a successful update must leave its own launcher usable.
launcher_update.validate_launcher()
if verify:
_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.
+ # Tauri desktop owns its own bundle entries; refreshing here would duplicate shortcuts.
if staging or os.environ.get("UNSLOTH_TAURI_UPDATE") == "1":
if verbose:
typer.echo(" refresh-launcher skipped (Tauri update)")
@@ -4641,44 +3723,63 @@ def update(
_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']}")
+def _discard_orphaned_stage() -> None:
+ """Take a leftover `.update-stage` out of an 805-807 shell's way: they map any stage directory
+ to `stage` and re-spawn `--stage` forever. Renamed before deleting."""
+ stage = STUDIO_HOME / _studio_stage.STAGE_DIR_NAME
+ if not os.path.lexists(stage):
+ return
+ aside = STUDIO_HOME / f".update-rollback-stage-{os.getpid()}"
+ try:
+ os.replace(stage, aside)
+ except OSError:
+ shutil.rmtree(stage, ignore_errors = True)
+ else:
+ shutil.rmtree(aside, ignore_errors = True)
+
+
+def _refuse_staged_update() -> None:
+ """Fail fast for a 805-807 desktop shell asking this wheel to stage.
+
+ The `.update-failed.json` marker is what makes their reconciler skip the same version.
+ backend_version is a plain String there, so a failed lookup is spelled out rather than null;
+ shell_version is an Option<String> and stays null. Nothing here touches the environment.
+ """
+ from importlib.metadata import version as package_version
+
+ try:
+ backend_version = package_version("unsloth")
+ except Exception:
+ backend_version = "unknown"
+ if not isinstance(backend_version, str) or not backend_version:
+ backend_version = "unknown"
+ shell_version = (os.environ.get(_studio_stage.SHELL_VERSION_ENV) or "").strip() or None
+ _discard_orphaned_stage()
+ marker = STUDIO_HOME / ".update-failed.json"
+ payload = (
+ json.dumps({"backend_version": backend_version, "shell_version": shell_version}, indent = 2)
+ + "\n"
+ )
+ try:
+ marker.parent.mkdir(parents = True, exist_ok = True)
+ temporary = marker.with_name(marker.name + f".{os.getpid()}.tmp")
+ temporary.write_text(payload, encoding = "utf-8")
+ os.replace(temporary, marker)
+ except OSError:
+ # A refusal the desktop can act on matters more than the marker.
+ pass
+ # stdout, not stderr: update.rs promotes a [TAURI:ERROR] line off the child's stdout.
+ typer.echo("[TAURI:ERROR] background staging is no longer supported; run the standard update")
+ raise typer.Exit(1)
class _WindowsLauncherUpdateTransaction:
"""Keep the managed Windows launcher recoverable during a Python update."""
_VERSION_TIMEOUT_SECONDS = 10
- # Sentinel rather than a message: _launcher_health_error matches on identity,
- # so it can never be confused with a real diagnostic that happens to read the
- # same way, and it never reaches a user.
+ # Sentinel rather than a message: _launcher_health_error matches on identity, and it never reaches a user.
_POLICY_BLOCKED = "an Application Control policy blocked the launcher"
- # Absence is not corruption. Quarantine takes the unsigned stub and leaves the
- # environment intact, and nothing executes the stub any more, so the CLI can be
- # perfectly healthy without it. Kept apart from the PE-shape failure, which is
- # still a real one.
+ # Absence is not corruption: quarantine leaves a healthy environment, so keep it apart from the PE-shape failure.
_LAUNCHER_ABSENT = "the updated launcher is not on disk"
_RESTORE_ATTEMPTS = 3
@@ -4771,8 +3872,7 @@ class _WindowsLauncherUpdateTransaction:
def _recover_missing_launcher(self) -> None:
assert self.launcher is not None
- # Validity, not existence: a truncated or quarantined launcher is just as
- # unusable, and the backup beside it can repair either.
+ # Validity, not existence: a truncated or quarantined launcher is just as unusable.
if self._is_valid_pe(self.launcher):
return
last_error: Optional[Tuple[Path, OSError]] = None
@@ -4781,10 +3881,7 @@ class _WindowsLauncherUpdateTransaction:
try:
self._atomic_copy(recovery, self.launcher)
except OSError as exc:
- # Try the next copy. The header check and the copy open the file
- # separately, so antivirus taking a candidate in between is a race
- # this loop can lose without the others being unusable, and giving
- # up on the first one turned a recoverable install into a failure.
+ # Try the next copy: the header check and the copy open the file separately, so one candidate lost to antivirus must not fail the install.
last_error = (recovery, exc)
continue
return
@@ -4813,26 +3910,16 @@ class _WindowsLauncherUpdateTransaction:
return False
def _move_launcher_aside(self) -> None:
- """Free the canonical path so the installer can publish a replacement.
-
- uv only self-replaces its OWN executable, so it deletes a third-party
- console script outright and hard-errors when the file is in use, after
- which the pip fallback no-ops on the already-satisfied bare unsloth and
- the upgrade is silently skipped. Renaming a running image is allowed on
- Windows: verified on windows-latest that renaming a live console-script
- launcher succeeds and a replacement can then be written at the freed
- path. Non-fatal, since failing to move it aside costs only the upgrade.
- """
+ """Free the canonical path so the installer can publish a replacement: uv deletes a third-party
+ console script outright and hard-errors when it is in use, after which the pip fallback
+ no-ops. Non-fatal; it costs only the upgrade."""
assert self.launcher is not None and self.stale is not None
if not self._is_valid_pe(self.launcher):
return
try:
os.replace(self.launcher, self.stale)
except OSError as exc:
- # Not fatal: an antivirus hold must not make the environment
- # unupdatable. But say what it costs, because uv cannot then replace
- # the launcher and the pip fallback drops --upgrade-package, so
- # unsloth is left at its old version while everything else updates.
+ # Not fatal, but say what it costs: the pip fallback drops --upgrade-package, leaving unsloth at its old version.
typer.echo(f"Warning: could not move the Unsloth launcher aside: {exc}", err = True)
typer.echo(
" unsloth itself may not be upgraded. Close anything holding "
@@ -4847,14 +3934,8 @@ class _WindowsLauncherUpdateTransaction:
return None
def _recovery_candidates(self) -> List[Path]:
- """Copies that could stand in for the launcher, best first.
-
- The backup is the last launcher known to run; the moved-aside copy is
- only this run's unvalidated canonical file; the legacy .deleteme and the
- PATH shim are what an install broken by the old updater still has. All
- of them are kept, because passing the two-byte header check does not
- make any one of them runnable and the next candidate has to be reachable.
- """
+ """Copies that could stand in for the launcher, best first. All are kept: passing the header
+ check does not make any of them runnable."""
seen: List[Path] = []
for path in (self.backup, self.stale, self.legacy_backup, self.shim):
if path is None or not self._is_valid_pe(path):
@@ -4865,9 +3946,7 @@ class _WindowsLauncherUpdateTransaction:
def _restore_from(self, source: Path) -> bool:
assert self.launcher is not None
- # The common setup-failure case leaves the original executable exactly
- # where it was. Avoid replacing that running file on Windows when it
- # already is the source byte-for-byte.
+ # The common setup-failure case leaves the original in place; do not replace a running Windows file with a byte-identical source.
if self._is_valid_pe(self.launcher) and self._files_match(self.launcher, source):
return True
last_error: Optional[OSError] = None
@@ -4884,51 +3963,23 @@ class _WindowsLauncherUpdateTransaction:
return False
def _restore_runnable(self) -> bool:
- """Put back the first copy that actually runs.
-
- Passing the two-byte header check does not make a copy runnable, so a
- candidate that fails --version must not stop the next one being tried,
- and a launcher already in place and working must not be replaced by a
- candidate that is merely PE-shaped.
-
- Under Application Control that discrimination degrades to the PE-shape
- check, because no candidate can be told apart by running it: every
- --version attempt dies in CreateProcess. That is a real limitation and
- not a hidden one -- a PE-shaped but corrupt copy can be left in place --
- but it is also unavoidable, since the only way to tell a good stub from a
- corrupt one is to start it. It is confined to the case where the launcher
- was missing or truncated, since an intact one never reaches this loop:
- _launcher_health_error asks the interpreter and reports healthy.
- """
+ """Put back the first copy that actually runs. Under Application Control every --version dies in
+ CreateProcess, so this degrades to the shape check."""
if self._launcher_health_error() is None:
return True
candidates = self._recovery_candidates()
for source in candidates:
if self._restore_from(source) and self._launcher_health_error() is None:
return True
- # Nothing ran. Leave the best candidate in place rather than whichever
- # one happened to be tried last.
+ # Nothing ran; leave the best candidate rather than whichever was tried last.
if candidates:
self._restore_from(candidates[0])
- # No copy could be put back and started. A launcher that is simply gone,
- # or one the policy denies, is still not a broken CLI, so ask the
- # interpreter before giving up. Asked only here, after every candidate
- # has been tried, so a launcher that could have been recovered still is.
+ # Gone, or denied by policy, is still not a broken CLI. Asked only after every candidate.
return self._recovered_cli_health_error() is None
def _launcher_runs_error(self) -> Optional[str]:
- """Whether THIS launcher file starts and answers --version.
-
- Deliberately about the file, not about the CLI: it is the only check that
- can catch a stub that is PE-shaped but corrupt, on every machine. Its
- caller decides what a policy denial means.
-
- The stub is probed first, and still is on a locked-down machine, which
- costs one denied-launch event per update there. That is a log entry, not
- a failure. Asking the interpreter instead would be quieter but blind: it
- cannot see a corrupt launcher on ANY machine, including the overwhelming
- majority that have no policy at all, which is the strictly worse trade.
- """
+ """Whether THIS launcher file starts and answers --version. About the file, not the CLI: the
+ only check that catches a PE-shaped but corrupt stub."""
assert self.launcher is not None
if not self.launcher.exists():
return self._LAUNCHER_ABSENT
@@ -4953,54 +4004,25 @@ class _WindowsLauncherUpdateTransaction:
return None
def _launcher_health_error(self) -> Optional[str]:
- """Whether the update left a working CLI -- the question that matters.
-
- Identical to _launcher_runs_error except when the launcher was denied by
- an Application Control policy. That denial happens before Python starts,
- so it says nothing about the update: the package can be perfectly
- healthy. Ask the signed interpreter beside it instead, or every update on
- such a machine reports failure and rolls a good install back (issue
- #8490). A launcher that fails to start for any other reason is the
- failure it always was.
- """
+ """Whether the update left a working CLI. Identical to _launcher_runs_error except for an
+ Application Control denial, which happens before Python starts: ask the signed interpreter,
+ or every update on such a machine rolls a good install back (#8490)."""
error = self._launcher_runs_error()
if error is self._POLICY_BLOCKED:
return self._interpreter_health_error(error)
return error
def _recovered_cli_health_error(self) -> Optional[str]:
- """_launcher_health_error, once recovering the launcher has been ruled out.
-
- Absence is the difference. A missing launcher IS worth restoring, so
- _launcher_health_error keeps reporting it and validate_launcher goes on
- to put the previous one back. But quarantine deletes the unsigned stub
- rather than denying it, and no copy survives being restored either, so
- once every candidate has failed, absence says as little about the update
- as a policy denial does: ask the interpreter instead of failing a good
- update and rolling it back (issue #8490).
- """
+ """_launcher_health_error, once recovery has been ruled out: a missing launcher IS worth
+ restoring, but once every candidate failed, quarantine says as little as a denial (#8490)."""
error = self._launcher_runs_error()
if error is self._POLICY_BLOCKED or error is self._LAUNCHER_ABSENT:
return self._interpreter_health_error(error)
return error
def _interpreter_health_error(self, reason: str) -> Optional[str]:
- """Health of the managed CLI when the launcher itself cannot be started.
-
- Answers the question validate_launcher actually has -- did the update
- leave a working CLI? -- on a machine where --version on the launcher can
- never succeed. Falls back to reporting the original block when there is
- no interpreter to ask.
-
- Isolated, alone among this module's managed invocations, because the
- launch it is predicting is itself isolated: build_update_command in
- studio/src-tauri/src/update.rs runs the desktop updater under
- Isolation::Isolated and clears PYTHONHOME/PYTHONPATH. Inheriting them
- here would let a foreign checkout on PYTHONPATH answer --version for a
- managed package the update actually broke, and validate_launcher would
- keep an update that the next desktop launch cannot start. -I implies -E,
- so it clears the same two variables the Rust side removes by hand.
- """
+ """Health of the managed CLI when the launcher cannot be started. Isolated alone among this
+ module's managed invocations, mirroring build_update_command's Isolation::Isolated."""
assert self.launcher is not None
python = self.launcher.parent / "python.exe"
if not python.is_file():
@@ -5015,13 +4037,7 @@ class _WindowsLauncherUpdateTransaction:
_managed_cli_argv(python, "--version", isolated = True),
check = False,
capture_output = True,
- # The import probe's ceiling, not the launcher's. --version on the
- # launcher is a process start; here it is a bare interpreter start
- # plus the whole CLI package import, which is exactly the work
- # _MANAGED_CLI_IMPORT_PROBE_TIMEOUT is generous for. Under the
- # antivirus scan that produced the quarantine this path exists to
- # survive, the launcher's 10 seconds would call a healthy update
- # broken and roll it back, once per recovery candidate.
+ # The import probe's ceiling, not the launcher's: this is an interpreter start plus the whole CLI import.
timeout = _MANAGED_CLI_IMPORT_PROBE_TIMEOUT,
**_windows_hidden_subprocess_kwargs(),
)
@@ -5038,12 +4054,8 @@ class _WindowsLauncherUpdateTransaction:
@staticmethod
def _managed_scripts_dir() -> Path:
- """Scripts dir of the venv setup actually updates.
-
- setup.ps1 installs into STUDIO_HOME/unsloth_studio, which is not this
- interpreter when a pip-installed or checkout CLI drives the update. Same
- distinction _studio_deps._managed_root draws for the damage scan.
- """
+ """Scripts dir of the venv setup actually updates: STUDIO_HOME/unsloth_studio, which is not
+ this interpreter when a pip-installed or checkout CLI drives the update."""
managed = STUDIO_HOME / "unsloth_studio"
if (managed / "pyvenv.cfg").is_file():
try:
@@ -5065,23 +4077,16 @@ class _WindowsLauncherUpdateTransaction:
self.launcher = scripts / "unsloth.exe"
self.backup = scripts / "unsloth.exe.update-backup"
self.legacy_backup = scripts / "unsloth.exe.deleteme"
- # Under the Unsloth home, not the venv: setup.ps1 removes the whole
- # $VenvDir to rebuild a stale torch, and an open handle inside it makes
- # Windows refuse the recursive delete. One lock per Unsloth home is the
- # right grain anyway, since that is what names the managed venv.
+ # Under the Unsloth home, not the venv: setup.ps1 removes the whole $VenvDir, which Windows refuses while a handle inside is open.
self.lock_path = STUDIO_HOME / "unsloth.exe.update-lock"
- # install.ps1 hardlinks this to the launcher, so it survives the old
- # updater's .deleteme unlink and is a valid recovery source.
+ # install.ps1 hardlinks this to the launcher, so it survives the old updater and is a valid recovery source.
self.shim = STUDIO_HOME / "bin" / "unsloth.exe"
self.stale = scripts / "unsloth.exe.update-stale"
self._acquire_lock()
try:
self._recover_missing_launcher()
if not self._is_valid_pe(self.launcher):
- # Warn, do not exit. The previous updater could leave an install
- # with no launcher and no .deleteme, and refusing here would stop
- # exactly those users from ever updating again. Setup may well
- # write a new launcher; validate_launcher still judges the result.
+ # Warn, do not exit: the previous updater could leave no launcher and no .deleteme, and refusing would strand those users.
typer.echo(
f"Warning: the managed Unsloth launcher is missing or invalid: {self.launcher}",
err = True,
@@ -5090,16 +4095,11 @@ class _WindowsLauncherUpdateTransaction:
if self._retained_backup() is None:
self.backup = None
elif self._retained_backup() is None:
- # Only write a backup when there is no usable one already. A
- # backup outlives __enter__ only when a previous run died before
- # validating, so it holds the last launcher known to run, while
- # the canonical file has passed nothing but the two-byte header
- # check. Overwriting it here destroyed the only recovery copy.
+ # Only when there is no usable backup: a surviving one holds the last launcher known to run.
try:
self._atomic_copy(self.launcher, self.backup)
except OSError as exc:
- # A backup is a safety net, not a precondition. Antivirus or a
- # locked-down Scripts dir must not abort the update outright.
+ # A backup is a safety net, not a precondition.
typer.echo(f"Warning: could not back up the Unsloth launcher: {exc}", err = True)
self.backup = None
self._move_launcher_aside()
@@ -5111,18 +4111,12 @@ class _WindowsLauncherUpdateTransaction:
def validate_launcher(self) -> None:
if not self.enabled:
return
- # Whether setup published anything decides how a bad result is read, so
- # it has to be sampled before any restore puts a launcher back.
+ # Sampled before any restore, since whether setup published anything decides how a bad result reads.
published = self.launcher.exists()
error = self._launcher_health_error()
if error is not None:
restored = self._restore_runnable()
- # Setup publishing nothing is the case this transaction exists for:
- # a no-op pip update leaves the freed path empty, and the old
- # updater then deleted its own .deleteme, leaving no launcher at
- # all. Putting the previous one back is success, not failure. A
- # launcher setup DID write and that cannot run is still a failure,
- # even though the previous one goes back.
+ # Setup publishing nothing is the case this exists for, so restoring is success; a launcher setup DID write that cannot run is a failure.
if published or not restored:
typer.echo(f"Error: Unsloth Studio update failed because {error}.", err = True)
if restored:
@@ -5131,12 +4125,7 @@ class _WindowsLauncherUpdateTransaction:
typer.echo(f"Manual recovery copy retained at: {self.backup}", err = True)
raise typer.Exit(1)
self._validated = True
- # Only once the launcher is actually back. A quarantined or locked stub can
- # be judged healthy through the interpreter while every attempt to restore
- # a copy failed, and deleting the copies there would throw away the only
- # material a later run could recover from. They are fixed names, so keeping
- # them costs nothing and the next update that does put a launcher back
- # clears them.
+ # Only once the launcher is back: a quarantined stub can be judged healthy while every restore failed, and the copies are the only recovery material.
if not self._is_valid_pe(self.launcher):
return
for orphan in (self.stale, self.backup, self.legacy_backup):
@@ -5157,9 +4146,6 @@ class _WindowsLauncherUpdateTransaction:
return False
-# ── unsloth studio reset-password ────────────────────────────────────
-
-
@studio_app.command("desktop-capabilities", hidden = True)
def desktop_capabilities(
json_output: bool = typer.Option(
@@ -5171,13 +4157,12 @@ def desktop_capabilities(
state = _install_state()
payload = {
"desktop_protocol_version": 1,
- # 2 adds studio_install_ok; the desktop treats < 2 as stale rather than
- # guess at an absent field.
+ # 2 adds studio_install_ok; the desktop treats < 2 as stale.
"desktop_manageability_version": 2,
"supports_provision_desktop_auth": True,
"supports_api_only": True,
"supports_desktop_backend_ownership": True,
- # Did the install finish and are the backend's boot deps still there.
+ # Did the install finish and are the backend boot deps still there.
"studio_install_ok": bool(state["ok"]),
"studio_install_reason": state["reason"],
"version": "unknown",
@@ -5204,14 +4189,8 @@ def verify_install(
help = "Emit machine-readable JSON.",
),
):
- """Check that the Unsloth Studio dependency install completed.
-
- Exits 0 when complete, 1 otherwise. setup.sh / setup.ps1 use the exit code
- to decide whether the "already up to date" fast path may be taken.
-
- Scans the installed files too, unlike `desktop-capabilities`: nothing times
- this one out.
- """
+ """Check that the Unsloth Studio dependency install completed. Exits 0 when complete; setup.sh
+ and setup.ps1 use the code for the "already up to date" fast path. Scans installed files too."""
state = _install_state(deep = True)
if json_output:
@@ -5240,12 +4219,8 @@ def provision_desktop_auth():
@studio_app.command("reset-password")
def reset_password():
- """Reset the Unsloth admin password.
-
- Rotates the credential in place: a running Unsloth accepts the new password on
- its next request, so there is nothing to restart. Shared /p preview links are
- not revoked -- rotate those in Settings if the old password leaked.
- """
+ """Reset the Unsloth admin password. Rotates in place, so nothing needs restarting. Shared /p
+ preview links are not revoked; rotate those in Settings if the old password leaked."""
new_password = _generate_reset_password()
try:
conn = _connect_auth_db()
diff --git a/unsloth_cli/tests/test_studio_update_stage.py b/unsloth_cli/tests/test_studio_update_stage.py
index 89db3205d2d..a3fb562bcae 100644
--- a/unsloth_cli/tests/test_studio_update_stage.py
+++ b/unsloth_cli/tests/test_studio_update_stage.py
@@ -94,207 +94,50 @@ def test_make_relocatable_rewrites_shell_wrapper_for_path_with_spaces(tmp_path):
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_an_accepted_stage_publishes_the_uv_cache_it_used(monkeypatch, tmp_path):
- """The staged child cannot write the live marker: STUDIO_HOME names the install it is
- replacing, and the stage may never activate. It parks the choice, and acceptance is
- what publishes it, or a desktop-only install never records one at all."""
- home = tmp_path / "studio"
- _make_venv(home)
- monkeypatch.delenv(_studio_stage.SHELL_VERSION_ENV, raising = False)
-
- def fake_update(root: Path, args: list[str]) -> int:
- (root / _studio_stage.UV_CACHE_MARKER).write_text("/warm/uv\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 = fake_update)
-
- live = home / "cache" / _studio_stage.UV_CACHE_MARKER
- assert live.read_text(encoding = "utf-8").strip() == "/warm/uv"
-
-
-def test_a_rejected_stage_publishes_nothing(monkeypatch, tmp_path):
- """Verification is the acceptance point, so a stage that parks a choice and then fails
- its probes must leave the live install pointing where it already pointed."""
- home = tmp_path / "studio"
- _make_venv(home)
- (home / "cache").mkdir(parents = True)
- (home / "cache" / _studio_stage.UV_CACHE_MARKER).write_text("/live/uv\n", encoding = "utf-8")
- monkeypatch.delenv(_studio_stage.SHELL_VERSION_ENV, raising = False)
-
- def fake_update(root: Path, args: list[str]) -> int:
- (root / _studio_stage.UV_CACHE_MARKER).write_text("/staged/uv\n", encoding = "utf-8")
- return 0
-
- def refuse(venv, env):
- raise _studio_stage.StageError("staged environment failed to start")
-
- monkeypatch.setattr(_studio_stage, "probe_cli", refuse)
-
- with pytest.raises(_studio_stage.StageError):
- _studio_stage.stage(home, update_args = [], echo = lambda _: None, run_update = fake_update)
-
- live = home / "cache" / _studio_stage.UV_CACHE_MARKER
- assert live.read_text(encoding = "utf-8").strip() == "/live/uv"
-
-
-def test_a_stage_that_parks_nothing_leaves_the_live_marker_alone(monkeypatch, tmp_path):
- """Nothing to promote is the normal case for a caller-pinned UV_CACHE_DIR, and it must
- not blank the marker an installer wrote."""
- home = tmp_path / "studio"
- _make_venv(home)
- (home / "cache").mkdir(parents = True)
- (home / "cache" / _studio_stage.UV_CACHE_MARKER).write_text("/live/uv\n", encoding = "utf-8")
- monkeypatch.delenv(_studio_stage.SHELL_VERSION_ENV, raising = False)
- 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 = lambda root, args: 0)
-
- live = home / "cache" / _studio_stage.UV_CACHE_MARKER
- assert live.read_text(encoding = "utf-8").strip() == "/live/uv"
-
-
-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)
[email protected](sys.platform == "win32", reason = "POSIX shebangs")
+def test_make_relocatable_never_shrinks_a_script_below_its_recorded_size(tmp_path):
+ """RECORD keeps the size the installer wrote and anything smaller is damage, so an 82-byte shebang would shrink every console script."""
+ long_root = tmp_path / ("d" * 60) / ("e" * 60)
+ long_root.mkdir(parents = True)
+ venv = _make_venv(long_root)
+ originals = {
+ name: (venv / "bin" / name).stat().st_size
+ for name in ("unsloth", "pip", "activate", "env-script", "native")
+ }
+ assert len(str(venv)) > 68
- 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)
+ assert _studio_stage.make_relocatable(venv) == 2
+ for name, original in originals.items():
+ assert (venv / "bin" / name).stat().st_size >= original, name
+ # Padded, not truncated: the script still ends in what the installer wrote.
+ text = (venv / "bin" / "unsloth").read_text(encoding = "utf-8")
+ assert text.startswith(_studio_stage.RELOCATABLE_SHEBANG)
+ assert text.endswith("print('cli')\n")
+ assert text.splitlines()[3].startswith("# ")
-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
- )
[email protected](sys.platform == "win32", reason = "POSIX shebangs")
+def test_a_finalised_stage_under_a_long_path_passes_the_record_size_check(tmp_path):
+ """End-to-end shape of the regression: the size comparison install_manifest runs after a finalised
+ stage decides whether every later update repeats the whole dependency pass."""
+ stage_root = tmp_path / ("l" * 70) / "studio" / _studio_stage.STAGE_DIR_NAME
+ stage_root.mkdir(parents = True)
+ 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)
+ # What RECORD holds for the console scripts, as sizes rather than a real wheel.
+ recorded = {name: (venv / "bin" / name).stat().st_size for name in ("unsloth", "pip")}
+ assert len(str(venv)) > 68
-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)
+ _studio_stage.finalize_for_activation(stage_root)
- 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()
+ damaged = [
+ name for name, size in recorded.items() if (venv / "bin" / name).stat().st_size < size
+ ]
+ assert damaged == []
def test_child_environment_points_the_staged_cli_at_the_stage_root(monkeypatch, tmp_path):
@@ -321,127 +164,14 @@ def test_staged_python_commands_use_isolated_mode(monkeypatch, tmp_path):
def fake_run(command, *, cwd, env):
commands.append(command)
- return type("Result", (), {"returncode": 0, "stdout": "2026.9.1\n", "stderr": ""})()
+ return type("Result", (), {"returncode": 0, "stdout": "", "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]
-
-
@pytest.mark.skipif(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)
@@ -479,3 +209,103 @@ def test_activation_finalizer_repairs_a_launcher_written_by_an_old_outer_stage(t
result = subprocess.run([str(live / "bin" / "unsloth"), "-h"], check = False)
assert result.returncode == 0
+
+
+def _invoke_stage(monkeypatch, home: Path):
+ from typer.testing import CliRunner
+ from unsloth_cli.commands import studio as studio_mod
+
+ monkeypatch.delenv(_studio_stage.STAGE_ROOT_ENV, raising = False)
+ monkeypatch.setattr(studio_mod, "STUDIO_HOME", home)
+ return CliRunner().invoke(studio_mod.studio_app, ["update", "--stage"])
+
+
+def test_stage_is_refused_and_records_what_the_old_shell_asked_for(monkeypatch, tmp_path):
+ """An 805-807 shell still spawns `--stage`: it has to fail and leave the marker, or the shell asks again."""
+ home = tmp_path / "studio"
+ monkeypatch.setenv(_studio_stage.SHELL_VERSION_ENV, "0.1.807-beta")
+
+ result = _invoke_stage(monkeypatch, home)
+
+ assert result.exit_code == 1, result.output
+ assert "[TAURI:ERROR] background staging is no longer supported" in result.output
+ marker = json.loads((home / ".update-failed.json").read_text(encoding = "utf-8"))
+ # StagedVersions types this one as a plain String; null would fail the whole parse.
+ assert isinstance(marker["backend_version"], str) and marker["backend_version"]
+ assert marker["shell_version"] == "0.1.807-beta"
+ assert not (home / _studio_stage.STAGE_DIR_NAME).exists()
+
+
+def test_a_refusal_clears_a_stage_an_earlier_shell_left_behind(monkeypatch, tmp_path):
+ """805-807 map any stage directory back to `stage`, so an orphan has the shell asking at every recheck."""
+ home = tmp_path / "studio"
+ stage = home / _studio_stage.STAGE_DIR_NAME
+ (stage / _studio_stage.VENV_NAME / "bin").mkdir(parents = True)
+ (stage / _studio_stage.VENV_NAME / "bin" / "python").write_text("x", encoding = "utf-8")
+ monkeypatch.setenv(_studio_stage.SHELL_VERSION_ENV, "0.1.805-beta")
+
+ result = _invoke_stage(monkeypatch, home)
+
+ assert result.exit_code == 1, result.output
+ assert not stage.exists()
+ assert [p.name for p in home.iterdir() if p.name.startswith(".update-")] == [
+ ".update-failed.json"
+ ]
+
+
+ ("environment", "expected"),
+ [
+ (None, None),
+ ("", None),
+ (" ", None),
+ (" 0.1.806-beta ", "0.1.806-beta"),
+ ],
+)
+def test_a_refusal_records_the_shell_version_or_nothing(
+ monkeypatch, tmp_path, environment, expected
+):
+ """`shell_version` is an `Option<String>`, so null parses; a placeholder would fail their equality check as null does."""
+ home = tmp_path / "studio"
+ if environment is None:
+ monkeypatch.delenv(_studio_stage.SHELL_VERSION_ENV, raising = False)
+ else:
+ monkeypatch.setenv(_studio_stage.SHELL_VERSION_ENV, environment)
+
+ result = _invoke_stage(monkeypatch, home)
+
+ assert result.exit_code == 1, result.output
+ marker = json.loads((home / ".update-failed.json").read_text(encoding = "utf-8"))
+ assert marker["shell_version"] == expected
+ assert isinstance(marker["backend_version"], str)
+
+
+def test_a_refusal_that_cannot_write_the_marker_still_reports_the_error(monkeypatch, tmp_path):
+ # An unwritable home is the one case where the refusal matters more than the marker.
+ blocker = tmp_path / "studio"
+ blocker.parent.mkdir(parents = True, exist_ok = True)
+ blocker.write_text("not a directory", encoding = "utf-8")
+
+ result = _invoke_stage(monkeypatch, blocker)
+
+ assert result.exit_code == 1, result.output
+ assert "[TAURI:ERROR] background staging is no longer supported" in result.output
+
+
+def test_the_activation_finalizer_imports_under_isolated_python():
+ """The 805-807 activation path imports finalize_for_activation under `python -I` inside the staged venv."""
+ result = subprocess.run(
+ [
+ sys.executable,
+ "-I",
+ "-c",
+ "import sys; sys.path.insert(0, sys.argv[1]); "
+ "from unsloth_cli._studio_stage import finalize_for_activation",
+ str(_REPO_ROOT),
+ ],
+ capture_output = True,
+ text = True,
+ check = False,
+ )
+
+ assert result.returncode == 0, result.stderr