Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: stop showing "Update failed" when the window is reloaded during an update (#11226)
Nilay5449a22c546b
diff --git a/studio/frontend/src/components/tauri/startup-messages.ts b/studio/frontend/src/components/tauri/startup-messages.tsindex ff1b052f548..09268eea34e 100644--- a/studio/frontend/src/components/tauri/startup-messages.ts+++ b/studio/frontend/src/components/tauri/startup-messages.ts@@ -1,6 +1,7 @@export const INITIAL_STARTUP_MESSAGE = "Starting Unsloth...";export const MODELS_STARTUP_MESSAGE = "Loading models...";export const SERVER_STARTUP_MESSAGE = "Nearly done...";+export const UPDATE_STARTUP_MESSAGE = "Finishing update...";export const STATUS_MESSAGE_ROTATION_MS = 5_000;export interface InstallProgressMessage {@@ -59,7 +60,8 @@ export function installProgressMessage(export type StartupMessage =| typeof INITIAL_STARTUP_MESSAGE| typeof MODELS_STARTUP_MESSAGE- | typeof SERVER_STARTUP_MESSAGE;+ | typeof SERVER_STARTUP_MESSAGE+ | typeof UPDATE_STARTUP_MESSAGE;const STARTUP_WAITING_MESSAGES = [INITIAL_STARTUP_MESSAGE,diff --git a/studio/frontend/src/hooks/backend-preflight-message.ts b/studio/frontend/src/hooks/backend-preflight-message.tsindex ad652475538..494408a788e 100644--- a/studio/frontend/src/hooks/backend-preflight-message.ts+++ b/studio/frontend/src/hooks/backend-preflight-message.ts@@ -11,6 +11,12 @@ export const WORKING_DIRECTORY_UNAVAILABLE = "working_directory_unavailable";/// Mirrors PATH_SETTING_UNRESOLVABLE in studio/src-tauri/src/preflight/managed.rs.export const PATH_SETTING_UNRESOLVABLE = "path_setting_unresolvable";+/// Mirrors MANAGED_ENVIRONMENT_BUSY in studio/src-tauri/src/preflight/managed.rs.+export const MANAGED_ENVIRONMENT_BUSY = "managed_environment_busy";++/// Mirrors MANAGED_ENVIRONMENT_UPDATING in studio/src-tauri/src/preflight/managed.rs.+export const MANAGED_ENVIRONMENT_UPDATING = "managed_environment_updating";+export function preflightStaleMessage(disposition: string,reason: string | null,diff --git a/studio/frontend/src/hooks/use-tauri-backend.ts b/studio/frontend/src/hooks/use-tauri-backend.tsindex bc8b061d046..2efe6053e18 100644--- a/studio/frontend/src/hooks/use-tauri-backend.ts+++ b/studio/frontend/src/hooks/use-tauri-backend.ts@@ -9,7 +9,11 @@ import {useSyncExternalStore,} from "react";import { isTauri, setApiBase } from "@/lib/api-base";-import { preflightStaleMessage } from "@/hooks/backend-preflight-message";+import {+ MANAGED_ENVIRONMENT_BUSY,+ MANAGED_ENVIRONMENT_UPDATING,+ preflightStaleMessage,+} from "@/hooks/backend-preflight-message";import {copySupportDiagnostics,type CopySupportDiagnosticsResult,@@ -29,6 +33,7 @@ import {import {INITIAL_STARTUP_MESSAGE,SERVER_STARTUP_MESSAGE,+ UPDATE_STARTUP_MESSAGE,startupMessageFromLog,type StartupMessage,} from "@/components/tauri/startup-messages";@@ -76,6 +81,10 @@ interface DesktopPreflightResult {}const MANAGED_STARTUP_POLL_MS = 500;+const MANAGED_ENVIRONMENT_POLL_MS = 5_000;+// Five minutes. Only bounds a gate held outside this app, e.g. a terminal+// `unsloth studio update` left at a prompt, which need never finish.+const MANAGED_ENVIRONMENT_WAIT_POLLS = 60;type TauriInvoke = typeof import("@tauri-apps/api/core").invoke;type ManagedStartupResult =@@ -162,6 +171,8 @@ export function useTauriBackend() {const [isExternalServer, setIsExternalServer] = useState(false);const externalPollRef = useRef<ReturnType<typeof setInterval> | null>(null);const externalPollAbortedRef = useRef(false);+ const environmentWaitRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const environmentWaitPollsRef = useRef(0);const authFailureRef = useRef<string | null>(getTauriAuthFailure());const elevationResumeRef = useRef<"install" | "repair" | null>(null);// Whether the repair in flight was asked to skip straight to the installer. Read back by@@ -174,6 +185,9 @@ export function useTauriBackend() {function setBackendStatus(nextStatus: BackendStatus) {if (authFailureRef.current) return;+ // A native install or repair outlives a reload and can raise elevation or+ // failure over the wait, which the next poll would otherwise overwrite.+ stopManagedEnvironmentWait();statusRef.current = nextStatus;setStatus(nextStatus);syncTrayStatus(nextStatus);@@ -184,6 +198,7 @@ export function useTauriBackend() {nextStatus: BackendStatus = "error",) {if (authFailureRef.current) return;+ stopManagedEnvironmentWait();statusRef.current = nextStatus;setStatus(nextStatus);setError(nextError);@@ -252,6 +267,34 @@ export function useTauriBackend() {statusRef.current = status;}, [status]);+ function stopManagedEnvironmentWait() {+ if (environmentWaitRef.current) {+ clearTimeout(environmentWaitRef.current);+ environmentWaitRef.current = null;+ }+ environmentWaitPollsRef.current = 0;+ }++ function waitForManagedEnvironment(bounded: boolean) {+ // setBackendStatus is a no-op here, so the poll would run on behind the error.+ if (authFailureRef.current) return;+ if (bounded && environmentWaitPollsRef.current >= MANAGED_ENVIRONMENT_WAIT_POLLS) {+ setBackendError(+ "Another Unsloth install or update, such as `unsloth studio update` in a terminal, is still running. Retry once it finishes.",+ );+ return;+ }+ // Read before setBackendStatus, which resets the count.+ const polls = bounded ? environmentWaitPollsRef.current + 1 : 0;+ setStartupMessage(UPDATE_STARTUP_MESSAGE);+ setBackendStatus("starting");+ environmentWaitPollsRef.current = polls;+ environmentWaitRef.current = setTimeout(() => {+ environmentWaitRef.current = null;+ void checkInstallAndStart();+ }, MANAGED_ENVIRONMENT_POLL_MS);+ }+async function checkInstallAndStart() {// Honor a persisted stop before preflight: the native command side-effects// (it can adopt a still-reaping backend, reset the intentional-stop flag,@@ -300,6 +343,13 @@ export function useTauriBackend() {case "managed_stale":setIsExternalServer(false);stopExternalServerPoll();+ if (+ preflight.reason === MANAGED_ENVIRONMENT_BUSY ||+ preflight.reason === MANAGED_ENVIRONMENT_UPDATING+ ) {+ waitForManagedEnvironment(preflight.reason === MANAGED_ENVIRONMENT_BUSY);+ return;+ }if (preflight.can_auto_repair) {await startRepair();} else {@@ -496,6 +546,7 @@ export function useTauriBackend() {elevationResumeRef.current = null;setIsExternalServer(false);stopExternalServerPoll();+ stopManagedEnvironmentWait();seenStepsRef.current.clear();if (resumeForcedRepair) {void startRepair({ forceInstaller: true });@@ -736,6 +787,7 @@ export function useTauriBackend() {disposed = true;cleanup.forEach((fn) => fn());stopExternalServerPoll();+ stopManagedEnvironmentWait();};}, []);diff --git a/studio/frontend/tests/backend-preflight-message.test.ts b/studio/frontend/tests/backend-preflight-message.test.tsindex 6b506813dca..aa4851b9d06 100644--- a/studio/frontend/tests/backend-preflight-message.test.ts+++ b/studio/frontend/tests/backend-preflight-message.test.ts@@ -2,11 +2,14 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";import test from "node:test";// use-tauri-backend.ts pulls in React and the Tauri APIs, so the message choice// lives in its own module and is driven directly here.import {+ MANAGED_ENVIRONMENT_BUSY,+ MANAGED_ENVIRONMENT_UPDATING,WORKING_DIRECTORY_UNAVAILABLE,PATH_SETTING_UNRESOLVABLE,preflightStaleMessage,@@ -97,3 +100,18 @@ test("the setting that could not be resolved is named", () => {assert.match(unnamed, /One of Unsloth's folder settings points/);assert.doesNotMatch(unnamed, UPDATE_ADVICE);});++test("the busy reasons are spelled the same in Rust", async () => {+ const native = await readFile(+ new URL("../../src-tauri/src/preflight/managed.rs", import.meta.url),+ "utf8",+ );+ assert.ok(+ native.includes(`MANAGED_ENVIRONMENT_BUSY: &str = "${MANAGED_ENVIRONMENT_BUSY}"`),+ );+ assert.ok(+ native.includes(+ `MANAGED_ENVIRONMENT_UPDATING: &str = "${MANAGED_ENVIRONMENT_UPDATING}"`,+ ),+ );+});diff --git a/studio/frontend/tests/forced-repair-retry.test.ts b/studio/frontend/tests/forced-repair-retry.test.tsindex 65ba6bbaa3a..463600cd093 100644--- a/studio/frontend/tests/forced-repair-retry.test.ts+++ b/studio/frontend/tests/forced-repair-retry.test.ts@@ -66,6 +66,7 @@ function runRetry(status: string, forced: boolean): Run {setElevationPackages: noop,setIsExternalServer: noop,stopExternalServerPoll: noop,+ stopManagedEnvironmentWait: noop,};const keys = Object.keys(scope);new Function(diff --git a/studio/frontend/tests/managed-environment-wait.test.ts b/studio/frontend/tests/managed-environment-wait.test.tsnew file mode 100644index 00000000000..8efa5816ed2--- /dev/null+++ b/studio/frontend/tests/managed-environment-wait.test.ts@@ -0,0 +1,243 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A reload during an install or update must wait it out: repairing instead is what+// produced "Update failed: Repair is already running.". The hook cannot be rendered,+// so its functions are lifted by regex, as in forced-repair-retry.test.ts.++import assert from "node:assert/strict";+import test from "node:test";++import {+ MANAGED_ENVIRONMENT_BUSY,+ MANAGED_ENVIRONMENT_UPDATING,+} from "../src/hooks/backend-preflight-message.ts";+import { UPDATE_STARTUP_MESSAGE } from "../src/components/tauri/startup-messages.ts";+import { readSrcAsync } from "./helpers/kit.ts";++const src = await readSrcAsync("hooks/use-tauri-backend.ts");++function lift(pattern: RegExp, what: string): string {+ const found = pattern.exec(src);+ assert.ok(found, `could not find ${what} in use-tauri-backend.ts`);+ return found[0];+}++const checkBody = lift(+ / async function checkInstallAndStart\(\) \{[\s\S]*?\n \}\n/,+ "checkInstallAndStart",+);+const waitBody = lift(+ / function waitForManagedEnvironment\([^)]*\) \{[\s\S]*?\n \}\n/,+ "waitForManagedEnvironment",+);+const statusBody = lift(+ / function setBackendStatus\([^)]*\) \{[\s\S]*?\n \}\n/,+ "setBackendStatus",+);+const errorBody = lift(+ / function setBackendError\([\s\S]*?\n \}\n/,+ "setBackendError",+);+const stopBody = lift(+ / function stopManagedEnvironmentWait\(\) \{[\s\S]*?\n \}\n/,+ "stopManagedEnvironmentWait",+);+const POLL_LIMIT = Number(+ lift(/const MANAGED_ENVIRONMENT_WAIT_POLLS = \d+;/, "the poll limit").replace(/\D/g, ""),+);++interface Preflight {+ disposition: string;+ reason: string | null;+ can_auto_repair: boolean;+ port: number | null;+}++const BUSY: Preflight = {+ disposition: "managed_stale",+ // The busy branch must win over it: the busy environment refuses that repair.+ can_auto_repair: true,+ reason: MANAGED_ENVIRONMENT_BUSY,+ port: null,+};++function harness(preflight: Preflight, authFailure: string | null = null) {+ const errors: string[] = [];+ const statuses: string[] = [];+ const messages: string[] = [];+ let repairs = 0;+ let starts = 0;+ let armed: (() => void) | null = null;+ let armedCount = 0;+ const environmentWaitPollsRef = { current: 0 };+ const noop = () => {};++ const scope: Record<string, unknown> = {+ MANAGED_ENVIRONMENT_BUSY,+ MANAGED_ENVIRONMENT_UPDATING,+ UPDATE_STARTUP_MESSAGE,+ MANAGED_ENVIRONMENT_POLL_MS: 5_000,+ MANAGED_ENVIRONMENT_WAIT_POLLS: POLL_LIMIT,+ SERVER_STARTUP_MESSAGE: "Nearly done...",+ authFailureRef: { current: authFailure },+ environmentWaitRef: { current: null as unknown },+ environmentWaitPollsRef,+ statusRef: { current: "checking" },+ portRef: { current: null as number | null },+ // The bare specifier does not resolve inside `new Function`.+ importTauriCore: () =>+ Promise.resolve({+ invoke: (command: string) => {+ if (command === "desktop_preflight") return Promise.resolve(preflight);+ if (command === "start_managed_repair") {+ repairs += 1;+ return Promise.reject("An update or repair is already running.");+ }+ return Promise.resolve(null);+ },+ }),+ setTimeout: (fn: () => void) => {+ armed = fn;+ armedCount += 1;+ return armedCount;+ },+ clearTimeout: () => {+ armed = null;+ },+ hasServerStopIntent: () => false,+ setStartupMessage: (message: string) => messages.push(message),+ setStatus: (status: string) => statuses.push(status),+ syncTrayStatus: noop,+ setError: (error: string) => errors.push(error),+ setApiBase: noop,+ setIsExternalServer: noop,+ stopExternalServerPoll: noop,+ startExternalServerPoll: noop,+ setRunningStatus: noop,+ startManagedServer: () => {+ starts += 1;+ return Promise.resolve();+ },+ startRepair: () => {+ repairs += 1;+ return Promise.resolve();+ },+ preflightStaleMessage: (_d: string, reason: string | null) => `stale:${reason}`,+ externalConflictMessage: () => "conflict",+ };++ const source = `+${stopBody}+${statusBody.replace(": BackendStatus", "")}+${errorBody.replace(/: (string|BackendStatus)/g, "")}+${waitBody.replace("bounded: boolean", "bounded")}+${checkBody+ .replace('await import("@tauri-apps/api/core")', "await importTauriCore()")+ .replace("invoke<DesktopPreflightResult>(", "invoke(")}+ return checkInstallAndStart;+ `;+ const keys = Object.keys(scope);+ const check = new Function(...keys, source)(+ ...keys.map((key) => scope[key]),+ ) as () => Promise<void>;++ return {+ check,+ errors,+ statuses,+ messages,+ get starts() {+ return starts;+ },+ get repairs() {+ return repairs;+ },+ get armedCount() {+ return armedCount;+ },+ get waiting() {+ return armed !== null;+ },+ polls: () => environmentWaitPollsRef.current,+ async fireWait() {+ const next = armed;+ assert.ok(next, "no wait was armed");+ armed = null;+ next();+ // The timer dispatches checkInstallAndStart as a floating promise.+ for (let i = 0; i < 8; i += 1) await Promise.resolve();+ },+ };+}++test("a busy environment waits instead of repairing", async () => {+ const run = harness(BUSY);+ await run.check();++ assert.equal(run.repairs, 0, "a busy environment refuses the repair it would start");+ assert.deepEqual(run.errors, [], "the user must not see a failure for a normal update");+ assert.deepEqual(run.statuses, ["starting"]);+ assert.deepEqual(run.messages, [UPDATE_STARTUP_MESSAGE]);+ assert.ok(run.waiting, "the wait must re-poll rather than give up on one answer");+});++test("the wait re-polls and starts by itself once the environment frees up", async () => {+ const preflight: Preflight = { ...BUSY };+ const run = harness(preflight);+ await run.check();+ assert.equal(run.polls(), 1);++ await run.fireWait();+ assert.equal(run.polls(), 2, "still busy, so the wait re-arms");+ assert.equal(run.repairs, 0);++ preflight.disposition = "managed_ready";+ preflight.reason = null;+ await run.fireWait();+ assert.equal(run.waiting, false, "a ready install ends the wait");+ assert.equal(run.polls(), 0, "and retires the count with it");+ assert.equal(run.starts, 1);+ assert.equal(run.repairs, 0);+});++test("a stale install that is not busy still repairs", async () => {+ const run = harness({ ...BUSY, reason: "cli_unusable" });+ await run.check();++ assert.equal(run.repairs, 1, "only the busy reason may skip the repair");+ assert.equal(run.waiting, false);+});++test("the wait is bounded, so a gate nobody releases still reaches Retry", async () => {+ const run = harness(BUSY);+ await run.check();+ for (let i = 1; i < POLL_LIMIT; i += 1) await run.fireWait();+ assert.equal(run.polls(), POLL_LIMIT, "the count tracks every consecutive busy answer");+ assert.equal(run.repairs, 0);++ await run.fireWait();+ assert.equal(run.waiting, false, "the wait gives up rather than spinning for ever");+ assert.equal(run.statuses.at(-1), "error", "which is the screen that carries Retry");+ assert.match(run.errors.at(-1) ?? "", /install or update/);+});++test("our own install or update is waited out without a bound", async () => {+ const run = harness({ ...BUSY, reason: MANAGED_ENVIRONMENT_UPDATING });+ await run.check();+ for (let i = 0; i < POLL_LIMIT + 1; i += 1) await run.fireWait();++ assert.ok(run.waiting, "the app's own mutation always ends, so it is never cut short");+ assert.equal(run.polls(), 0);+ assert.deepEqual(run.errors, []);+ assert.equal(run.repairs, 0);+});++test("a persisted auth failure is not buried under the wait", async () => {+ const run = harness(BUSY, "Desktop auth failed");+ await run.check();++ assert.equal(run.waiting, false);+ assert.equal(run.armedCount, 0);+ assert.equal(run.repairs, 0);+});diff --git a/studio/frontend/tests/startup-messages.test.ts b/studio/frontend/tests/startup-messages.test.tsindex c1b4054e3c1..43315b2ca28 100644--- a/studio/frontend/tests/startup-messages.test.ts+++ b/studio/frontend/tests/startup-messages.test.ts@@ -5,6 +5,7 @@ import {INITIAL_STARTUP_MESSAGE,installProgressMessage,STATUS_MESSAGE_ROTATION_MS,+ UPDATE_STARTUP_MESSAGE,startupMessageFromLog,startupWaitingMessage,} from "../src/components/tauri/startup-messages.ts";@@ -67,3 +68,15 @@ test("nearly done only appears after the backend starts its server", () => {test("status copy rotates every five seconds", () => {assert.equal(STATUS_MESSAGE_ROTATION_MS, 5_000);});++test("the update wait keeps its copy until the backend starts", () => {+ assert.equal(startupWaitingMessage(UPDATE_STARTUP_MESSAGE, 3), "Finishing update...");+ assert.equal(+ startupMessageFromLog(UPDATE_STARTUP_MESSAGE, "unrelated output"),+ UPDATE_STARTUP_MESSAGE,+ );+ assert.equal(+ startupMessageFromLog(UPDATE_STARTUP_MESSAGE, " - Starting server..."),+ "Nearly done...",+ );+});diff --git a/studio/src-tauri/src/commands.rs b/studio/src-tauri/src/commands.rsindex 438cdf0750d..cc2ff7f65c8 100644--- a/studio/src-tauri/src/commands.rs+++ b/studio/src-tauri/src/commands.rs@@ -221,11 +221,27 @@ pub async fn desktop_preflight(app: AppHandle,state: tauri::State<'_, BackendState>,shutdown: tauri::State<'_, ShutdownFlag>,+ update_state: tauri::State<'_, update::UpdateState>,+ install_state: tauri::State<'_, install::InstallState>,diagnostics: tauri::State<'_, DiagnosticsState>,) -> Result<crate::preflight::DesktopPreflightResult, String> {let started = Instant::now();+ // A window reload re-runs this during our own install or update, and the+ // installer phase does not hold the runtime gate. Checked on both sides of the+ // probe: one that ends mid-probe still leaves a half-written reading.+ let mutating = || {+ install::is_install_running(install_state.inner())+ || update::is_update_running(update_state.inner())+ || update::is_repair_running(update_state.inner())+ };+ let mutating_before = mutating();let (result, adopted_watchdog_generation) =crate::preflight::desktop_preflight_result_with_state(state.inner()).await?;+ let result = if mutating_before || mutating() {+ crate::preflight::busy_managed_environment(result)+ } else {+ result+ };diagnostics::record_preflight(&diagnostics, &result);info!(@@ -944,13 +960,7 @@ pub async fn start_managed_repair(return Err("Cannot repair while installation is in progress.".to_string());}- if update_state- .lock()- .map(|s| s.child.is_some())- .unwrap_or(false)- {- return Err("Repair is already running.".to_string());- }+ let _repair = update::RepairInFlight::claim(update_state.inner())?;let diagnostics_state = diagnostics.inner().clone();diff --git a/studio/src-tauri/src/preflight.rs b/studio/src-tauri/src/preflight.rsindex 57e7550e12f..cf282781771 100644--- a/studio/src-tauri/src/preflight.rs+++ b/studio/src-tauri/src/preflight.rs@@ -35,13 +35,12 @@ fn release_auto_repair() -> bool {!cfg!(debug_assertions)}-/// Whether the managed install sits on a profile the app cannot reach:-/// `Unavailable` if the binary was never looked up, `Stale` if it has nowhere to run.+/// Whether the managed install is somewhere repair cannot reach: a profile or+/// path setting it needs, or an environment another install already holds.fn managed_profile_unreachable(managed: &ManagedProbe) -> bool {match managed {ManagedProbe::Unavailable { reason } | ManagedProbe::Stale { reason, .. } => {- // Either context failure: repair needs the same profile or path setting.- managed::is_context_reason(reason)+ managed::blocks_auto_repair(reason)}ManagedProbe::Ready { .. } | ManagedProbe::Missing => false,}@@ -68,6 +67,27 @@ fn stale_reason(managed: &ManagedProbe, reason: &str) -> String {reason.to_string()}+/// While this app's own install, update or repair runs, the probe reads a half-written+/// environment: acting on it as missing, ready or broken would install, start or+/// repair over the running mutation.+pub fn busy_managed_environment(result: DesktopPreflightResult) -> DesktopPreflightResult {+ let disposition = match result.disposition {+ DesktopPreflightDisposition::AttachedReady+ | DesktopPreflightDisposition::OwnedReady+ | DesktopPreflightDisposition::ExternalConflict => return result,+ DesktopPreflightDisposition::OwnedStale => DesktopPreflightDisposition::OwnedStale,+ DesktopPreflightDisposition::NotInstalled+ | DesktopPreflightDisposition::ManagedReady+ | DesktopPreflightDisposition::ManagedStale => DesktopPreflightDisposition::ManagedStale,+ };+ DesktopPreflightResult {+ disposition,+ reason: Some(managed::MANAGED_ENVIRONMENT_UPDATING.to_string()),+ can_auto_repair: false,+ ..result+ }+}+fn managed_bin_for_result(managed: &ManagedProbe) -> Option<PathBuf> {match managed {ManagedProbe::Ready { bin } | ManagedProbe::Stale { bin, .. } => Some(bin.clone()),@@ -101,8 +121,8 @@ fn choose_preflight(managed: ManagedProbe, backend: BackendProbe) -> DesktopPref},ManagedProbe::Stale { bin, reason } => DesktopPreflightResult {disposition: DesktopPreflightDisposition::ManagedStale,- // The repair needs the same home directory, so do not offer it.- can_auto_repair: release_auto_repair() && !managed::is_context_reason(&reason),+ // A busy gate or unreachable context would refuse the repair too.+ can_auto_repair: release_auto_repair() && !managed::blocks_auto_repair(&reason),reason: Some(reason),port: None,managed_bin: Some(bin),@@ -490,6 +510,86 @@ mod tests {}}+ #[test]+ fn a_busy_environment_never_offers_a_repair_to_a_stale_backend() {+ let bin = PathBuf::from("/managed/unsloth");+ let busy = ManagedProbe::Stale {+ bin: bin.clone(),+ reason: managed::MANAGED_ENVIRONMENT_BUSY.to_string(),+ };++ assert!(managed_profile_unreachable(&busy));+ assert!(!stale_auto_repair(&busy));++ let owned = choose_owned_preflight(+ &busy,+ &VerifiedOwnedBackend {+ owner: crate::desktop_backend_owner::test_owner_state("root", "token", 8000),+ port: 8000,+ backend_pid: 2,+ generation: 3,+ readiness: OwnedBackendReadiness::Stale {+ reason: "backend_outdated".to_string(),+ },+ },+ );+ let ownerless = choose_ownerless_spawned_preflight(+ &busy,+ &BackendProbe::Old {+ port: 8000,+ reason: "backend_outdated".to_string(),+ },+ Some(8000),+ );++ for result in [+ owned,+ ownerless,+ choose_preflight(busy, BackendProbe::Missing),+ ] {+ assert!(!result.can_auto_repair, "{result:?}");+ assert_eq!(+ result.reason.as_deref(),+ Some(managed::MANAGED_ENVIRONMENT_BUSY),+ "{result:?}"+ );+ }+ }++ #[test]+ fn our_own_install_makes_every_managed_probe_wait() {+ let probed = |disposition| DesktopPreflightResult {+ disposition,+ reason: Some("cli_unusable".to_string()),+ port: None,+ can_auto_repair: true,+ managed_bin: Some(PathBuf::from("/managed/unsloth")),+ };++ use DesktopPreflightDisposition as D;+ for (probe, waits_as) in [+ (D::NotInstalled, D::ManagedStale),+ (D::ManagedReady, D::ManagedStale),+ (D::ManagedStale, D::ManagedStale),+ (D::OwnedStale, D::OwnedStale),+ ] {+ let busy = busy_managed_environment(probed(probe));+ assert_eq!(busy.disposition, waits_as);+ assert_eq!(+ busy.reason.as_deref(),+ Some(managed::MANAGED_ENVIRONMENT_UPDATING)+ );+ assert!(!busy.can_auto_repair);+ assert_eq!(busy.managed_bin, Some(PathBuf::from("/managed/unsloth")));+ }++ // A backend that answers is not waiting on anything.+ for disposition in [D::AttachedReady, D::OwnedReady, D::ExternalConflict] {+ let untouched = probed(disposition);+ assert_eq!(busy_managed_environment(untouched.clone()), untouched);+ }+ }+#[test]fn repair_is_withheld_from_stale_backends_on_an_unreachable_profile() {let bin = PathBuf::from("/managed/unsloth");diff --git a/studio/src-tauri/src/preflight/managed.rs b/studio/src-tauri/src/preflight/managed.rsindex 0e56338397e..c1ad821e9c7 100644--- a/studio/src-tauri/src/preflight/managed.rs+++ b/studio/src-tauri/src/preflight/managed.rs@@ -53,6 +53,30 @@ pub(super) fn is_context_reason(reason: &str) -> bool {head == WORKING_DIRECTORY_UNAVAILABLE || head == PATH_SETTING_UNRESOLVABLE}+/// The runtime gate was held, so the CLI was never probed. Mirrored in the frontend.+pub(super) const MANAGED_ENVIRONMENT_BUSY: &str = "managed_environment_busy";+/// This app's own install, update or repair is running. Mirrored in the frontend.+pub(super) const MANAGED_ENVIRONMENT_UPDATING: &str = "managed_environment_updating";++pub(super) fn blocks_auto_repair(reason: &str) -> bool {+ reason == MANAGED_ENVIRONMENT_BUSY || is_context_reason(reason)+}++fn unasked_reason(error: &str) -> String {+ if error == MANAGED_ENVIRONMENT_BUSY {+ return error.to_string();+ }+ working_directory_reason().unwrap_or_else(|| WORKING_DIRECTORY_UNAVAILABLE.to_string())+}++fn probe_spawn_error(error: String) -> String {+ if error == crate::process::STUDIO_RUNTIME_GATE_BUSY {+ MANAGED_ENVIRONMENT_BUSY.to_string()+ } else {+ error+ }+}+const FNV64_OFFSET_BASIS: u64 = 0xcbf29ce484222325;const FNV64_PRIME: u64 = 0x100000001b3;const HASHED_MARKER_MAX_BYTES: u64 = 64 * 1024;@@ -407,15 +431,27 @@ async fn run_cli_probe(bin: &Path, args: &[&str]) -> Result<bool, String> {cmd.creation_flags(crate::process::CREATE_NO_WINDOW);}- let Ok(mut child) = crate::process::with_studio_runtime_launch_guard(|| {+ let spawned = crate::process::with_studio_runtime_launch_guard(|| {cmd.spawn().map_err(|error| error.to_string())- }) else {- info!(- "Managed preflight probe {:?} failed to spawn in {}ms",- args,- started.elapsed().as_millis()- );- return Ok(false);+ })+ .map_err(probe_spawn_error);+ let mut child = match spawned {+ Ok(child) => child,+ Err(error) if error == MANAGED_ENVIRONMENT_BUSY => {+ info!(+ "Managed preflight probe {:?} skipped: managed environment is busy",+ args+ );+ return Err(error);+ }+ Err(_) => {+ info!(+ "Managed preflight probe {:?} failed to spawn in {}ms",+ args,+ started.elapsed().as_millis()+ );+ return Ok(false);+ }};let ok = match tokio::time::timeout(Duration::from_secs(10), child.wait()).await {@@ -470,14 +506,23 @@ async fn probe_cli_capability(bin: &Path) -> Result<Option<DesktopCapability>, Scmd.creation_flags(crate::process::CREATE_NO_WINDOW);}- let Ok(mut child) = crate::process::with_studio_runtime_launch_guard(|| {+ let spawned = crate::process::with_studio_runtime_launch_guard(|| {cmd.spawn().map_err(|error| error.to_string())- }) else {- info!(- "Managed desktop-capabilities probe failed to spawn in {}ms",- started.elapsed().as_millis()- );- return Ok(None);+ })+ .map_err(probe_spawn_error);+ let mut child = match spawned {+ Ok(child) => child,+ Err(error) if error == MANAGED_ENVIRONMENT_BUSY => {+ info!("Managed desktop-capabilities probe skipped: managed environment is busy");+ return Err(error);+ }+ Err(_) => {+ info!(+ "Managed desktop-capabilities probe failed to spawn in {}ms",+ started.elapsed().as_millis()+ );+ return Ok(None);+ }};let Some(mut stdout) = child.stdout.take() else {return Ok(None);@@ -587,16 +632,15 @@ pub(super) async fn probe_managed_bin(bin: PathBuf) -> ManagedProbe {// below still skips the heavier desktop-capabilities probe on a hit.match run_cli_probe(&bin, &["-h"]).await {// The CLI was never asked, so do not report a broken install.- Err(_) => {+ Err(error) => {info!(- "Managed preflight: no usable managed context for {:?} in {}ms",+ "Managed preflight: cli not asked for {:?} in {}ms",bin,started.elapsed().as_millis());return ManagedProbe::Stale {bin,- reason: working_directory_reason()- .unwrap_or_else(|| WORKING_DIRECTORY_UNAVAILABLE.to_string()),+ reason: unasked_reason(&error),};}Ok(false) => {@@ -627,16 +671,15 @@ pub(super) async fn probe_managed_bin(bin: PathBuf) -> ManagedProbe {let capability = match probe_cli_capability(&bin).await {Ok(capability) => capability,- Err(_) => {+ Err(error) => {info!(- "Managed preflight: no usable managed context for {:?} in {}ms",+ "Managed preflight: cli not asked for {:?} in {}ms",bin,started.elapsed().as_millis());return ManagedProbe::Stale {bin,- reason: working_directory_reason()- .unwrap_or_else(|| WORKING_DIRECTORY_UNAVAILABLE.to_string()),+ reason: unasked_reason(&error),};}};@@ -956,6 +999,20 @@ mod tests {let _ = fs::remove_dir_all(&venv);}+ #[test]+ fn a_busy_runtime_gate_is_not_a_broken_install() {+ let busy = probe_spawn_error(crate::process::STUDIO_RUNTIME_GATE_BUSY.to_string());+ assert_eq!(busy, MANAGED_ENVIRONMENT_BUSY);+ assert_eq!(unasked_reason(&busy), MANAGED_ENVIRONMENT_BUSY);+ assert!(blocks_auto_repair(&busy));+ assert!(!is_context_reason(&busy));++ let spawn_failure = probe_spawn_error("No such file or directory".to_string());+ assert_eq!(spawn_failure, "No such file or directory");+ assert!(!blocks_auto_repair("cli_unusable"));+ assert!(blocks_auto_repair(WORKING_DIRECTORY_UNAVAILABLE));+ }+#[test]fn a_context_reason_names_the_setting_it_could_not_preserve() {use crate::process::ManagedContextError;diff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rsindex 3667f4c2c10..dd27968d25e 100644--- a/studio/src-tauri/src/process.rs+++ b/studio/src-tauri/src/process.rs@@ -341,6 +341,7 @@ mod appimage_environment_tests {const STUDIO_MANAGED_RUNTIME_MUTEX_PREFIX: &str = "Global\\UnslothStudioManagedEnvironment-";pub(crate) const STUDIO_RUNTIME_GATE_HANDOFF_ENV: &str = "_UNSLOTH_STUDIO_RUNTIME_GATE_HANDOFF";+pub(crate) const STUDIO_RUNTIME_GATE_BUSY: &str = "Unsloth installation is modifying the managed environment. Wait for it to finish, then start the backend again.";const STUDIO_RUNTIME_GATE_ACQUIRE_ENV: &str = "_UNSLOTH_STUDIO_RUNTIME_GATE_ACQUIRE";#[cfg(windows)]@@ -402,10 +403,7 @@ fn acquire_named_studio_runtime_launch_guard(unsafe {let _ = windows_sys::Win32::Foundation::CloseHandle(handle);}- Err(- "Unsloth installation is modifying the managed environment. Wait for it to finish, then start the backend again."- .to_string(),- )+ Err(STUDIO_RUNTIME_GATE_BUSY.to_string())}_ => {let error = std::io::Error::last_os_error();@@ -534,10 +532,7 @@ fn acquire_file_studio_runtime_launch_guard(}let error = std::io::Error::last_os_error();if error.kind() == std::io::ErrorKind::WouldBlock {- return Err(- "Unsloth installation is modifying the managed environment. Wait for it to finish, then start the backend again."- .to_string(),- );+ return Err(STUDIO_RUNTIME_GATE_BUSY.to_string());}Err(format!("Could not acquire the Unsloth Studio runtime lock: {error}"))}diff --git a/studio/src-tauri/src/update.rs b/studio/src-tauri/src/update.rsindex eb7743c06fa..24a74d195f5 100644--- a/studio/src-tauri/src/update.rs+++ b/studio/src-tauri/src/update.rs@@ -13,6 +13,7 @@ pub struct UpdateProcess {pub child: Option<Box<dyn ChildWrapper + Send>>,pub intentional_stop: bool,pub current_attempt: Option<AttemptLog>,+ repair_in_flight: bool,}pub type UpdateState = Arc<Mutex<UpdateProcess>>;@@ -233,7 +234,9 @@ fn stream_output(fn wait_for_exit(state: &UpdateState) -> Result<(ExitStatus, bool), String> {const MAX_WAIT_ITERATIONS: u32 = 72_000; // 2h at 100ms intervalsfor _ in 0..MAX_WAIT_ITERATIONS {- let mut update = state.lock().map_err(|e| e.to_string())?;+ let mut update = state+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());let intentional = update.intentional_stop;match update.child.as_mut() {@@ -412,6 +415,39 @@ pub fn is_update_running(state: &UpdateState) -> bool {.unwrap_or(false)}+pub fn is_repair_running(state: &UpdateState) -> bool {+ state+ .lock()+ .map(|update| update.repair_in_flight)+ .unwrap_or(false)+}++/// Held for a whole repair: between its update and installer phases no child runs.+pub struct RepairInFlight(UpdateState);++impl RepairInFlight {+ pub fn claim(state: &UpdateState) -> Result<Self, String> {+ let mut update = state+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ if update.child.is_some() || update.repair_in_flight {+ return Err("An update or repair is already running.".to_string());+ }+ update.repair_in_flight = true;+ Ok(Self(state.clone()))+ }+}++impl Drop for RepairInFlight {+ fn drop(&mut self) {+ let mut update = self+ .0+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ update.repair_in_flight = false;+ }+}+pub fn record_update_intentional_stop(state: &UpdateState, diagnostics: &DiagnosticsState) {let attempt = state.lock()@@ -531,6 +567,18 @@ mod tests {use super::*;use std::io::Cursor;+ #[test]+ fn a_repair_is_running_until_its_claim_drops() {+ let state = new_update_state();+ let repair = RepairInFlight::claim(&state).unwrap();+ assert!(is_repair_running(&state));+ assert!(RepairInFlight::claim(&state).is_err());++ drop(repair);+ assert!(!is_repair_running(&state));+ assert!(RepairInFlight::claim(&state).is_ok());+ }+#[test]fn tauri_backend_update_skips_the_web_frontend_build() {use std::ffi::OsStr;