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.

Windows: start the backend from a usable folder on login autostart (#8575)

Daniel Han715535d1c5af
diff --git a/.github/workflows/cross-platform-parity-ci.yml b/.github/workflows/cross-platform-parity-ci.yml
index 8d9b554508c..88afed5eed6 100644
--- a/.github/workflows/cross-platform-parity-ci.yml
+++ b/.github/workflows/cross-platform-parity-ci.yml
@@ -33,6 +33,9 @@ on:
- 'install.sh'
- 'install.ps1'
- 'unsloth_cli/__init__.py'
+ # The System32 working-directory guard the CLI callback runs; all of that
+ # logic lives here now, so an edit to it alone must still run this leg.
+ - 'unsloth_cli/_system_dir_guard.py'
# test_installer_profile_hardening.py asserts this module directly (unconditional
# -NoProfile, the proxy handoff), so a change to it has to run here.
- 'unsloth_cli/commands/studio.py'
@@ -83,6 +86,9 @@ on:
- 'install.sh'
- 'install.ps1'
- 'unsloth_cli/__init__.py'
+ # The System32 working-directory guard the CLI callback runs; all of that
+ # logic lives here now, so an edit to it alone must still run this leg.
+ - 'unsloth_cli/_system_dir_guard.py'
# test_installer_profile_hardening.py asserts this module directly (unconditional
# -NoProfile, the proxy handoff), so a change to it has to run here.
- 'unsloth_cli/commands/studio.py'
diff --git a/.github/workflows/studio-update-smoke.yml b/.github/workflows/studio-update-smoke.yml
index 5a34440f743..2f005d7a186 100644
--- a/.github/workflows/studio-update-smoke.yml
+++ b/.github/workflows/studio-update-smoke.yml
@@ -21,6 +21,8 @@ on:
- 'studio/install_llama_prebuilt.py'
- 'studio/backend/requirements/**'
- 'unsloth_cli/commands/studio.py'
+ - 'unsloth_cli/__init__.py'
+ - 'unsloth_cli/_system_dir_guard.py'
- 'pyproject.toml'
- '.github/workflows/studio-update-smoke.yml'
# The install step in this workflow is `uses:` on that composite action,
diff --git a/.github/workflows/studio-windows-update-smoke.yml b/.github/workflows/studio-windows-update-smoke.yml
index 7964badffdc..246db5eb553 100644
--- a/.github/workflows/studio-windows-update-smoke.yml
+++ b/.github/workflows/studio-windows-update-smoke.yml
@@ -32,6 +32,8 @@ on:
- 'studio/install_llama_prebuilt.py'
- 'studio/backend/requirements/**'
- 'unsloth_cli/commands/studio.py'
+ - 'unsloth_cli/__init__.py'
+ - 'unsloth_cli/_system_dir_guard.py'
- 'pyproject.toml'
- '.github/workflows/studio-windows-update-smoke.yml'
push:
diff --git a/cli.py b/cli.py
index 534babed2c6..c3fd954b52c 100644
--- a/cli.py
+++ b/cli.py
@@ -1,6 +1,14 @@
# 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 sys
+
+# unsloth_cli only runs its console-script setup (stream encoding, `-np<N>`,
+# the Windows folder guard) for argv[0] == "unsloth", and it must precede the
+# command imports: commands.studio resolves STUDIO_HOME at import time.
+if __name__ == "__main__":
+ sys.argv[0] = "unsloth"
+
from unsloth_cli import app
if __name__ == "__main__":
diff --git a/studio/frontend/src/hooks/backend-preflight-message.ts b/studio/frontend/src/hooks/backend-preflight-message.ts
new file mode 100644
index 00000000000..06a7665086b
--- /dev/null
+++ b/studio/frontend/src/hooks/backend-preflight-message.ts
@@ -0,0 +1,42 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+/** Preflight reported a stale install; say which kind, since the fixes differ. */
+
+/// The install is fine, the folder it must run from is not reachable.
+/// Mirrors WORKING_DIRECTORY_UNAVAILABLE in studio/src-tauri/src/preflight/managed.rs.
+export const WORKING_DIRECTORY_UNAVAILABLE = "working_directory_unavailable";
+
+/// The folder is reachable; a path setting the user wrote is not resolvable.
+/// Mirrors PATH_SETTING_UNRESOLVABLE in studio/src-tauri/src/preflight/managed.rs.
+export const PATH_SETTING_UNRESOLVABLE = "path_setting_unresolvable";
+
+export function preflightStaleMessage(
+ disposition: string,
+ reason: string | null,
+): string {
+ // The backend appends the setting it could not preserve, as `reason:NAME`, so
+ // the discriminator is the part before the colon and the name is the rest.
+ const [kind, setting] = (reason ?? "").split(":", 2);
+ // Not an install problem: the home folder itself is unreachable, and updating
+ // needs the same folder. The roaming-profile cause is a Windows one, but this
+ // reason reaches every platform (`home_dir_available()` is probed ungated), so
+ // it is offered rather than asserted.
+ if (kind === WORKING_DIRECTORY_UNAVAILABLE) {
+ const cause =
+ typeof navigator !== "undefined" && /Win/i.test(navigator.platform ?? "")
+ ? " This usually means a network or roaming profile is not available yet."
+ : "";
+ return `Unsloth cannot reach your user folder, so it has nowhere to run from.${cause} Reconnect and try again.`;
+ }
+ // Also not an install problem, and not the folder either: one of Unsloth's own
+ // path settings names somewhere unresolvable, so the value is the fix.
+ if (kind === PATH_SETTING_UNRESOLVABLE) {
+ const which = setting ? `${setting} points` : "One of Unsloth's folder settings points";
+ return `${which} somewhere that cannot be resolved, so Unsloth has nowhere safe to run from. Set it to a full path, such as D:\\unsloth-cache, and try again.`;
+ }
+ if (disposition === "owned_stale") {
+ return "Desktop-owned Unsloth backend is too old for this desktop app. Run `unsloth studio update`, then restart Unsloth.";
+ }
+ return "Managed Unsloth install is too old. Run `unsloth studio update`.";
+}
diff --git a/studio/frontend/src/hooks/use-tauri-backend.ts b/studio/frontend/src/hooks/use-tauri-backend.ts
index 566fd1778a1..a9679338b54 100644
--- a/studio/frontend/src/hooks/use-tauri-backend.ts
+++ b/studio/frontend/src/hooks/use-tauri-backend.ts
@@ -9,6 +9,7 @@ import {
useSyncExternalStore,
} from "react";
import { isTauri, setApiBase } from "@/lib/api-base";
+import { preflightStaleMessage } from "@/hooks/backend-preflight-message";
import {
copySupportDiagnostics,
type CopySupportDiagnosticsResult,
@@ -276,9 +277,7 @@ export function useTauriBackend() {
await startRepair();
} else {
setBackendError(
- preflight.disposition === "owned_stale"
- ? "Desktop-owned Unsloth backend is too old for this desktop app. Run `unsloth studio update`, then restart Unsloth."
- : "Managed Unsloth install is too old. Run `unsloth studio update`.",
+ preflightStaleMessage(preflight.disposition, preflight.reason),
);
}
return;
diff --git a/studio/frontend/tests/backend-preflight-message.test.ts b/studio/frontend/tests/backend-preflight-message.test.ts
new file mode 100644
index 00000000000..6b506813dca
--- /dev/null
+++ b/studio/frontend/tests/backend-preflight-message.test.ts
@@ -0,0 +1,99 @@
+// 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";
+
+// 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 {
+ WORKING_DIRECTORY_UNAVAILABLE,
+ PATH_SETTING_UNRESOLVABLE,
+ preflightStaleMessage,
+} from "../src/hooks/backend-preflight-message.ts";
+
+const UNREACHABLE_PROFILE = /cannot reach your user folder/;
+const UPDATE_ADVICE = /unsloth studio update/;
+const MANAGED_TOO_OLD = /Managed Unsloth install is too old/;
+const OWNED_TOO_OLD = /Desktop-owned Unsloth backend is too old/;
+const TOO_OLD = /too old/;
+
+test("an unreachable profile is not reported as an outdated install", () => {
+ for (const disposition of ["managed_stale", "owned_stale"]) {
+ const message = preflightStaleMessage(
+ disposition,
+ WORKING_DIRECTORY_UNAVAILABLE,
+ );
+ assert.match(message, UNREACHABLE_PROFILE);
+ // Updating needs the same folder, so it must not be the advice given.
+ assert.doesNotMatch(message, UPDATE_ADVICE);
+ }
+});
+
+test("a genuinely stale install still says to update", () => {
+ assert.match(
+ preflightStaleMessage("managed_stale", "old cli"),
+ MANAGED_TOO_OLD,
+ );
+ assert.match(
+ preflightStaleMessage("owned_stale", "backend_outdated"),
+ OWNED_TOO_OLD,
+ );
+ assert.match(preflightStaleMessage("managed_stale", null), TOO_OLD);
+});
+
+test("the reason string matches the one the Rust side sends", () => {
+ assert.equal(WORKING_DIRECTORY_UNAVAILABLE, "working_directory_unavailable");
+});
+
+test("the roaming-profile cause is offered on Windows and withheld elsewhere", () => {
+ // The probe calls `home_dir_available()` ungated, so this reason reaches Linux
+ // and macOS, where the same symptom is an unmounted home or a permissions
+ // problem rather than a roaming profile.
+ const original = globalThis.navigator;
+ const withPlatform = (platform: string) => {
+ Object.defineProperty(globalThis, "navigator", {
+ value: { platform },
+ configurable: true,
+ });
+ return preflightStaleMessage("managed_stale", WORKING_DIRECTORY_UNAVAILABLE);
+ };
+ try {
+ assert.match(withPlatform("Win32"), /roaming profile/);
+ for (const platform of ["Linux x86_64", "MacIntel"]) {
+ const message = withPlatform(platform);
+ assert.doesNotMatch(message, /roaming profile/);
+ // The symptom and the remedy still have to survive the trim.
+ assert.match(message, UNREACHABLE_PROFILE);
+ assert.match(message, /Reconnect and try again/);
+ }
+ } finally {
+ Object.defineProperty(globalThis, "navigator", {
+ value: original,
+ configurable: true,
+ });
+ }
+});
+
+test("a path setting that cannot be resolved is told apart from an unreachable folder", () => {
+ const message = preflightStaleMessage("managed_stale", PATH_SETTING_UNRESOLVABLE);
+ assert.match(message, /folder settings/);
+ // Not the profile, and not something an update can fix: the value is the fix.
+ assert.doesNotMatch(message, /user folder/);
+ assert.doesNotMatch(message, /update/);
+});
+
+test("the setting that could not be resolved is named", () => {
+ // "one of Unsloth's folder settings" is not something anyone can act on, so
+ // the backend appends the name and the message uses it.
+ const named = preflightStaleMessage(
+ "managed_stale",
+ `${PATH_SETTING_UNRESOLVABLE}:HF_HOME`,
+ );
+ assert.match(named, /^HF_HOME points somewhere that cannot be resolved/);
+ assert.match(named, /full path/);
+ // Without a name it still reads as a sentence, and still is not an update.
+ const unnamed = preflightStaleMessage("managed_stale", PATH_SETTING_UNRESOLVABLE);
+ assert.match(unnamed, /One of Unsloth's folder settings points/);
+ assert.doesNotMatch(unnamed, UPDATE_ADVICE);
+});
diff --git a/studio/src-tauri/src/commands.rs b/studio/src-tauri/src/commands.rs
index d28b818b6dd..347e9d758bb 100644
--- a/studio/src-tauri/src/commands.rs
+++ b/studio/src-tauri/src/commands.rs
@@ -153,6 +153,11 @@ pub async fn check_install_status() -> bool {
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null());
+ if let Err(error) = process::apply_managed_cli_context_tokio(&mut cmd) {
+ warn!("Install check: no usable working directory: {}", error);
+ return false;
+ }
+
#[cfg(windows)]
{
cmd.creation_flags(crate::process::CREATE_NO_WINDOW);
diff --git a/studio/src-tauri/src/desktop_auth.rs b/studio/src-tauri/src/desktop_auth.rs
index 3af08945ff9..f3b0c046e4a 100644
--- a/studio/src-tauri/src/desktop_auth.rs
+++ b/studio/src-tauri/src/desktop_auth.rs
@@ -230,6 +230,8 @@ async fn provision_desktop_auth() -> Result<(), String> {
cmd.args(["studio", "provision-desktop-auth"])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::piped());
+ crate::process::apply_managed_cli_context_tokio(&mut cmd)
+ .map_err(|error| format!("Desktop auth provisioning failed: {}", error))?;
#[cfg(target_os = "linux")]
crate::process::scrub_appimage_python_env_tokio(&mut cmd);
diff --git a/studio/src-tauri/src/install.rs b/studio/src-tauri/src/install.rs
index 686ea1d0385..d451c96c4e2 100644
--- a/studio/src-tauri/src/install.rs
+++ b/studio/src-tauri/src/install.rs
@@ -390,13 +390,10 @@ fn spawn_script(
install.intentional_stop = false;
install.needed_packages.clear();
- // Scripts create ~/.unsloth/studio/ themselves, but need a writable cwd.
- let home = dirs::home_dir().ok_or("Could not determine home directory")?;
- let work_dir = home.join(".unsloth");
- if !work_dir.exists() {
- std::fs::create_dir_all(&work_dir)
- .map_err(|e| format!("Failed to create {}: {}", work_dir.display(), e))?;
- }
+ // Scripts create ~/.unsloth/studio/ themselves but need a writable cwd, and
+ // unlike the CLI children they always want ~/.unsloth. No Windows-directory
+ // rejection: install.ps1 detects a SYSTEM profile itself and explains it.
+ let work_dir = crate::process::install_working_dir(dirs::home_dir())?;
#[cfg(unix)]
let mut cmd = Command::new("bash");
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index f849c5f1efd..231c1ce9c4b 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -1886,9 +1886,9 @@ mod tests {
#[cfg(target_os = "linux")]
const BID: &str = "ai.unsloth.studio";
- // Only XDG_DATA_HOME is swapped, and nothing else in the crate reads it, so the
- // tests running beside these stay clear. HOME is left alone for the same reason:
- // `dirs::home_dir` is all over this crate.
+ // Only XDG_DATA_HOME is swapped, and it is read elsewhere now (a relocated CLI
+ // child pins it), so the swap holds the crate-wide env lock and readers take it
+ // too. HOME is left alone: `dirs::home_dir` is all over this crate.
#[cfg(target_os = "linux")]
fn with_xdg_data_home<T>(value: &str, f: impl FnOnce() -> T) -> T {
// The crate-wide lock, not one of this module's own: the path policy
diff --git a/studio/src-tauri/src/preflight.rs b/studio/src-tauri/src/preflight.rs
index 2e348b778a1..2d3c14ae257 100644
--- a/studio/src-tauri/src/preflight.rs
+++ b/studio/src-tauri/src/preflight.rs
@@ -34,10 +34,43 @@ 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.
+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)
+ }
+ ManagedProbe::Ready { .. } | ManagedProbe::Missing => false,
+ }
+}
+
+/// Repair reinstalls through the managed CLI, which needs the profile the probe
+/// just failed to reach, and stops a backend that still answers to do it.
+fn stale_auto_repair(managed: &ManagedProbe) -> bool {
+ release_auto_repair() && !managed_profile_unreachable(managed)
+}
+
+/// What to tell the user about a stale backend: the unreachable profile wins,
+/// since the frontend answers every other reason with "update", which needs it.
+fn stale_reason(managed: &ManagedProbe, reason: &str) -> String {
+ if managed_profile_unreachable(managed) {
+ info!("Desktop preflight: stale backend ({reason}) reported as an unusable managed context");
+ return match managed {
+ ManagedProbe::Unavailable { reason } | ManagedProbe::Stale { reason, .. } => {
+ reason.clone()
+ }
+ _ => managed::WORKING_DIRECTORY_UNAVAILABLE.to_string(),
+ };
+ }
+ reason.to_string()
+}
+
fn managed_bin_for_result(managed: &ManagedProbe) -> Option<PathBuf> {
match managed {
ManagedProbe::Ready { bin } | ManagedProbe::Stale { bin, .. } => Some(bin.clone()),
- ManagedProbe::Missing => None,
+ ManagedProbe::Missing | ManagedProbe::Unavailable { .. } => None,
}
}
@@ -67,9 +100,10 @@ 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),
reason: Some(reason),
port: None,
- can_auto_repair: release_auto_repair(),
managed_bin: Some(bin),
},
ManagedProbe::Missing => DesktopPreflightResult {
@@ -79,6 +113,14 @@ fn choose_preflight(managed: ManagedProbe, backend: BackendProbe) -> DesktopPref
can_auto_repair: false,
managed_bin: None,
},
+ // Not "install Unsloth": the install may exist on an unmounted profile.
+ ManagedProbe::Unavailable { reason } => DesktopPreflightResult {
+ disposition: DesktopPreflightDisposition::ManagedStale,
+ reason: Some(reason),
+ port: None,
+ can_auto_repair: false,
+ managed_bin: None,
+ },
},
}
}
@@ -101,9 +143,9 @@ fn choose_owned_preflight(
},
OwnedBackendReadiness::Stale { reason } => DesktopPreflightResult {
disposition: DesktopPreflightDisposition::OwnedStale,
- reason: Some(reason.clone()),
+ reason: Some(stale_reason(managed, reason)),
port: Some(owned.port),
- can_auto_repair: release_auto_repair(),
+ can_auto_repair: stale_auto_repair(managed),
managed_bin: managed_bin_for_result(managed),
},
}
@@ -154,9 +196,9 @@ fn choose_ownerless_spawned_preflight(
(Some(owned_port), BackendProbe::Old { port, reason }) if owned_port == *port => {
DesktopPreflightResult {
disposition: DesktopPreflightDisposition::OwnedStale,
- reason: Some(reason.clone()),
+ reason: Some(stale_reason(managed, reason)),
port: Some(*port),
- can_auto_repair: release_auto_repair(),
+ can_auto_repair: stale_auto_repair(managed),
managed_bin: managed_bin_for_result(managed),
}
}
@@ -410,6 +452,18 @@ mod tests {
false,
None,
),
+ // An unreachable profile is not a missing install.
+ (
+ ManagedProbe::Unavailable {
+ reason: managed::WORKING_DIRECTORY_UNAVAILABLE.to_string(),
+ },
+ BackendProbe::Missing,
+ DesktopPreflightDisposition::ManagedStale,
+ None,
+ Some(managed::WORKING_DIRECTORY_UNAVAILABLE),
+ false,
+ None,
+ ),
];
for (managed, backend, disposition, port, reason, can_auto_repair, managed_bin) in cases {
@@ -422,6 +476,84 @@ mod tests {
}
}
+ #[test]
+ fn repair_is_withheld_from_stale_backends_on_an_unreachable_profile() {
+ let bin = PathBuf::from("/managed/unsloth");
+ let unreachable = [
+ ManagedProbe::Unavailable {
+ reason: managed::WORKING_DIRECTORY_UNAVAILABLE.to_string(),
+ },
+ ManagedProbe::Stale {
+ bin: bin.clone(),
+ reason: managed::WORKING_DIRECTORY_UNAVAILABLE.to_string(),
+ },
+ ];
+ let reachable = [
+ ManagedProbe::Ready { bin: bin.clone() },
+ ManagedProbe::Missing,
+ ManagedProbe::Stale {
+ bin: bin.clone(),
+ reason: "cli_unusable".to_string(),
+ },
+ ];
+
+ let owned = |managed: &ManagedProbe| {
+ choose_owned_preflight(
+ managed,
+ &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 = |managed: &ManagedProbe| {
+ choose_ownerless_spawned_preflight(
+ managed,
+ &BackendProbe::Old {
+ port: 8000,
+ reason: "backend_outdated".to_string(),
+ },
+ Some(8000),
+ )
+ };
+
+ for managed in &unreachable {
+ assert!(managed_profile_unreachable(managed), "{managed:?}");
+ assert!(!stale_auto_repair(managed), "{managed:?}");
+ // Repair would stop a working backend for an install that cannot run.
+ for result in [owned(managed), ownerless(managed)] {
+ assert_eq!(result.disposition, DesktopPreflightDisposition::OwnedStale);
+ assert_eq!(result.port, Some(8000));
+ assert!(!result.can_auto_repair, "{managed:?}");
+ // The frontend answers "backend_outdated" with "update", which needs
+ // the profile.
+ assert_eq!(
+ result.reason.as_deref(),
+ Some(managed::WORKING_DIRECTORY_UNAVAILABLE),
+ "{managed:?}"
+ );
+ }
+ }
+
+ for managed in &reachable {
+ assert!(!managed_profile_unreachable(managed), "{managed:?}");
+ assert_eq!(stale_auto_repair(managed), release_auto_repair());
+ for result in [owned(managed), ownerless(managed)] {
+ assert_eq!(result.can_auto_repair, release_auto_repair(), "{managed:?}");
+ assert_eq!(
+ result.reason.as_deref(),
+ Some("backend_outdated"),
+ "{managed:?}"
+ );
+ }
+ }
+ }
+
#[test]
fn external_conflict_blocks_managed_flow() {
let result = choose_preflight(
diff --git a/studio/src-tauri/src/preflight/managed.rs b/studio/src-tauri/src/preflight/managed.rs
index 0d7efbd0fb5..9f00a0df293 100644
--- a/studio/src-tauri/src/preflight/managed.rs
+++ b/studio/src-tauri/src/preflight/managed.rs
@@ -14,6 +14,46 @@ use tokio::process::Command;
// 3: the cached capability gained studio_install_ok / studio_install_reason.
const MANAGED_CAPABILITY_CACHE_SCHEMA: u16 = 3;
+/// The install is fine; the directory its children must run from is not reachable.
+pub(super) const WORKING_DIRECTORY_UNAVAILABLE: &str = "working_directory_unavailable";
+/// The profile is reachable but a user-written path setting is not resolvable,
+/// so reinstalling hits the same wall. Mirrored in the frontend message map.
+pub(super) const PATH_SETTING_UNRESOLVABLE: &str = "path_setting_unresolvable";
+
+/// The reason a managed context failure is reported under, with the setting that
+/// caused it where there is one: "one of Unsloth's folder settings" is not
+/// something a user can act on, and every pin failure names the setting it could
+/// not preserve. The name only, never the value, since this reaches the window.
+pub(super) fn context_reason(error: &crate::process::ManagedContextError) -> String {
+ match error {
+ crate::process::ManagedContextError::WorkingDirectory(_) => {
+ WORKING_DIRECTORY_UNAVAILABLE.to_string()
+ }
+ crate::process::ManagedContextError::PathSetting(detail) => {
+ match setting_name(detail) {
+ Some(name) => format!("{PATH_SETTING_UNRESOLVABLE}:{name}"),
+ None => PATH_SETTING_UNRESOLVABLE.to_string(),
+ }
+ }
+ }
+}
+
+/// The leading token of a pin failure, when it looks like an environment name.
+fn setting_name(detail: &str) -> Option<&str> {
+ let name = detail.split_whitespace().next()?;
+ let named = !name.is_empty()
+ && name
+ .chars()
+ .all(|c| c.is_ascii_uppercase() || c.is_ascii_digit() || c == '_');
+ named.then_some(name)
+}
+
+/// Whether the reason is a context the app cannot build, not a repairable install.
+pub(super) fn is_context_reason(reason: &str) -> bool {
+ let head = reason.split(':').next().unwrap_or(reason);
+ head == WORKING_DIRECTORY_UNAVAILABLE || head == PATH_SETTING_UNRESOLVABLE
+}
+
const FNV64_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
const FNV64_PRIME: u64 = 0x100000001b3;
const HASHED_MARKER_MAX_BYTES: u64 = 64 * 1024;
@@ -302,11 +342,22 @@ fn write_cached_capability(fingerprint: &ManagedBinFingerprint, capability: &Des
}
}
-async fn run_cli_probe(bin: &Path, args: &[&str]) -> bool {
+async fn run_cli_probe(bin: &Path, args: &[&str]) -> Result<bool, String> {
let started = Instant::now();
let mut cmd = Command::new(bin);
cmd.args(args).stdout(Stdio::null()).stderr(Stdio::null());
+ // Reported, not folded into `false`: the CLI never ran, so calling it broken
+ // would start a repair needing the same context. Re-checking afterwards is not
+ // enough: a context that recovers in between makes an untested install look bad.
+ if let Err(error) = crate::process::apply_managed_cli_context_tokio(&mut cmd) {
+ info!(
+ "Managed preflight probe {:?} has no usable working directory: {}",
+ args, error
+ );
+ return Err(error);
+ }
+
#[cfg(target_os = "linux")]
crate::process::scrub_appimage_python_env_tokio(&mut cmd);
@@ -329,7 +380,7 @@ async fn run_cli_probe(bin: &Path, args: &[&str]) -> bool {
args,
started.elapsed().as_millis()
);
- return false;
+ return Ok(false);
};
let ok = match tokio::time::timeout(Duration::from_secs(10), child.wait()).await {
@@ -346,16 +397,25 @@ async fn run_cli_probe(bin: &Path, args: &[&str]) -> bool {
ok,
started.elapsed().as_millis()
);
- ok
+ Ok(ok)
}
-async fn probe_cli_capability(bin: &Path) -> Option<DesktopCapability> {
+async fn probe_cli_capability(bin: &Path) -> Result<Option<DesktopCapability>, String> {
let started = Instant::now();
let mut cmd = Command::new(bin);
cmd.args(["studio", "desktop-capabilities", "--json"])
.stdout(Stdio::piped())
.stderr(Stdio::null());
+ // As above: a context that cannot be built is not a probe result.
+ if let Err(error) = crate::process::apply_managed_cli_context_tokio(&mut cmd) {
+ info!(
+ "Managed desktop-capabilities probe has no usable working directory: {}",
+ error
+ );
+ return Err(error);
+ }
+
#[cfg(target_os = "linux")]
crate::process::scrub_appimage_python_env_tokio(&mut cmd);
@@ -377,9 +437,11 @@ async fn probe_cli_capability(bin: &Path) -> Option<DesktopCapability> {
"Managed desktop-capabilities probe failed to spawn in {}ms",
started.elapsed().as_millis()
);
- return None;
+ return Ok(None);
+ };
+ let Some(mut stdout) = child.stdout.take() else {
+ return Ok(None);
};
- let mut stdout = child.stdout.take()?;
match tokio::time::timeout(Duration::from_secs(10), child.wait()).await {
Ok(Ok(status)) if status.success() => {}
@@ -390,20 +452,20 @@ async fn probe_cli_capability(bin: &Path) -> Option<DesktopCapability> {
"Managed desktop-capabilities probe timed out in {}ms",
started.elapsed().as_millis()
);
- return None;
+ return Ok(None);
}
_ => {
info!(
"Managed desktop-capabilities probe exited unsuccessfully in {}ms",
started.elapsed().as_millis()
);
- return None;
+ return Ok(None);
}
}
let mut output = Vec::new();
if stdout.read_to_end(&mut output).await.is_err() {
- return None;
+ return Ok(None);
}
let capability = serde_json::from_slice::<DesktopCapability>(&output).ok();
@@ -412,7 +474,7 @@ async fn probe_cli_capability(bin: &Path) -> Option<DesktopCapability> {
capability.is_some(),
started.elapsed().as_millis()
);
- capability
+ Ok(capability)
}
fn desktop_capability_stale_reason(capability: &DesktopCapability) -> Option<String> {
@@ -451,24 +513,65 @@ fn desktop_capability_ready(capability: &DesktopCapability) -> bool {
desktop_capability_stale_reason(capability).is_none()
}
+/// The reason an unbuildable context is reported under, if that is what went
+/// wrong. Checked after a probe that did run and failed anyway.
+fn working_directory_reason() -> Option<String> {
+ // The whole context: an unresolvable override fails the same spawn, and is a
+ // different thing to fix.
+ let error = crate::process::managed_cli_context_error()?;
+ info!("Managed preflight: managed context unavailable: {error}");
+ Some(context_reason(&error))
+}
+
pub(super) async fn probe_managed_bin(bin: PathBuf) -> ManagedProbe {
let started = Instant::now();
+
+ // An unmounted roaming profile fails every probe below, which is not a broken
+ // install: "cli_unusable" would start a repair needing the same directory.
+ if let Some(error) = crate::process::managed_cli_context_error() {
+ info!(
+ "Managed preflight: no usable managed context for {:?}: {}",
+ bin, error
+ );
+ return ManagedProbe::Stale {
+ bin,
+ reason: context_reason(&error),
+ };
+ }
+
// Always verify the managed CLI actually launches before trusting the cache.
// A matching capability fingerprint does not prove the binary can still run:
// its venv interpreter or a runtime dependency can be broken while the
// path/size/mtime/markers are unchanged, so the -h probe runs first and a
// non-launchable install is reported Stale for repair. The capability cache
// below still skips the heavier desktop-capabilities probe on a hit.
- if !run_cli_probe(&bin, &["-h"]).await {
- info!(
- "Managed preflight: cli unusable for {:?} in {}ms",
- bin,
- started.elapsed().as_millis()
- );
- return ManagedProbe::Stale {
- bin,
- reason: "cli_unusable".to_string(),
- };
+ match run_cli_probe(&bin, &["-h"]).await {
+ // The CLI was never asked, so do not report a broken install.
+ Err(_) => {
+ info!(
+ "Managed preflight: no usable managed context for {:?} in {}ms",
+ bin,
+ started.elapsed().as_millis()
+ );
+ return ManagedProbe::Stale {
+ bin,
+ reason: working_directory_reason()
+ .unwrap_or_else(|| WORKING_DIRECTORY_UNAVAILABLE.to_string()),
+ };
+ }
+ Ok(false) => {
+ info!(
+ "Managed preflight: cli unusable for {:?} in {}ms",
+ bin,
+ started.elapsed().as_millis()
+ );
+ // The profile can drop between the check above and the probe, so ask again.
+ return ManagedProbe::Stale {
+ bin,
+ reason: working_directory_reason().unwrap_or_else(|| "cli_unusable".to_string()),
+ };
+ }
+ Ok(true) => {}
}
if let Some(fingerprint) = managed_bin_fingerprint(&bin) {
@@ -482,7 +585,21 @@ pub(super) async fn probe_managed_bin(bin: PathBuf) -> ManagedProbe {
}
}
- let capability = probe_cli_capability(&bin).await;
+ let capability = match probe_cli_capability(&bin).await {
+ Ok(capability) => capability,
+ Err(_) => {
+ info!(
+ "Managed preflight: no usable managed context for {:?} in {}ms",
+ bin,
+ started.elapsed().as_millis()
+ );
+ return ManagedProbe::Stale {
+ bin,
+ reason: working_directory_reason()
+ .unwrap_or_else(|| WORKING_DIRECTORY_UNAVAILABLE.to_string()),
+ };
+ }
+ };
if let Some(capability) = capability {
if let Some(fingerprint) = managed_bin_fingerprint(&bin) {
write_cached_capability(&fingerprint, &capability);
@@ -514,7 +631,8 @@ pub(super) async fn probe_managed_bin(bin: PathBuf) -> ManagedProbe {
);
ManagedProbe::Stale {
bin,
- reason: "desktop_capability_probe_failed".to_string(),
+ reason: working_directory_reason()
+ .unwrap_or_else(|| "desktop_capability_probe_failed".to_string()),
}
}
@@ -522,7 +640,17 @@ pub(super) async fn probe_managed_install() -> ManagedProbe {
let started = Instant::now();
let result = match crate::process::find_unsloth_binary() {
Some(bin) => probe_managed_bin(bin).await,
- None => ManagedProbe::Missing,
+ // The managed install lives under the profile, so an unreachable one looks
+ // like no install. Say which, or a late network profile sends them to reinstall.
+ None => match crate::process::home_dir_available() {
+ Ok(()) => ManagedProbe::Missing,
+ Err(error) => {
+ info!("Managed preflight: {}", error);
+ ManagedProbe::Unavailable {
+ reason: WORKING_DIRECTORY_UNAVAILABLE.to_string(),
+ }
+ }
+ },
};
info!(
"Managed preflight: install probe result {:?} in {}ms",
@@ -751,4 +879,26 @@ mod tests {
);
let _ = fs::remove_dir_all(&venv);
}
+
+ #[test]
+ fn a_context_reason_names_the_setting_it_could_not_preserve() {
+ use crate::process::ManagedContextError;
+ // Every pin failure names the setting first, and the window needs that
+ // name: "one of Unsloth's folder settings" is not something to act on.
+ let reason = context_reason(&ManagedContextError::PathSetting(
+ "HF_HOME names a path this machine cannot resolve".to_string(),
+ ));
+ assert_eq!(reason, "path_setting_unresolvable:HF_HOME");
+ assert!(is_context_reason(&reason));
+ // The name is carried, never the value or the sentence around it.
+ assert!(!reason.contains("cannot resolve"));
+ // A failure that does not start with a setting name still classifies.
+ let bare = context_reason(&ManagedContextError::PathSetting(
+ "the environment block is too long".to_string(),
+ ));
+ assert_eq!(bare, PATH_SETTING_UNRESOLVABLE);
+ assert!(is_context_reason(&bare));
+ assert!(is_context_reason(WORKING_DIRECTORY_UNAVAILABLE));
+ assert!(!is_context_reason("cli_unusable"));
+ }
}
diff --git a/studio/src-tauri/src/preflight/types.rs b/studio/src-tauri/src/preflight/types.rs
index 56884061792..88ba8661346 100644
--- a/studio/src-tauri/src/preflight/types.rs
+++ b/studio/src-tauri/src/preflight/types.rs
@@ -33,6 +33,9 @@ pub(super) enum ManagedProbe {
Missing,
Ready { bin: PathBuf },
Stale { bin: PathBuf, reason: String },
+ /// The install could not be looked at, rather than found wanting: no binary
+ /// path to report and nothing to repair until the profile is back.
+ Unavailable { reason: String },
}
#[derive(Debug, Clone, PartialEq, Eq)]
diff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rs
index ad3f618ce5b..f5344e1fa22 100644
--- a/studio/src-tauri/src/process.rs
+++ b/studio/src-tauri/src/process.rs
@@ -936,6 +936,989 @@ pub fn find_unsloth_binary() -> Option<std::path::PathBuf> {
find_unsloth_binary_in_studio_dir(&studio)
}
+/// Whether the user's profile is reachable at all: the managed install lives
+/// under it, so an unmounted roaming profile looks like no install.
+pub(crate) fn home_dir_available() -> Result<(), String> {
+ usable_home_dir(dirs::home_dir(), &windows_roots(), true).map(|_| ())
+}
+
+/// The profile a managed install may live under, or why it cannot. One policy for
+/// both callers: a home reported available but then rejected by the resolver sends
+/// a SYSTEM account to an install flow that cannot start.
+fn usable_home_dir(
+ home: Option<std::path::PathBuf>,
+ windirs: &[std::path::PathBuf],
+ require_existing: bool,
+) -> Result<std::path::PathBuf, String> {
+ let home = home.ok_or_else(|| "Could not determine the home directory".to_string())?;
+
+ // A SYSTEM account's home is under the Windows tree
+ // (C:\Windows\System32\config\systemprofile), the folder the CLI rejects.
+ if is_inside_windows_dir(&home, windirs) {
+ return Err(format!(
+ "Home directory {} is inside the Windows directory",
+ home.display()
+ ));
+ }
+
+ // The installer is the one caller that may build the profile as it goes, the
+ // way it did before it shared this resolver. For everything else a home that
+ // is not there yet is an unmounted roaming profile, and creating it would
+ // leave an empty folder shadowing the real one when it arrives.
+ if require_existing && !home.is_dir() {
+ return Err(format!(
+ "Home directory {} is not reachable",
+ home.display()
+ ));
+ }
+ Ok(home)
+}
+
+/// Marker the desktop sets on every CLI child it owns. The Python CLI reads it to
+/// tell a desktop-managed launch from a user typing the same command in a shell.
+pub(crate) const DESKTOP_MANAGED_ENV: &str = "UNSLOTH_DESKTOP_MANAGED";
+
+/// Windows registers "run at login" as an HKCU Run value, which carries no working
+/// directory, so the app starts in C:\Windows\system32 and every child inherits it.
+/// The CLI refuses to run there, so pick the directory explicitly.
+pub(crate) fn managed_cli_working_dir_from(
+ home: Option<std::path::PathBuf>,
+ windirs: &[std::path::PathBuf],
+) -> Result<std::path::PathBuf, String> {
+ working_dir_under(home, windirs, true)
+}
+
+/// The same directory for the installer, which may create the profile it runs
+/// under: install.ps1 and install.sh detect a SYSTEM profile themselves, and
+/// before they shared this resolver a home that did not exist yet was simply
+/// created along with ~/.unsloth.
+pub(crate) fn install_working_dir(
+ home: Option<std::path::PathBuf>,
+) -> Result<std::path::PathBuf, String> {
+ working_dir_under(home, &[], false)
+}
+
+fn working_dir_under(
+ home: Option<std::path::PathBuf>,
+ windirs: &[std::path::PathBuf],
+ require_existing_home: bool,
+) -> Result<std::path::PathBuf, String> {
+ let home = usable_home_dir(home, windirs, require_existing_home)?;
+
+ // Where the installer already runs, so ~/.unsloth stays the one working root.
+ let work_dir = home.join(".unsloth");
+ if !work_dir.exists() {
+ std::fs::create_dir_all(&work_dir)
+ .map_err(|e| format!("Failed to create {}: {}", work_dir.display(), e))?;
+ }
+ if !work_dir.is_dir() {
+ return Err(format!("{} is not a directory", work_dir.display()));
+ }
+ Ok(work_dir)
+}
+
+// Case-insensitive, either separator, no trailing one, no \\?\ prefix. Not
+// cfg-gated, so the check stays unit-testable from Linux CI.
+fn normalize_windows_path(path: &std::path::Path) -> String {
+ // Lowercased first: \\?\unc\ is accepted too, and must not read as relative.
+ let text = path.to_string_lossy().replace('/', "\\").to_lowercase();
+ let text = match text.strip_prefix("\\\\?\\unc\\") {
+ Some(rest) => format!("\\\\{rest}"),
+ None => text.strip_prefix("\\\\?\\").unwrap_or(&text).to_string(),
+ };
+ text.trim_end_matches('\\').to_string()
+}
+
+fn is_inside_windows_dir(path: &std::path::Path, windirs: &[std::path::PathBuf]) -> bool {
+ let normalized = normalize_windows_path(path);
+ windirs.iter().any(|windir| {
+ let root = normalize_windows_path(windir);
+ // "c:" (a WINDIR of "C:\") would otherwise match the whole drive.
+ root.len() > 2 && (normalized == root || normalized.starts_with(&(root.clone() + "\\")))
+ })
+}
+
+/// Directory a desktop-spawned `unsloth` CLI child should run from: the inherited
+/// one, unless unusable (on Windows, a system folder), so cwd-relative defaults
+/// keep resolving where they did and only the login start moves. Resolved per call
+/// so a late-mounting profile recovers, and never falls back to a temp dir.
+pub(crate) fn managed_cli_working_dir() -> Result<std::path::PathBuf, String> {
+ let windirs = windows_roots();
+ if let Ok(cwd) = std::env::current_dir() {
+ if !is_unusable_cwd(&cwd, &windirs) {
+ return Ok(cwd);
+ }
+ }
+ managed_cli_working_dir_from(dirs::home_dir(), &windirs)
+}
+
+/// The directories the CLI guard refuses to run from, and only those. The rest of
+/// the Windows tree still disqualifies a *home*, but a child already running from
+/// C:\Windows\Temp keeps doing so: the guard allowed that before this change.
+fn is_unusable_cwd(path: &std::path::Path, windirs: &[std::path::PathBuf]) -> bool {
+ windirs.iter().any(|windir| {
+ ["System32", "SysWOW64"]
+ .iter()
+ .any(|name| is_inside_windows_dir(path, &[windir.join(name)]))
+ })
+}
+
+/// Every real Windows directory, empty off Windows. Candidates are checked, not
+/// trusted: a settable variable could aim the check somewhere harmless, and a
+/// WINDIR aimed at the profile would reject it. So a root must hold System32.
+fn windows_roots() -> Vec<std::path::PathBuf> {
+ if !cfg!(windows) {
+ return Vec::new();
+ }
+ let system_root = std::env::var("SystemRoot").ok();
+ let fallback = system_root
+ .clone()
+ .unwrap_or_else(|| r"C:\Windows".to_string());
+ windows_roots_from(
+ [
+ system_root,
+ std::env::var("WINDIR").ok(),
+ Some(r"C:\Windows".to_string()),
+ ]
+ .into_iter()
+ .flatten()
+ .map(std::path::PathBuf::from)
+ .collect(),
+ std::path::PathBuf::from(fallback),
+ |root| root.join("System32").is_dir(),
+ )
+}
+
+fn windows_roots_from(
+ candidates: Vec<std::path::PathBuf>,
+ fallback: std::path::PathBuf,
+ is_windows_dir: impl Fn(&std::path::Path) -> bool,
+) -> Vec<std::path::PathBuf> {
+ let mut roots: Vec<std::path::PathBuf> = Vec::new();
+ for root in candidates {
+ if is_windows_dir(&root) && !roots.contains(&root) {
+ roots.push(root);
+ }
+ }
+ if roots.is_empty() {
+ // No Windows install found: keep the check alive on a non-settable value.
+ roots.push(fallback);
+ }
+ roots
+}
+
+/// Path overrides a relative value makes cwd-dependent, so moving the child
+/// without rewriting them would point them somewhere else. Search lists such as
+/// PATH are absent: they are not single paths. Mirrors `_RELATIVE_PATH_ENV` in
+/// unsloth_cli/_system_dir_guard.py, held identical by a parity test.
+pub(crate) const RELATIVE_PATH_ENV: &[&str] = &[
+ "UNSLOTH_STUDIO_HOME",
+ "STUDIO_HOME",
+ "UNSLOTH_STUDIO_DOCUMENTS_HOME",
+ "UNSLOTH_STUDIO_PROJECTS_HOME",
+ "UNSLOTH_STUDIO_SANDBOX_HOME",
+ "STUDIO_LOCAL_REPO",
+ "UNSLOTH_LLAMA_CPP_PATH",
+ "UNSLOTH_LLAMA_CPP_SCRIPTS_DIR",
+ "UNSLOTH_SD_CPP_PATH",
+ "UNSLOTH_WHISPER_CPP_PATH",
+ "LLAMA_SERVER_PATH",
+ "WHISPER_SERVER_PATH",
+ "SD_CLI_PATH",
+ "SD_SERVER_PATH",
+ "LLAMA_ARG_MODEL",
+ "LLAMA_ARG_MMPROJ",
+ "LLAMA_ARG_MODEL_DRAFT",
+ "LLAMA_ARG_SPEC_DRAFT_MODEL",
+ "AMDGPU_ASIC_ID_TABLE_PATH",
+ "VLLM_CACHE_ROOT",
+ "GGML_BACKEND_PATH",
+ "CUDA_PATH",
+ "HIP_PATH",
+ "HIP_PATH_57",
+ "ROCM_PATH",
+ "MLX_HOSTFILE",
+ // Read exactly like MLX_HOSTFILE: either inline JSON or a filename.
+ "MLX_IBV_DEVICES",
+ "OLLAMA_MODELS",
+ "DG_VISUAL_BIN",
+ "UNSLOTH_DG_SHIM",
+ "UNSLOTH_COMPILE_LOCATION",
+ "TORCHINDUCTOR_CACHE_DIR",
+ "UNSLOTH_DIFFUSION_COMPILE_CACHE_DIR",
+ "UNSLOTH_DIFFUSION_COND_CACHE_DIR",
+ "HF_HOME",
+ "HF_HUB_CACHE",
+ "HUGGINGFACE_HUB_CACHE",
+ "HF_XET_CACHE",
+ "HF_DATASETS_CACHE",
+ "HF_ASSETS_CACHE",
+ // huggingface_hub resolves the credential file from here; a relative value
+ // would follow the child and silently lose access to gated repos.
+ "HF_TOKEN_PATH",
+ // uv reads this as written and Studio treats a non-blank value as
+ // authoritative, so an update would install from a different cache.
+ "UV_CACHE_DIR",
+ "TRANSFORMERS_CACHE",
+ "SENTENCE_TRANSFORMERS_HOME",
+ "XDG_CACHE_HOME",
+ "XDG_CONFIG_HOME",
+ "XDG_DATA_HOME",
+ "UNSLOTH_STUDIO_CHILD_RECORD",
+ "UNSLOTH_LLAMA_INSTALLER",
+ "CUDA_HOME",
+ "CUDA_ROOT",
+];
+
+/// The same, for values holding several separated directories: one relative
+/// entry changes what the whole list allows or searches. PYTHONPATH is here
+/// because a relative entry in it is resolved at import time, so a moved child
+/// would let whatever sits in the new directory shadow a managed import. PATH is
+/// deliberately absent: it is mostly other people's absolute entries, and
+/// refusing a launch over one unresolvable entry there would cost more than it
+/// protects.
+pub(crate) const PATH_LIST_ENV: &[&str] = &[
+ "UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH",
+ "CUDA_RUNTIME_DLL_DIR",
+ "PYTHONPATH",
+];
+
+/// Whether a value names one directory whatever the process does next.
+///
+/// Windows rules on every platform: a Windows value is what reaches this code,
+/// and hard-coding them keeps the check testable from Linux CI. Matches
+/// `_is_fully_qualified` in the CLI guard, "C:sub" and "\\cache" included, both
+/// of which name a directory only in combination with process state.
+fn is_fully_qualified(value: &str) -> bool {
+ let lowered = value.to_lowercase();
+ if lowered.starts_with("\\\\?\\unc\\") {
+ return true;
+ }
+ let value = if lowered.starts_with("\\\\?\\") {
+ &value[4..]
+ } else {
+ value
+ };
+ if value.starts_with("\\\\") || value.starts_with("//") {
+ return true;
+ }
+ // Spelled out rather than deferred to Path::is_absolute, so the answer is
+ // the same on the Linux runner that tests it as on the Windows machine that
+ // runs it, and the same as _is_fully_qualified in the CLI guard.
+ matches!(value.as_bytes(), [drive, b':', sep, ..]
+ if drive.is_ascii_alphabetic() && (*sep == b'\\' || *sep == b'/'))
+}
+
+/// `$NAME` and `${NAME}` against the process environment, as posixpath.expandvars
+/// reads them: an unset name and a `$` that starts no name are left exactly as
+/// written, and `%NAME%` is an ordinary filename character off Windows.
+fn expand_posix_vars(value: &str, lookup: &impl Fn(&str) -> Option<String>) -> String {
+ let bytes = value.as_bytes();
+ let mut out = String::with_capacity(value.len());
+ let mut index = 0;
+ while index < bytes.len() {
+ if bytes[index] != b'$' {
+ let start = index;
+ while index < bytes.len() && bytes[index] != b'$' {
+ index += 1;
+ }
+ out.push_str(&value[start..index]);
+ continue;
+ }
+ let rest = &value[index + 1..];
+ let (name, consumed) = if let Some(rest) = rest.strip_prefix('{') {
+ match rest.find('}') {
+ Some(end) => (&rest[..end], end + 2),
+ None => {
+ out.push_str(&value[index..]);
+ break;
+ }
+ }
+ } else {
+ let end = rest
+ .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
+ .unwrap_or(rest.len());
+ (&rest[..end], end)
+ };
+ if name.is_empty() {
+ out.push('$');
+ index += 1;
+ continue;
+ }
+ match lookup(name) {
+ Some(value) => out.push_str(&value),
+ None => out.push_str(&value[index..index + consumed + 1]),
+ }
+ index += consumed + 1;
+ }
+ out
+}
+
+/// Whether the value names the same place from any working directory.
+///
+/// Windows rules on Windows, the native ones off it. The lost-directory
+/// fallback below is the one branch a Linux or macOS process reaches, and what
+/// it reads there is a POSIX environment: `/var/cache/unsloth` is no more
+/// cwd-dependent than `C:\cache`, and judging it by the Windows rules refused
+/// every managed spawn over a setting that was never relative. A Windows-shaped
+/// value stays Windows-judged, so "/cache" is still the root of whichever drive
+/// the process is on.
+fn is_cwd_independent(value: &str, windows: bool) -> bool {
+ if windows {
+ is_fully_qualified(value)
+ } else {
+ // The whole of absoluteness off Windows.
+ value.starts_with('/')
+ }
+}
+
+/// The most a Windows environment variable holds, terminator included.
+const WINDOWS_ENV_VALUE_LIMIT: usize = 32_767;
+
+/// What separates the entries of a path list, as os.pathsep spells it.
+fn path_list_separator(windows: bool) -> char {
+ if windows {
+ ';'
+ } else {
+ ':'
+ }
+}
+
+/// Whether the value depends on process state `join` cannot see: the current
+/// directory of a drive ("D:cache") or of the current drive ("\\cache").
+fn needs_os_resolution(value: &str) -> bool {
+ if value.starts_with('\\') || value.starts_with('/') {
+ return true;
+ }
+ matches!(value.as_bytes(), [drive, b':', ..] if drive.is_ascii_alphabetic())
+}
+
+/// MLX_HOSTFILE holds either a filename or the host list itself, as JSON.
+const INLINE_JSON_ENV: &[&str] = &["MLX_HOSTFILE", "MLX_IBV_DEVICES"];
+
+/// Names whose readers disagree about %VAR%: huggingface_hub expands HF_HOME
+/// (and the XDG_CACHE_HOME it defaults from), HF_HUB_CACHE and HF_ASSETS_CACHE,
+/// and Studio expands SENTENCE_TRANSFORMERS_HOME, but Studio's own
+/// hf_cache_settings does not, so it reads %LOCALAPPDATA%\hf as a relative
+/// folder. Expanding before deciding settles it: both readers then see one
+/// absolute path. Scoped to these names because a directory really called
+/// "%data%" is legal and every other name is read as one.
+const EXPANDED_ENV: &[&str] = &[
+ "HF_HOME",
+ "HF_TOKEN_PATH",
+ "HF_HUB_CACHE",
+ "HUGGINGFACE_HUB_CACHE",
+ "HF_ASSETS_CACHE",
+ "XDG_CACHE_HOME",
+ "SENTENCE_TRANSFORMERS_HOME",
+];
+
+/// The pre-quant allowlist skips a bare on/off token so there is no allow-all
+/// mode; anchoring one would turn it into a real allowlisted directory.
+const TOGGLE_ENV: &[&str] = &["UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH"];
+
+/// %NAME%, $NAME and ${NAME} against the process environment.
+///
+/// Mirrors ntpath.expandvars, which is what the CLI guard uses, down to its
+/// pattern: `'[^']*'?|%(%|[^%]*%?)|\$(\$|[-\w]+|\{[^}]*\}?)`. The details matter
+/// because the two layers have to name the same folder: a single-quoted run is
+/// copied through unexpanded, `%%` and `$$` stand for one character, a `$` name
+/// may contain a hyphen, and anything unterminated is left exactly as written,
+/// as is a name this machine does not set.
+fn expand_windows_vars(value: &str, lookup: &impl Fn(&str) -> Option<String>) -> String {
+ let bytes = value.as_bytes();
+ let mut out = String::with_capacity(value.len());
+ let mut index = 0;
+ while index < bytes.len() {
+ // Only taken for the three ASCII markers below, where index + 1 is
+ // always a character boundary.
+ match bytes[index] {
+ b'\'' => {
+ // A quoted run is copied through, terminator included when it
+ // has one, so a reference inside it is not expanded.
+ let rest = &value[index + 1..];
+ let end = rest
+ .find('\'')
+ .map_or(value.len(), |offset| index + 1 + offset + 1);
+ out.push_str(&value[index..end]);
+ index = end;
+ }
+ b'%' => {
+ let rest = &value[index + 1..];
+ if rest.starts_with('%') {
+ out.push('%');
+ index += 2;
+ continue;
+ }
+ match rest.find('%') {
+ Some(offset) => {
+ let end = index + 1 + offset + 1;
+ match lookup(&rest[..offset]) {
+ Some(expanded) => out.push_str(&expanded),
+ None => out.push_str(&value[index..end]),
+ }
+ index = end;
+ }
+ // No closing %, so nothing here is a reference.
+ None => {
+ out.push_str(&value[index..]);
+ index = value.len();
+ }
+ }
+ }
+ b'$' => {
+ let rest = &value[index + 1..];
+ if rest.starts_with('$') {
+ out.push('$');
+ index += 2;
+ continue;
+ }
+ if rest.starts_with('{') {
+ match rest.find('}') {
+ Some(offset) => {
+ let end = index + 1 + offset + 1;
+ match lookup(&rest[1..offset]) {
+ Some(expanded) => out.push_str(&expanded),
+ None => out.push_str(&value[index..end]),
+ }
+ index = end;
+ }
+ None => {
+ out.push_str(&value[index..]);
+ index = value.len();
+ }
+ }
+ continue;
+ }
+ // \w under re.ASCII, plus the hyphen ntpath allows.
+ let end = rest
+ .find(|c: char| !(c.is_ascii_alphanumeric() || c == '_' || c == '-'))
+ .unwrap_or(rest.len());
+ if end == 0 {
+ out.push('$');
+ index += 1;
+ continue;
+ }
+ match lookup(&rest[..end]) {
+ Some(expanded) => out.push_str(&expanded),
+ None => out.push_str(&value[index..index + 1 + end]),
+ }
+ index += 1 + end;
+ }
+ _ => {
+ let step = value[index..].chars().next().map_or(1, char::len_utf8);
+ out.push_str(&value[index..index + step]);
+ index += step;
+ }
+ }
+ }
+ out
+}
+
+/// Whether the working directory is what resolves this variable's value.
+///
+/// The twin of `_names_a_path` in `unsloth_cli/_system_dir_guard.py`. Each
+/// exemption is scoped to the variables whose reader proves it, because the
+/// syntax is only special there: a directory really called "[llama]" is legal on
+/// Windows, and UNSLOTH_LLAMA_CPP_PATH is read as one.
+/// `value` expanded once, or None if one pass does not settle it.
+///
+/// One pass is what every reader does, so one pass is what this does. The result
+/// is only usable if expanding it again would change nothing, because the reader
+/// expands whatever gets written back: a nested %LOCALAPPDATA% that itself holds
+/// %USERPROFILE%, an escaped %%NAME%%, or a self-reference would be expanded a
+/// second time and read as a folder with another drive in the middle of it. The
+/// twin of `_expand_settled` in the CLI guard.
+fn expand_settled(
+ value: &str,
+ lookup: &impl Fn(&str) -> Option<String>,
+ windows: bool,
+) -> Option<String> {
+ let expand = |value: &str| {
+ if windows {
+ expand_windows_vars(value, lookup)
+ } else {
+ expand_posix_vars(value, lookup)
+ }
+ };
+ let expanded = expand(value);
+ (expand(&expanded) == expanded).then_some(expanded)
+}
+
+fn names_a_path(name: &str, value: &str) -> bool {
+ if INLINE_JSON_ENV.contains(&name) && (value.starts_with('[') || value.starts_with('{')) {
+ return false;
+ }
+ if TOGGLE_ENV.contains(&name)
+ && matches!(
+ value.to_ascii_lowercase().as_str(),
+ "1" | "true" | "yes" | "on" | "0" | "false" | "no" | "off"
+ )
+ {
+ return false;
+ }
+ true
+}
+
+/// Names every managed spawn removes before starting the child: Tauri uses the
+/// legacy Studio root whatever the environment says. Resolving one can only
+/// invent a failure for a value the child is never going to see.
+const MANAGED_CHILD_SCRUBBED_ENV: &[&str] = &["UNSLOTH_STUDIO_HOME", "STUDIO_HOME"];
+
+/// Read only by the update and installer path (install_python_stack.py), so a
+/// stale value must not be able to fail a probe, a backend start or an auth
+/// provision that would never have looked at it.
+const UPDATE_ONLY_ENV: &[&str] = &["STUDIO_LOCAL_REPO"];
+
+/// `~` and `~name`, resolved the way ntpath.expanduser resolves them.
+///
+/// Written out rather than skipped, because only some readers of these names
+/// expand it themselves: llama_cpp.py hands UNSLOTH_LLAMA_CPP_PATH straight to
+/// Path(), so a moved child would look for a folder called "~" beside its new
+/// working directory.
+fn expand_windows_user(
+ value: &str,
+ home: &std::path::Path,
+ username: Option<&str>,
+) -> String {
+ if !value.starts_with('~') {
+ return value.to_string();
+ }
+ let end = value[1..]
+ .find(['\\', '/'])
+ .map_or(value.len(), |offset| offset + 1);
+ let (name, rest) = (&value[1..end], &value[end..]);
+ let home = home.to_string_lossy();
+ let base = if name.is_empty() {
+ home.into_owned()
+ } else {
+ // ~someone-else is the sibling of this profile, but only where ntpath
+ // agrees: it declines to guess unless this profile is named after the
+ // current user, since C:\Users\alice.DOMAIN is not alice's sibling.
+ // Split on the string, not with Path::parent: these are Windows paths
+ // whichever platform the code is running on.
+ let cut = match home.rfind(['\\', '/']) {
+ Some(cut) => cut,
+ None => return value.to_string(),
+ };
+ let this_profile = &home[cut + 1..];
+ match username {
+ Some(user) if user == name => home.clone().into_owned(),
+ Some(user) if user == this_profile => format!("{}{}", &home[..cut + 1], name),
+ _ => return value.to_string(),
+ }
+ };
+ format!("{}{}", base, rest)
+}
+
+fn relative_override_pins_from(
+ cwd: Option<std::path::PathBuf>,
+ work_dir: &std::path::Path,
+ lookup: impl Fn(&str) -> Option<String>,
+ absolute: impl Fn(&str) -> Option<std::path::PathBuf>,
+ home: Option<&std::path::Path>,
+ skipped: &[&str],
+ windows: bool,
+) -> Result<Vec<(&'static str, std::path::PathBuf)>, String> {
+ // Written out, so the reader that expands %VAR% and the reader that does not
+ // land in the same folder. Only for the names that have both.
+ let username = lookup("USERNAME");
+ // ntpath.expanduser answers USERPROFILE, and the CLI guard uses it, so the
+ // tilde has to resolve to the same folder here. dirs::home_dir() reads the
+ // known folder instead, which a portable or overridden environment moves.
+ let tilde_home = lookup("USERPROFILE")
+ .map(std::path::PathBuf::from)
+ .or_else(|| home.map(|home| home.to_path_buf()));
+ let home = tilde_home.as_deref();
+ // One pass does not settle every value. What the reader sees is one pass: if
+ // that names a folder on its own the value is safe to leave alone, and if it
+ // does not, the folder it names depends on where the process is standing, so
+ // the move has to be refused rather than taken with the value following it.
+ let expanded = |name: &str, value: &str| -> Result<Option<String>, String> {
+ if !EXPANDED_ENV.contains(&name) {
+ return Ok(Some(value.to_string()));
+ }
+ // Windows rules on Windows, the native ones off it: a POSIX reader leaves
+ // %HOME% as an ordinary name and expands $HOME instead, so reading this
+ // the Windows way would call a relative value absolute.
+ match expand_settled(value, &lookup, windows) {
+ Some(settled) => Ok(Some(settled)),
+ None => {
+ let once = if windows {
+ expand_windows_vars(value, &lookup)
+ } else {
+ expand_posix_vars(value, &lookup)
+ };
+ if is_cwd_independent(&once, windows) {
+ Ok(None)
+ } else {
+ Err(format!("{name} does not expand to one folder"))
+ }
+ }
+ }
+ };
+ let Some(cwd) = cwd else {
+ // The directory being left is unknown, so nothing can be anchored to it.
+ // Moving anyway would quietly retarget every relative value at the new
+ // directory, so this is only survivable with nothing left to preserve.
+ for name in RELATIVE_PATH_ENV.iter().chain(PATH_LIST_ENV) {
+ if skipped.contains(name) {
+ continue;
+ }
+ let Some(value) = lookup(name) else { continue };
+ // A list is judged entry by entry: "C:\\vendor;plugins" starts with a
+ // drive and still carries something the lost directory decided.
+ let raw = value.trim();
+ let entries: Vec<&str> = if PATH_LIST_ENV.contains(name) {
+ raw.split(path_list_separator(windows)).collect()
+ } else {
+ vec![raw]
+ };
+ for entry in entries {
+ let entry = entry.trim();
+ if entry.is_empty() {
+ // An empty PYTHONPATH component is the directory itself.
+ if *name == "PYTHONPATH" && !raw.is_empty() {
+ return Err(format!(
+ "{name} names the directory it was written against, which is gone"
+ ));
+ }
+ continue;
+ }
+ // Judged the same way the moving path judges it, or a setting
+ // that decides nothing here (an expanded %LOCALAPPDATA%, inline
+ // JSON, a 0/1 toggle) would be read as relative and refuse
+ // every spawn over a value no directory ever decided.
+ let entry = match home {
+ Some(home) => expand_windows_user(entry, home, username.as_deref()),
+ None => entry.to_string(),
+ };
+ let Some(entry) = expanded(name, &entry)? else {
+ continue;
+ };
+ if is_cwd_independent(&entry, windows) {
+ continue;
+ }
+ if !names_a_path(name, &entry) {
+ continue;
+ }
+ return Err(format!(
+ "{name} is relative and the directory it was written against is gone"
+ ));
+ }
+ }
+ return Ok(Vec::new());
+ };
+ // The usual case: the child keeps the directory it inherited, so every
+ // relative value still means what it did and nothing is rewritten.
+ if cwd == work_dir {
+ return Ok(Vec::new());
+ }
+ // A value the OS declines to resolve is refused rather than dropped: moving
+ // the child with that override still relative would retarget it silently,
+ // which is what the pinning exists to prevent. The CLI guard refuses the
+ // same case.
+ let anchor = |name: &str, value: &str| -> Result<std::path::PathBuf, String> {
+ if needs_os_resolution(value) {
+ // "D:cache" is drive D's own current directory and "\\cache" the
+ // root of the current drive, neither of which join() knows.
+ absolute(value)
+ .ok_or_else(|| format!("{name} names a path this machine cannot resolve"))
+ } else {
+ Ok(cwd.join(value))
+ }
+ };
+ let mut pins = Vec::new();
+ for name in RELATIVE_PATH_ENV {
+ if skipped.contains(name) {
+ continue;
+ }
+ let Some(value) = lookup(name) else { continue };
+ let original = value.trim().to_string();
+ // The tilde first and the variables second, the order the CLI guard uses,
+ // so a value that names a folder through both reaches the same one.
+ let value = match home {
+ Some(home) => expand_windows_user(&original, home, username.as_deref()),
+ None => original.clone(),
+ };
+ let Some(value) = expanded(name, &value)? else {
+ continue;
+ };
+ if value.is_empty() {
+ continue;
+ }
+ // Windows rules on Windows, the native ones off it, exactly as the
+ // lost-directory branch reads them: /opt/vendor is no more cwd-dependent
+ // there than C:\\cache is here.
+ if is_cwd_independent(&value, windows) {
+ // Already names one folder. Still worth writing back if expanding is
+ // what made it name one: the reader that does not expand cannot see
+ // that on its own.
+ if value != original {
+ pins.push((*name, std::path::PathBuf::from(value)));
+ }
+ continue;
+ }
+ if !names_a_path(name, &value) {
+ continue;
+ }
+ match anchor(name, &value) {
+ Ok(pinned) => {
+ if windows && pinned.as_os_str().len() >= WINDOWS_ENV_VALUE_LIMIT {
+ return Err(format!(
+ "{name} does not fit in an environment variable once it names its folder in full"
+ ));
+ }
+ pins.push((*name, pinned));
+ }
+ Err(error) => {
+ if !BEST_EFFORT_ENV.contains(name) {
+ return Err(error);
+ }
+ }
+ }
+ }
+ for name in PATH_LIST_ENV {
+ let Some(raw) = lookup(name) else { continue };
+ if raw.trim().is_empty() {
+ continue;
+ }
+ let separator = path_list_separator(windows);
+ let mut entries: Vec<String> = Vec::new();
+ for entry in raw.split(separator) {
+ let original = entry.trim().to_string();
+ // Python never expands `~` in PYTHONPATH, so `~\plugins` is an
+ // ordinary relative folder there, and expanding it would point the
+ // import at a profile folder the interpreter was never reading.
+ let entry = match home {
+ Some(home) if *name != "PYTHONPATH" => {
+ expand_windows_user(&original, home, username.as_deref())
+ }
+ _ => original.clone(),
+ };
+ let Some(entry) = expanded(name, &entry)? else {
+ entries.push(original);
+ continue;
+ };
+ // PYTHONPATH has two spellings that follow the process rather than
+ // the caller: an empty component means the working directory itself,
+ // and a leading `~` is never expanded there, so Python reads
+ // `~\plugins` as an ordinary relative folder.
+ // An empty PYTHONPATH component means the working directory itself.
+ if *name == "PYTHONPATH" && entry.is_empty() {
+ entries.push(cwd.to_string_lossy().into_owned());
+ continue;
+ }
+ if entry.is_empty() || is_cwd_independent(&entry, windows) {
+ entries.push(entry);
+ continue;
+ }
+ if !names_a_path(name, &entry) {
+ entries.push(entry);
+ continue;
+ }
+ entries.push(anchor(name, &entry)?.to_string_lossy().into_owned());
+ }
+ let joined = entries.join(&separator.to_string());
+ // 2. A value the OS will not accept is a failure to report here, not one
+ // to discover in CreateProcess: the caller turns this into the same
+ // "path setting" message as an unresolvable one, and a repair that would
+ // hit the same wall is not offered.
+ if windows && joined.len() >= WINDOWS_ENV_VALUE_LIMIT {
+ return Err(format!(
+ "{name} does not fit in an environment variable once each entry names its folder in full"
+ ));
+ }
+ if joined == raw {
+ continue;
+ }
+ pins.push((*name, std::path::PathBuf::from(joined)));
+ }
+ Ok(pins)
+}
+
+/// Relative overrides, anchored to the directory the child is being moved out of.
+fn relative_override_pins(
+ work_dir: &std::path::Path,
+ skipped: &[&str],
+) -> Result<Vec<(&'static str, std::path::PathBuf)>, String> {
+ relative_override_pins_from(
+ std::env::current_dir().ok(),
+ work_dir,
+ |name| std::env::var(name).ok(),
+ // GetFullPathNameW on Windows, which is what knows each drive's own
+ // current directory.
+ |value| std::path::absolute(value).ok(),
+ dirs::home_dir().as_deref(),
+ skipped,
+ cfg!(windows),
+ )
+}
+
+/// The pins a move needs, or None when the move must not happen.
+///
+/// A directory that cannot be named is one nothing can be anchored to. Staying is
+/// what the child did before this file learned about working directories, and it
+/// keeps every relative setting meaning exactly what it does now; only a
+/// directory we can name is worth moving out of. Refusing the whole spawn instead
+/// would take a probe, a backend, an auth provision or an update down over a
+/// setting the command may never read.
+fn pins_for_move(
+ work_dir: &std::path::Path,
+ skipped: &[&str],
+) -> Result<Option<Vec<(&'static str, std::path::PathBuf)>>, String> {
+ stay_put_on_lost_cwd(
+ relative_override_pins(work_dir, skipped),
+ std::env::current_dir().is_ok(),
+ )
+}
+
+/// Split out so the decision is testable without moving this process.
+fn stay_put_on_lost_cwd(
+ pins: Result<Vec<(&'static str, std::path::PathBuf)>, String>,
+ cwd_is_known: bool,
+) -> Result<Option<Vec<(&'static str, std::path::PathBuf)>>, String> {
+ match pins {
+ Ok(pins) => Ok(Some(pins)),
+ Err(error) if cwd_is_known => Err(error),
+ Err(_) => Ok(None),
+ }
+}
+
+/// What the update child neither receives nor needs. It is the one child that
+/// reads STUDIO_LOCAL_REPO, and the one that wants no PYTHONPATH at all on
+/// Windows, where -I covers only the first interpreter and the update starts
+/// more. Skipping it here rather than removing it afterwards means an
+/// unresolvable entry cannot refuse an update that was never going to read it.
+fn update_child_skipped_env() -> Vec<&'static str> {
+ MANAGED_CHILD_SCRUBBED_ENV
+ .iter()
+ .copied()
+ .chain(cfg!(windows).then_some("PYTHONPATH"))
+ .collect()
+}
+
+/// Pinned when it can be, but never at the cost of the spawn. The update is the
+/// one child that receives STUDIO_LOCAL_REPO, and a bare `unsloth studio update`
+/// drops it before anything reads it (commands/studio.py), so refusing to start
+/// over a stale drive-relative value would defeat the fallback this exists for.
+/// The twin of `_BEST_EFFORT_ENV` in the CLI guard.
+const BEST_EFFORT_ENV: &[&str] = &["STUDIO_LOCAL_REPO"];
+
+/// What an ordinary managed child neither receives nor needs.
+fn child_skipped_env() -> Vec<&'static str> {
+ MANAGED_CHILD_SCRUBBED_ENV
+ .iter()
+ .chain(UPDATE_ONLY_ENV)
+ .copied()
+ .collect()
+}
+
+/// The error a managed spawn would fail with, without spawning anything.
+///
+/// Preflight asks first: a context that cannot be built is not a broken CLI, and
+/// reporting it as one starts an automatic repair that needs the same context
+/// and fails the same way.
+pub(crate) fn managed_cli_context_error() -> Option<ManagedContextError> {
+ let work_dir = match managed_cli_working_dir() {
+ Ok(work_dir) => work_dir,
+ Err(error) => return Some(ManagedContextError::WorkingDirectory(error)),
+ };
+ pins_for_move(&work_dir, &child_skipped_env())
+ .err()
+ .map(ManagedContextError::PathSetting)
+}
+
+/// Why a managed spawn cannot be configured. The two are told apart because the
+/// fixes are: a profile that has to come back, and a path setting the user wrote
+/// that the OS cannot resolve.
+#[derive(Debug, Clone)]
+pub(crate) enum ManagedContextError {
+ WorkingDirectory(String),
+ PathSetting(String),
+}
+
+impl std::fmt::Display for ManagedContextError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::WorkingDirectory(error) | Self::PathSetting(error) => f.write_str(error),
+ }
+ }
+}
+
+/// Whether the child has to be told where to run.
+///
+/// It does not when that is already where the parent is: reopening the inherited
+/// directory by name can fail (an ancestor turned unreadable after launch) where
+/// simply inheriting the open handle would have worked, so the no-move case is
+/// left exactly as it was before this file learned about working directories.
+fn needs_explicit_cwd(work_dir: &std::path::Path) -> bool {
+ std::env::current_dir()
+ .map(|cwd| cwd != work_dir)
+ .unwrap_or(true)
+}
+
+/// Pin the working directory and mark the child as desktop-managed. Env
+/// scrubbing, creation flags and the ownership handshake stay with the caller.
+/// For the update, which is the one child that reads STUDIO_LOCAL_REPO.
+pub(crate) fn apply_managed_cli_context(cmd: &mut Command) -> Result<(), String> {
+ // The update is the one child that reads STUDIO_LOCAL_REPO, and the one that
+ // wants no PYTHONPATH at all on Windows: -I covers only the first
+ // interpreter, and the update starts more. Skipping it here rather than
+ // removing it afterwards means an unresolvable entry cannot refuse an update
+ // that was never going to read it.
+ apply_managed_cli_context_inner(cmd, &managed_cli_working_dir()?, &update_child_skipped_env())
+}
+
+pub(crate) fn apply_managed_cli_context_at(
+ cmd: &mut Command,
+ work_dir: &std::path::Path,
+) -> Result<(), String> {
+ apply_managed_cli_context_inner(cmd, work_dir, &child_skipped_env())
+}
+
+fn apply_managed_cli_context_inner(
+ cmd: &mut Command,
+ work_dir: &std::path::Path,
+ skipped: &[&str],
+) -> Result<(), String> {
+ if let Some(pins) = pins_for_move(work_dir, skipped)? {
+ for (name, pinned) in pins {
+ cmd.env(name, pinned);
+ }
+ if needs_explicit_cwd(work_dir) {
+ cmd.current_dir(work_dir);
+ }
+ }
+ // Removed here as well as at the call sites, so the skip above is a fact
+ // about the child rather than an assumption about every caller.
+ for name in skipped {
+ cmd.env_remove(name);
+ }
+ cmd.env(DESKTOP_MANAGED_ENV, "1");
+ Ok(())
+}
+
+pub(crate) fn apply_managed_cli_context_tokio(
+ cmd: &mut tokio::process::Command,
+) -> Result<(), String> {
+ let work_dir = managed_cli_working_dir()?;
+ let skipped = child_skipped_env();
+ if let Some(pins) = pins_for_move(&work_dir, &skipped)? {
+ for (name, pinned) in pins {
+ cmd.env(name, pinned);
+ }
+ if needs_explicit_cwd(&work_dir) {
+ cmd.current_dir(&work_dir);
+ }
+ }
+ for name in &skipped {
+ cmd.env_remove(name);
+ }
+ cmd.env(DESKTOP_MANAGED_ENV, "1");
+ Ok(())
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -1137,6 +2120,26 @@ pub fn start_backend(
}
};
+ // A precondition like resolve_backend_binary above, so it runs before any
+ // ownership or job state is touched.
+ let work_dir = match managed_cli_working_dir() {
+ Ok(work_dir) => work_dir,
+ Err(error) => {
+ let msg = format!(
+ "Failed to pick a working directory for the backend: {}",
+ error
+ );
+ diagnostics::record_backend_start_failure(
+ diagnostics_state,
+ Some(port),
+ None,
+ "resolve_working_directory",
+ &msg,
+ );
+ return Err(msg);
+ }
+ };
+
let args = backend_args(port);
let start_line = format!("Starting backend: {:?} {}", bin, args.join(" "));
let pending_owner = match crate::desktop_backend_owner::new_pending_owner() {
@@ -1158,6 +2161,20 @@ pub fn start_backend(
.stdout(Stdio::piped())
.stderr(Stdio::piped());
+ if let Err(error) = apply_managed_cli_context_at(&mut cmd, &work_dir) {
+ // The drive holding an override can go between the preflight check and
+ // this call, and a panic in the spawn path takes the desktop with it.
+ let msg = format!("Failed to prepare the Unsloth backend command: {}", error);
+ diagnostics::record_backend_start_failure(
+ diagnostics_state,
+ Some(port),
+ None,
+ "managed_cli_context",
+ &msg,
+ );
+ return Err(msg);
+ }
+
#[cfg(windows)]
cmd.env(STUDIO_RUNTIME_GATE_HANDOFF_ENV, "1");
@@ -2218,6 +3235,1423 @@ fn stop_backend_inner(
result
}
+// A login-started desktop on Windows inherits C:\Windows\system32 (issue #8510),
+// and so did every CLI child, where the Python CLI refuses to run. These pin the
+// replacement directory and that each command carries it.
+#[cfg(test)]
+mod managed_cli_working_dir_tests {
+ use super::*;
+ use std::fs;
+ use std::path::PathBuf;
+ use std::time::{SystemTime, UNIX_EPOCH};
+
+ fn scratch(test_name: &str) -> PathBuf {
+ let nanos = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_nanos();
+ let dir = std::env::temp_dir().join(format!(
+ "unsloth-{test_name}-{}-{nanos}",
+ std::process::id()
+ ));
+ fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ #[test]
+ fn a_normal_home_yields_the_unsloth_directory_and_creates_it() {
+ let home = scratch("cwd-normal-home");
+ let resolved = managed_cli_working_dir_from(Some(home.clone()), &[])
+ .expect("a normal home must resolve");
+ assert_eq!(resolved, home.join(".unsloth"));
+ assert!(resolved.is_dir(), "the working directory must exist");
+ fs::remove_dir_all(&home).ok();
+ }
+
+ #[test]
+ fn an_existing_working_directory_is_reused() {
+ let home = scratch("cwd-existing");
+ fs::create_dir_all(home.join(".unsloth")).unwrap();
+ let resolved = managed_cli_working_dir_from(Some(home.clone()), &[]).unwrap();
+ assert_eq!(resolved, home.join(".unsloth"));
+ fs::remove_dir_all(&home).ok();
+ }
+
+ #[test]
+ fn a_home_with_spaces_and_non_ascii_survives_intact() {
+ let base = scratch("cwd-unicode");
+ let home = base.join("Jane O'Brien ünïcode");
+ fs::create_dir_all(&home).unwrap();
+ let resolved = managed_cli_working_dir_from(Some(home.clone()), &[]).unwrap();
+ assert_eq!(resolved, home.join(".unsloth"));
+ fs::remove_dir_all(&base).ok();
+ }
+
+ #[test]
+ fn a_home_inside_the_windows_directory_is_not_reported_as_available() {
+ // Reporting it available sends a SYSTEM account to an install flow that
+ // the working directory resolver then refuses to start.
+ let windirs = [PathBuf::from("C:\\Windows")];
+ let home = PathBuf::from("C:\\Windows\\System32\\config\\systemprofile");
+ let error = usable_home_dir(Some(home), &windirs, true).unwrap_err();
+ assert!(
+ error.contains("inside the Windows directory"),
+ "unexpected error: {error}"
+ );
+ let real_home = scratch("usable-home");
+ fs::create_dir_all(&real_home).unwrap();
+ assert_eq!(
+ usable_home_dir(Some(real_home.clone()), &windirs, true).unwrap(),
+ real_home
+ );
+ fs::remove_dir_all(&real_home).ok();
+ }
+
+ #[test]
+ fn relative_path_overrides_are_pinned_only_when_the_child_moves() {
+ let cwd = PathBuf::from("C:\\Windows\\System32");
+ let work_dir = PathBuf::from("C:\\Users\\me\\.unsloth");
+ let env = |name: &str| match name {
+ "HF_HOME" => Some("cache".to_string()),
+ // A name the child keeps: the two Studio roots are removed for
+ // every managed spawn, so they are never pinned.
+ "UNSLOTH_COMPILE_LOCATION" => Some(" studio ".to_string()),
+ "OLLAMA_MODELS" => Some("D:\\models".to_string()),
+ "HF_HUB_CACHE" => Some("C:\\hub".to_string()),
+ "XDG_CACHE_HOME" => Some(" ".to_string()),
+ "LLAMA_SERVER_PATH" => Some("\\srv\\llama-server".to_string()),
+ // Relative to drive D's own current directory, not to the cwd.
+ "HF_DATASETS_CACHE" => Some("D:datasets".to_string()),
+ _ => None,
+ };
+ // What GetFullPathNameW would answer: drive D's own current directory,
+ // and the current drive for a root-relative value.
+ let absolute = |value: &str| match value {
+ "D:datasets" => Some(PathBuf::from("D:\\work\\datasets")),
+ "\\srv\\llama-server" => Some(PathBuf::from("C:\\srv\\llama-server")),
+ other => panic!("unexpected value needing the OS: {other}"),
+ };
+
+ let pins =
+ relative_override_pins_from(Some(cwd.clone()), &work_dir, env, absolute, Some(std::path::Path::new("C:\\Users\\me")), MANAGED_CHILD_SCRUBBED_ENV, true).unwrap();
+ assert_eq!(
+ pins,
+ vec![
+ // Root-relative: the drive is the current one, which the move
+ // can change, so the OS resolves it before that happens.
+ (
+ "LLAMA_SERVER_PATH",
+ PathBuf::from("C:\\srv\\llama-server")
+ ),
+ ("UNSLOTH_COMPILE_LOCATION", cwd.join("studio")),
+ ("HF_HOME", cwd.join("cache")),
+ (
+ "HF_DATASETS_CACHE",
+ PathBuf::from("D:\\work\\datasets")
+ ),
+ ],
+ "only values that name no directory on their own are rewritten"
+ );
+
+ // An unresolvable drive-relative value refuses the whole move rather
+ // than being dropped: a child moved with that override still relative
+ // would read and write somewhere else than the caller named.
+ assert!(relative_override_pins_from(Some(cwd.clone()), &work_dir, env, |_| None, Some(std::path::Path::new("C:\\Users\\me")), MANAGED_CHILD_SCRUBBED_ENV, true).is_err());
+
+ // Staying put is the common case: nothing is rewritten, so a desktop
+ // started from a project folder keeps every override as it was.
+ assert!(
+ relative_override_pins_from(Some(work_dir.clone()), &work_dir, env, absolute, Some(std::path::Path::new("C:\\Users\\me")), MANAGED_CHILD_SCRUBBED_ENV, true)
+ .unwrap()
+ .is_empty()
+ );
+ // The directory being left is unknown, so a relative override cannot be
+ // anchored to it and the move is refused rather than retargeting it.
+ assert!(relative_override_pins_from(None, &work_dir, env, absolute, Some(std::path::Path::new("C:\\Users\\me")), MANAGED_CHILD_SCRUBBED_ENV, true).is_err());
+ // With nothing relative left to preserve, an unknown directory is fine.
+ let absolute_only = |name: &str| match name {
+ "HF_HOME" => Some("D:\\cache".to_string()),
+ "HF_HUB_CACHE" => Some("C:\\hub".to_string()),
+ // Removed for every managed child, so never in the way.
+ "UNSLOTH_STUDIO_HOME" => Some("studio".to_string()),
+ _ => None,
+ };
+ assert!(
+ relative_override_pins_from(None, &work_dir, absolute_only, absolute, Some(std::path::Path::new("C:\\Users\\me")), MANAGED_CHILD_SCRUBBED_ENV, true)
+ .unwrap()
+ .is_empty()
+ );
+ }
+
+ #[test]
+ fn a_profile_that_is_not_there_yet_stops_a_managed_child_but_not_the_installer() {
+ // The installer built the profile as it went before it shared this
+ // resolver; a managed child that created one would leave an empty folder
+ // shadowing the roaming profile when it finally arrives.
+ let missing = scratch("absent-profile").join("someone");
+ let error = managed_cli_working_dir_from(Some(missing.clone()), &[]).unwrap_err();
+ assert!(error.contains("not reachable"), "unexpected error: {error}");
+ assert_eq!(
+ install_working_dir(Some(missing.clone())).unwrap(),
+ missing.join(".unsloth")
+ );
+ assert!(missing.join(".unsloth").is_dir());
+ fs::remove_dir_all(missing.parent().unwrap()).ok();
+ }
+
+ #[test]
+ fn the_update_child_skips_the_value_the_windows_update_drops_anyway() {
+ // build_update_command removes PYTHONPATH on Windows, so pinning it there
+ // could only refuse an update over a value the child never receives.
+ let skipped = update_child_skipped_env();
+ assert_eq!(
+ skipped.contains(&"PYTHONPATH"),
+ cfg!(windows),
+ "PYTHONPATH is skipped exactly where the update drops it"
+ );
+ // STUDIO_LOCAL_REPO stays: the update is the one child that reads it.
+ assert!(!skipped.contains(&"STUDIO_LOCAL_REPO"));
+ assert!(child_skipped_env().contains(&"STUDIO_LOCAL_REPO"));
+ }
+
+ #[test]
+ fn a_posix_list_is_split_and_joined_with_its_own_separator() {
+ // The lost-directory branch already reads POSIX rules; the moving path
+ // has to as well, or "plugins:vendor" is one entry and both import roots
+ // leave with it.
+ let cwd = PathBuf::from("/mnt/work/session");
+ let work_dir = PathBuf::from("/home/me/.unsloth");
+ let pins = relative_override_pins_from(
+ Some(cwd.clone()),
+ &work_dir,
+ |name: &str| (name == "PYTHONPATH").then(|| "plugins:/opt/vendor".to_string()),
+ |value: &str| panic!("unexpected value needing the OS: {value}"),
+ Some(std::path::Path::new("/home/me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ false,
+ )
+ .unwrap();
+ assert_eq!(
+ pins,
+ vec![(
+ "PYTHONPATH",
+ PathBuf::from(format!("{}:/opt/vendor", cwd.join("plugins").display()))
+ )]
+ );
+ }
+
+ #[test]
+ fn a_scalar_that_would_not_fit_is_reported_too() {
+ // Anchoring a value that was already near the limit can cross it, and
+ // CreateProcess is too late to say which setting did.
+ let cwd = PathBuf::from("C:\\Windows\\System32");
+ let long = "x".repeat(WINDOWS_ENV_VALUE_LIMIT);
+ let error = relative_override_pins_from(
+ Some(cwd),
+ std::path::Path::new("C:\\Users\\me\\.unsloth"),
+ |name: &str| (name == "HF_HOME").then(|| long.clone()),
+ |value: &str| panic!("unexpected value needing the OS: {value}"),
+ Some(std::path::Path::new("C:\\Users\\me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true,
+ )
+ .unwrap_err();
+ assert!(error.starts_with("HF_HOME does not fit"), "{error}");
+ }
+
+ #[test]
+ fn a_posix_reader_expands_its_own_spelling_and_no_other() {
+ // posixpath.expandvars reads $NAME and ${NAME}; %NAME% is an ordinary
+ // filename there, so reading it the Windows way would call a relative
+ // value absolute and let the child move out from under it.
+ let lookup = |name: &str| match name {
+ "HOME" => Some("/home/me".to_string()),
+ _ => None,
+ };
+ assert_eq!(expand_posix_vars("$HOME/hf", &lookup), "/home/me/hf");
+ assert_eq!(expand_posix_vars("${HOME}/hf", &lookup), "/home/me/hf");
+ assert_eq!(expand_posix_vars("%HOME%/hf", &lookup), "%HOME%/hf");
+ assert_eq!(expand_posix_vars("$UNSET/hf", &lookup), "$UNSET/hf");
+ assert_eq!(expand_posix_vars("${UNTERMINATED/hf", &lookup), "${UNTERMINATED/hf");
+ assert_eq!(expand_posix_vars("cost: $5", &lookup), "cost: $5");
+ assert_eq!(expand_posix_vars("plain/path", &lookup), "plain/path");
+
+ // And the lost-directory branch reads it that way: %HOME%/hf depends on
+ // where the process is standing, so the move is refused rather than
+ // taken with the value following it.
+ let error = relative_override_pins_from(
+ None,
+ std::path::Path::new("/home/me/.unsloth"),
+ |name: &str| match name {
+ "HOME" => Some("/home/me".to_string()),
+ "HF_HOME" => Some("%HOME%/hf".to_string()),
+ _ => None,
+ },
+ |value: &str| panic!("unexpected value needing the OS: {value}"),
+ Some(std::path::Path::new("/home/me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ false,
+ )
+ .unwrap_err();
+ assert!(error.contains("HF_HOME"), "{error}");
+ // The POSIX spelling of the same setting names one folder, so it passes.
+ assert_eq!(
+ relative_override_pins_from(
+ None,
+ std::path::Path::new("/home/me/.unsloth"),
+ |name: &str| match name {
+ "HOME" => Some("/home/me".to_string()),
+ "HF_HOME" => Some("$HOME/hf".to_string()),
+ _ => None,
+ },
+ |value: &str| panic!("unexpected value needing the OS: {value}"),
+ Some(std::path::Path::new("/home/me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ false,
+ )
+ .unwrap(),
+ Vec::new()
+ );
+ }
+
+ #[test]
+ fn a_list_that_would_not_fit_is_reported_rather_than_spawned() {
+ // Windows refuses the variable, and CreateProcess is too late to say
+ // which setting did it: the caller turns this into the same message as
+ // an unresolvable one, and offers no repair that would hit the same wall.
+ let cwd = PathBuf::from("C:\\Windows\\System32");
+ let work_dir = PathBuf::from("C:\\Users\\me\\.unsloth");
+ let long = std::iter::repeat("entry")
+ .take(WINDOWS_ENV_VALUE_LIMIT / 5)
+ .collect::<Vec<_>>()
+ .join(";");
+ let error = relative_override_pins_from(
+ Some(cwd),
+ &work_dir,
+ |name: &str| (name == "PYTHONPATH").then(|| long.clone()),
+ |value: &str| panic!("unexpected value needing the OS: {value}"),
+ Some(std::path::Path::new("C:\\Users\\me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true,
+ )
+ .unwrap_err();
+ assert!(error.starts_with("PYTHONPATH does not fit"), "{error}");
+ }
+
+ #[test]
+ fn the_tilde_follows_the_profile_the_cli_guard_reads() {
+ // ntpath.expanduser answers USERPROFILE, so a portable or overridden
+ // environment must not send the two layers to different folders.
+ let cwd = PathBuf::from("C:\\Windows\\System32");
+ let work_dir = PathBuf::from("C:\\Users\\me\\.unsloth");
+ let pins = relative_override_pins_from(
+ Some(cwd),
+ &work_dir,
+ |name: &str| match name {
+ "USERPROFILE" => Some("D:\\portable\\me".to_string()),
+ "UNSLOTH_LLAMA_CPP_PATH" => Some("~\\llama.cpp".to_string()),
+ _ => None,
+ },
+ |value: &str| panic!("unexpected value needing the OS: {value}"),
+ // What dirs::home_dir() would answer, which is not where the tilde
+ // points once USERPROFILE says otherwise.
+ Some(std::path::Path::new("C:\\Users\\me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true,
+ )
+ .unwrap();
+ assert_eq!(
+ pins,
+ vec![(
+ "UNSLOTH_LLAMA_CPP_PATH",
+ PathBuf::from("D:\\portable\\me\\llama.cpp")
+ )]
+ );
+ }
+
+ #[test]
+ fn the_pin_decision_is_a_table_with_no_other_outcomes() {
+ // Every combination of the three things the pinning looks at, so "nothing
+ // happens unless the directory is one the CLI refuses" is a table rather
+ // than a claim. The child either stays with nothing rewritten, moves with
+ // every relative setting anchored to the directory it left, or the caller
+ // is told exactly which setting could not be preserved. There is no
+ // fourth outcome.
+ let home = std::path::Path::new("C:\\Users\\me");
+ let work_dir = PathBuf::from("C:\\Users\\me\\.unsloth");
+ let cwds = [
+ (Some(PathBuf::from("C:\\Users\\me\\project")), "elsewhere"),
+ (Some(work_dir.clone()), "already-there"),
+ (Some(PathBuf::from("C:\\Windows\\System32")), "system"),
+ (None, "unknown"),
+ ];
+ let envs: [(&dyn Fn(&str) -> Option<String>, &str); 4] = [
+ (&|_: &str| None, "clean"),
+ (
+ &|name: &str| (name == "HF_HOME").then(|| "cache".to_string()),
+ "relative",
+ ),
+ (
+ &|name: &str| (name == "HF_HOME").then(|| "D:\\cache".to_string()),
+ "absolute",
+ ),
+ (
+ &|name: &str| {
+ (name == "UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH").then(|| "1".to_string())
+ },
+ "toggle",
+ ),
+ ];
+ let absolute = |value: &str| panic!("unexpected value needing the OS: {value}");
+ let mut table = Vec::new();
+ for (cwd, cwd_kind) in &cwds {
+ for (lookup, env_kind) in &envs {
+ let outcome = relative_override_pins_from(
+ cwd.clone(),
+ &work_dir,
+ lookup,
+ absolute,
+ Some(home),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true,
+ );
+ let cell = match &outcome {
+ Ok(pins) if pins.is_empty() => "nothing rewritten",
+ Ok(_) => "anchored to the directory being left",
+ Err(_) => "reported as unpreservable",
+ };
+ table.push((*cwd_kind, *env_kind, cell));
+ }
+ }
+ assert_eq!(
+ table,
+ vec![
+ ("elsewhere", "clean", "nothing rewritten"),
+ ("elsewhere", "relative", "anchored to the directory being left"),
+ ("elsewhere", "absolute", "nothing rewritten"),
+ ("elsewhere", "toggle", "nothing rewritten"),
+ // Staying put rewrites nothing whatever the environment holds.
+ ("already-there", "clean", "nothing rewritten"),
+ ("already-there", "relative", "nothing rewritten"),
+ ("already-there", "absolute", "nothing rewritten"),
+ ("already-there", "toggle", "nothing rewritten"),
+ ("system", "clean", "nothing rewritten"),
+ ("system", "relative", "anchored to the directory being left"),
+ ("system", "absolute", "nothing rewritten"),
+ ("system", "toggle", "nothing rewritten"),
+ // Nothing can be anchored to a directory with no name, so a
+ // relative setting is reported and the caller stays put.
+ ("unknown", "clean", "nothing rewritten"),
+ ("unknown", "relative", "reported as unpreservable"),
+ ("unknown", "absolute", "nothing rewritten"),
+ ("unknown", "toggle", "nothing rewritten"),
+ ]
+ );
+ }
+
+ #[test]
+ fn a_directory_that_cannot_be_named_leaves_the_child_where_it_is() {
+ // Nothing can be anchored to a directory this process cannot name, so the
+ // child stays in it rather than the spawn failing over a setting the
+ // command may never read. What it must not do is move and take the
+ // setting with it.
+ let work_dir = PathBuf::from("C:\\Users\\me\\.unsloth");
+ let relative = |name: &str| match name {
+ "DG_VISUAL_BIN" => Some("visual".to_string()),
+ _ => None,
+ };
+ let absolute = |value: &str| panic!("unexpected value needing the OS: {value}");
+ assert!(
+ relative_override_pins_from(
+ None,
+ &work_dir,
+ relative,
+ absolute,
+ Some(std::path::Path::new("C:\\Users\\me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true,
+ )
+ .is_err(),
+ "the pins still report what a move would lose"
+ );
+ // And the spawn path turns that report into staying put, without
+ // moving this process to prove it: an unpinnable environment plus a
+ // directory that cannot be named means the child stays where it is.
+ let unpinnable: Result<Vec<(&'static str, PathBuf)>, String> =
+ Err("DG_VISUAL_BIN is relative and the directory it was written against is gone"
+ .to_string());
+ assert_eq!(stay_put_on_lost_cwd(unpinnable.clone(), false), Ok(None));
+ assert!(stay_put_on_lost_cwd(unpinnable, true).is_err());
+ }
+
+ #[test]
+ fn an_expansion_that_stays_relative_refuses_the_move() {
+ // The reader expands once. When that still holds a reference the folder
+ // depends on where the process is standing, so the move is refused; when
+ // it already names a drive the value is left exactly as written.
+ fn pins(
+ lookup: impl Fn(&str) -> Option<String>,
+ ) -> Result<Vec<(&'static str, PathBuf)>, String> {
+ relative_override_pins_from(
+ Some(PathBuf::from("C:\\Windows\\System32")),
+ std::path::Path::new("C:\\Users\\me\\.unsloth"),
+ lookup,
+ |value: &str| panic!("unexpected value needing the OS: {value}"),
+ Some(std::path::Path::new("C:\\Users\\me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true,
+ )
+ }
+ let refused = |error: String| {
+ assert!(
+ error.contains("does not expand to one folder"),
+ "unexpected error: {error}"
+ );
+ };
+ // Nested: one pass leaves the reference NESTED itself holds.
+ refused(
+ pins(|name: &str| match name {
+ "USERPROFILE" => Some("C:\\Users\\me".to_string()),
+ "NESTED" => Some("%USERPROFILE%\\AppData\\Local".to_string()),
+ "HF_ASSETS_CACHE" => Some("%NESTED%\\assets".to_string()),
+ _ => None,
+ })
+ .unwrap_err(),
+ );
+ // Escaped: one pass turns %% into the reference it was protecting.
+ refused(
+ pins(|name: &str| match name {
+ "USERPROFILE" => Some("C:\\Users\\me".to_string()),
+ "XDG_CACHE_HOME" => Some("%%USERPROFILE%%\\xdg".to_string()),
+ _ => None,
+ })
+ .unwrap_err(),
+ );
+ // Self-referencing: no number of passes settles it.
+ refused(
+ pins(|name: &str| (name == "HF_HOME").then(|| "%HF_HOME%\\cache".to_string()))
+ .unwrap_err(),
+ );
+ // Already names a drive after one pass, so it means the same folder from
+ // anywhere and nothing is rewritten.
+ assert_eq!(
+ pins(|name: &str| (name == "HF_ASSETS_CACHE")
+ .then(|| "C:\\cache\\%UNSET%\\assets".to_string()))
+ .unwrap(),
+ Vec::new()
+ );
+ }
+
+ #[test]
+ fn the_model_paths_llama_server_reads_for_itself_are_pinned() {
+ // llama-server resolves these against its own working directory, so a
+ // relative one has to move with the child. The URL spelling names no
+ // local file.
+ let cwd = PathBuf::from("C:\\Windows\\System32");
+ let work_dir = PathBuf::from("C:\\Users\\me\\.unsloth");
+ let env = |name: &str| match name {
+ "LLAMA_ARG_MODEL" => Some("models\\qwen.gguf".to_string()),
+ "LLAMA_ARG_MMPROJ" => Some(".\\mmproj.gguf".to_string()),
+ "LLAMA_ARG_MODEL_DRAFT" => Some("draft.gguf".to_string()),
+ "LLAMA_ARG_SPEC_DRAFT_MODEL" => Some("D:\\drafts\\small.gguf".to_string()),
+ "LLAMA_ARG_MMPROJ_URL" => Some("https://example.invalid/proj.gguf".to_string()),
+ _ => None,
+ };
+ let absolute = |value: &str| panic!("unexpected value needing the OS: {value}");
+ let pins = relative_override_pins_from(
+ Some(cwd.clone()),
+ &work_dir,
+ env,
+ absolute,
+ Some(std::path::Path::new("C:\\Users\\me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true,
+ )
+ .unwrap();
+ assert_eq!(
+ pins,
+ vec![
+ ("LLAMA_ARG_MODEL", cwd.join("models\\qwen.gguf")),
+ ("LLAMA_ARG_MMPROJ", cwd.join(".\\mmproj.gguf")),
+ ("LLAMA_ARG_MODEL_DRAFT", cwd.join("draft.gguf")),
+ ]
+ );
+ }
+
+ #[test]
+ fn a_lost_directory_still_reads_a_setting_that_never_depended_on_it() {
+ // %LOCALAPPDATA%\hf, inline JSON and a toggle are the same three shapes
+ // the moving path exempts. Judging them raw here refused every managed
+ // spawn over values no directory ever decided.
+ let work_dir = std::path::PathBuf::from("C:\\Users\\me\\.unsloth");
+ let env = |name: &str| match name {
+ "LOCALAPPDATA" => Some("C:\\Users\\me\\AppData\\Local".to_string()),
+ "HF_HOME" => Some("%LOCALAPPDATA%\\hf".to_string()),
+ "MLX_HOSTFILE" => Some("[\"127.0.0.1\"]".to_string()),
+ "UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH" => Some("1".to_string()),
+ _ => None,
+ };
+ let absolute = |_: &str| None;
+ assert!(
+ relative_override_pins_from(
+ None,
+ &work_dir,
+ env,
+ absolute,
+ Some(std::path::Path::new("C:\\Users\\me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true
+ )
+ .unwrap()
+ .is_empty()
+ );
+ // A genuinely relative folder in the same list is still refused.
+ let with_relative = |name: &str| match name {
+ "UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH" => Some("1;models".to_string()),
+ _ => None,
+ };
+ assert!(
+ relative_override_pins_from(
+ None,
+ &work_dir,
+ with_relative,
+ absolute,
+ Some(std::path::Path::new("C:\\Users\\me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true
+ )
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn the_pinned_override_list_matches_the_cli_guard() {
+ // A name in one list and not the other means the same install places
+ // state in two folders, depending on which layer moved the child.
+ let guard = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../../unsloth_cli/_system_dir_guard.py");
+ let source = fs::read_to_string(&guard).unwrap();
+ let start = source.find("_RELATIVE_PATH_ENV = (").unwrap();
+ let block = &source[start..start + source[start..].find("\n)").unwrap()];
+ for name in RELATIVE_PATH_ENV {
+ assert!(
+ block.contains(&format!("\"{name}\"")),
+ "{name} is pinned by the desktop but not by the CLI guard"
+ );
+ }
+ let names = block.matches('"').count() / 2;
+ assert_eq!(
+ names,
+ RELATIVE_PATH_ENV.len(),
+ "the CLI guard pins names the desktop does not"
+ );
+ }
+
+ #[test]
+ fn a_missing_home_is_an_error_rather_than_a_fallback() {
+ let error = managed_cli_working_dir_from(None, &[]).unwrap_err();
+ assert!(
+ error.contains("home directory"),
+ "unexpected error: {error}"
+ );
+ }
+
+ #[test]
+ fn a_home_that_does_not_exist_is_rejected() {
+ let home = scratch("cwd-absent").join("gone");
+ let error = managed_cli_working_dir_from(Some(home), &[]).unwrap_err();
+ assert!(error.contains("not reachable"), "unexpected error: {error}");
+ }
+
+ #[test]
+ fn a_file_masquerading_as_a_home_is_rejected() {
+ let base = scratch("cwd-file-home");
+ let home = base.join("home-is-a-file");
+ fs::write(&home, b"not a directory").unwrap();
+ let error = managed_cli_working_dir_from(Some(home), &[]).unwrap_err();
+ assert!(error.contains("not reachable"), "unexpected error: {error}");
+ fs::remove_dir_all(&base).ok();
+ }
+
+ // The SYSTEM account's profile is C:\Windows\System32\config\systemprofile, so
+ // trusting the home API here would hand the child the folder it just rejected.
+ #[test]
+ fn a_home_inside_the_windows_directory_is_rejected() {
+ let windir = PathBuf::from("C:\\Windows");
+ for home in [
+ "C:\\Windows",
+ "C:\\Windows\\System32\\config\\systemprofile",
+ "C:\\Windows\\",
+ ] {
+ let error = managed_cli_working_dir_from(
+ Some(PathBuf::from(home)),
+ std::slice::from_ref(&windir),
+ )
+ .unwrap_err();
+ assert!(
+ error.contains("inside the Windows directory"),
+ "{home} must be rejected, got: {error}"
+ );
+ }
+ }
+
+ // The separator keeps the match on a path boundary, so a profile that merely
+ // starts with the same letters as the Windows directory is not rejected.
+ #[test]
+ fn a_home_that_merely_shares_a_prefix_with_the_windows_directory_is_allowed() {
+ let error = managed_cli_working_dir_from(
+ Some(PathBuf::from(r"C:\Windows2\Users\jane")),
+ &[PathBuf::from(r"C:\Windows")],
+ )
+ .unwrap_err();
+ assert!(
+ !error.contains("inside the Windows directory"),
+ "C:\\Windows2 is a normal folder, got: {error}"
+ );
+ }
+
+ // A WINDIR of "C:\" would otherwise swallow the whole drive.
+ #[test]
+ fn a_drive_root_windows_directory_does_not_reject_every_home() {
+ let error = managed_cli_working_dir_from(
+ Some(PathBuf::from(r"C:\Users\me")),
+ &[PathBuf::from("C:\\")],
+ )
+ .unwrap_err();
+ assert!(
+ !error.contains("inside the Windows directory"),
+ "unexpected rejection: {error}"
+ );
+ }
+
+ #[test]
+ fn forward_slashes_and_case_do_not_hide_the_windows_directory() {
+ let error = managed_cli_working_dir_from(
+ Some(PathBuf::from("c:/WINDOWS/System32/config/systemprofile")),
+ &[PathBuf::from(r"C:\Windows")],
+ )
+ .unwrap_err();
+ assert!(
+ error.contains("inside the Windows directory"),
+ "got: {error}"
+ );
+ }
+
+ // \\?\C:\Windows\... is the same folder spelled the long way; the Python
+ // guard strips the prefix too.
+ #[test]
+ fn an_extended_length_path_does_not_hide_the_windows_directory() {
+ let error = managed_cli_working_dir_from(
+ Some(PathBuf::from(
+ r"\\?\C:\Windows\System32\config\systemprofile",
+ )),
+ &[PathBuf::from(r"C:\Windows")],
+ )
+ .unwrap_err();
+ assert!(
+ error.contains("inside the Windows directory"),
+ "got: {error}"
+ );
+ }
+
+ // The pin exists to replace an unusable directory, not to relocate every
+ // launch: a desktop started from a project folder keeps resolving ./models
+ // and other cwd-relative defaults there, on every platform.
+ #[test]
+ fn a_usable_inherited_directory_is_kept() {
+ assert_eq!(
+ managed_cli_working_dir().expect("the test's own directory is usable"),
+ std::env::current_dir().unwrap()
+ );
+ }
+
+ #[test]
+ fn only_a_windows_directory_counts_as_unusable() {
+ let windirs = [PathBuf::from(r"C:\Windows")];
+ assert!(is_inside_windows_dir(
+ std::path::Path::new(r"C:\Windows\System32"),
+ &windirs
+ ));
+ assert!(!is_inside_windows_dir(
+ std::path::Path::new(r"D:\projects\llm"),
+ &windirs
+ ));
+ assert!(!is_inside_windows_dir(
+ std::path::Path::new("/home/me"),
+ &windirs
+ ));
+ }
+
+ // A WINDIR aimed at the user's profile would otherwise make this reject that
+ // profile, so the backend would never start anywhere on that machine.
+ #[test]
+ fn a_candidate_that_holds_no_system32_is_not_a_windows_directory() {
+ let roots = windows_roots_from(
+ vec![
+ PathBuf::from(r"C:\Windows"),
+ PathBuf::from(r"C:\Users\me"),
+ PathBuf::from(r"C:\Windows"),
+ ],
+ PathBuf::from(r"C:\Windows"),
+ |root| root == std::path::Path::new(r"C:\Windows"),
+ );
+ assert_eq!(roots, vec![PathBuf::from(r"C:\Windows")]);
+ }
+
+ #[test]
+ fn a_shadowed_windir_does_not_hide_the_real_windows_directory() {
+ let roots = windows_roots_from(
+ vec![PathBuf::from(r"D:\Windows"), PathBuf::from(r"C:\Users\me")],
+ PathBuf::from(r"D:\Windows"),
+ |root| root == std::path::Path::new(r"D:\Windows"),
+ );
+ assert_eq!(roots, vec![PathBuf::from(r"D:\Windows")]);
+ }
+
+ #[test]
+ fn nothing_that_looks_like_windows_falls_back_to_the_authoritative_value() {
+ let roots = windows_roots_from(
+ vec![PathBuf::from(r"E:\Windows"), PathBuf::from(r"C:\Users\me")],
+ PathBuf::from(r"E:\Windows"),
+ |_root| false,
+ );
+ assert_eq!(
+ roots,
+ vec![PathBuf::from(r"E:\Windows")],
+ "the guard must stay alive, and never on the settable value"
+ );
+ }
+
+ #[test]
+ fn a_configured_command_carries_the_directory_and_the_marker() {
+ // relative_override_pins reads the ambient environment, which another
+ // test may be swapping, so this takes the crate-wide env lock.
+ let _env = crate::native_path_policy::PROCESS_ENV_LOCK
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
+ let work_dir = scratch("cwd-command-shape");
+
+ let mut cmd = Command::new("unsloth");
+ apply_managed_cli_context_at(&mut cmd, &work_dir).unwrap();
+ assert_eq!(cmd.get_current_dir(), Some(work_dir.as_path()));
+ assert!(
+ cmd.get_envs()
+ .any(|(key, value)| key == DESKTOP_MANAGED_ENV && value == Some("1".as_ref())),
+ "the desktop marker must be set"
+ );
+ fs::remove_dir_all(&work_dir).ok();
+ }
+
+ #[test]
+ fn only_the_folders_the_cli_refuses_count_as_unusable() {
+ let windirs = [PathBuf::from("C:\\Windows")];
+ for unusable in [
+ "C:\\Windows\\System32",
+ "c:\\windows\\system32\\config\\systemprofile",
+ "C:\\Windows\\SysWOW64",
+ "\\\\?\\C:\\Windows\\System32",
+ ] {
+ assert!(
+ is_unusable_cwd(std::path::Path::new(unusable), &windirs),
+ "{unusable} must be replaced"
+ );
+ }
+ for usable in [
+ // The guard has always allowed these, so a child that was running
+ // from one keeps running from it.
+ "C:\\Windows\\Temp\\project",
+ "C:\\Windows",
+ "C:\\Windows2\\System32",
+ "C:\\Users\\me\\projects",
+ ] {
+ assert!(
+ !is_unusable_cwd(std::path::Path::new(usable), &windirs),
+ "{usable} must be kept"
+ );
+ }
+ }
+
+ #[test]
+ fn an_extended_unc_path_compares_the_same_in_either_case() {
+ // The object manager accepts \\?\unc\, so a profile spelled that way
+ // must not be read as a relative name.
+ assert_eq!(
+ normalize_windows_path(std::path::Path::new("\\\\?\\UNC\\server\\profiles\\me")),
+ normalize_windows_path(std::path::Path::new("\\\\?\\unc\\server\\profiles\\me"))
+ );
+ assert!(is_fully_qualified("\\\\?\\unc\\server\\profiles\\me"));
+ assert!(is_fully_qualified("\\\\?\\UNC\\server\\profiles\\me"));
+ }
+
+ #[test]
+ fn a_lost_directory_is_judged_entry_by_entry() {
+ // "C:\\vendor;plugins" starts with a drive and still carries something
+ // the directory that is gone decided.
+ let work_dir = PathBuf::from("C:\\Users\\me\\.unsloth");
+ let home = Some(std::path::Path::new("C:\\Users\\me"));
+ let mixed = |name: &str| match name {
+ "PYTHONPATH" => Some("C:\\vendor;plugins".to_string()),
+ _ => None,
+ };
+ assert!(relative_override_pins_from(
+ None,
+ &work_dir,
+ mixed,
+ |_| None,
+ home,
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true
+ )
+ .is_err());
+ // Every entry qualified: nothing is left depending on it.
+ let qualified = |name: &str| match name {
+ "PYTHONPATH" => Some("C:\\vendor;D:\\plugins".to_string()),
+ _ => None,
+ };
+ assert!(relative_override_pins_from(
+ None,
+ &work_dir,
+ qualified,
+ |_| None,
+ home,
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true
+ )
+ .unwrap()
+ .is_empty());
+ }
+
+ #[test]
+ fn a_lost_directory_reads_a_posix_environment_by_posix_rules() {
+ // Off Windows the same fallback runs, and what it reads there is a POSIX
+ // environment. Judging /var/cache/unsloth by the Windows rules called it
+ // relative and failed preflight and every managed spawn over a setting
+ // that was never relative.
+ let work_dir = PathBuf::from("/home/me/.unsloth");
+ let home = Some(std::path::Path::new("/home/me"));
+ let posix = |name: &str| match name {
+ "XDG_CACHE_HOME" => Some("/var/cache/unsloth".to_string()),
+ _ => None,
+ };
+ assert!(
+ relative_override_pins_from(
+ None,
+ &work_dir,
+ posix,
+ |_| None,
+ home,
+ MANAGED_CHILD_SCRUBBED_ENV,
+ false
+ )
+ .unwrap()
+ .is_empty()
+ );
+ // Something genuinely relative is still refused.
+ let relative = |name: &str| match name {
+ "XDG_CACHE_HOME" => Some("cache".to_string()),
+ _ => None,
+ };
+ assert!(relative_override_pins_from(
+ None,
+ &work_dir,
+ relative,
+ |_| None,
+ home,
+ MANAGED_CHILD_SCRUBBED_ENV,
+ false
+ )
+ .is_err());
+ // A POSIX list is separated by ':', so a relative entry behind an
+ // absolute one is still caught.
+ let mixed = |name: &str| match name {
+ "PYTHONPATH" => Some("/opt/vendor:plugins".to_string()),
+ _ => None,
+ };
+ assert!(relative_override_pins_from(
+ None,
+ &work_dir,
+ mixed,
+ |_| None,
+ home,
+ MANAGED_CHILD_SCRUBBED_ENV,
+ false
+ )
+ .is_err());
+ // And on Windows the same value stays Windows-judged: "/var/cache" is
+ // the root of whichever drive the process is on.
+ assert!(relative_override_pins_from(
+ None,
+ &PathBuf::from("C:\\Users\\me\\.unsloth"),
+ posix,
+ |_| None,
+ Some(std::path::Path::new("C:\\Users\\me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true
+ )
+ .is_err());
+ }
+
+ #[test]
+ fn only_the_update_child_carries_the_local_checkout() {
+ // STUDIO_LOCAL_REPO is read by the update and installer path alone, so a
+ // stale one must not fail a probe or a backend start that ignores it.
+ let cwd = PathBuf::from("C:\\Windows\\System32");
+ let work_dir = PathBuf::from("C:\\Users\\me\\.unsloth");
+ let home = Some(std::path::Path::new("C:\\Users\\me"));
+ let env = |name: &str| match name {
+ "STUDIO_LOCAL_REPO" => Some("..\\src\\unsloth".to_string()),
+ _ => None,
+ };
+ let for_update = relative_override_pins_from(
+ Some(cwd.clone()),
+ &work_dir,
+ env,
+ |_| None,
+ home,
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true,
+ )
+ .unwrap();
+ assert_eq!(
+ for_update,
+ vec![("STUDIO_LOCAL_REPO", cwd.join("..\\src\\unsloth"))]
+ );
+ let for_child = relative_override_pins_from(
+ Some(cwd),
+ &work_dir,
+ env,
+ |_| None,
+ home,
+ &child_skipped_env(),
+ true,
+ )
+ .unwrap();
+ assert!(for_child.is_empty(), "a child that ignores it must not pin it");
+ }
+
+ #[test]
+ fn a_tilde_is_written_out_the_way_expanduser_writes_it() {
+ let home = std::path::Path::new("C:\\Users\\me");
+ let me = Some("me");
+ assert_eq!(expand_windows_user("~", home, me), "C:\\Users\\me");
+ assert_eq!(
+ expand_windows_user("~\\llama.cpp", home, me),
+ "C:\\Users\\me\\llama.cpp"
+ );
+ assert_eq!(
+ expand_windows_user("~/llama.cpp", home, me),
+ "C:\\Users\\me/llama.cpp"
+ );
+ // ~name is the sibling profile, as ntpath resolves it.
+ assert_eq!(expand_windows_user("~other\\x", home, me), "C:\\Users\\other\\x");
+ // ~me is this profile whatever the folder is called.
+ let domain = std::path::Path::new("C:\\Users\\me.DOMAIN");
+ assert_eq!(expand_windows_user("~me\\x", domain, me), "C:\\Users\\me.DOMAIN\\x");
+ // And ntpath declines to guess a sibling when this profile is not named
+ // after the current user, so neither does this.
+ assert_eq!(expand_windows_user("~other\\x", domain, me), "~other\\x");
+ assert_eq!(expand_windows_user("~other\\x", home, None), "~other\\x");
+ // Nothing else is touched.
+ for value in ["cache", "C:\\cache", "a~b"] {
+ assert_eq!(expand_windows_user(value, home, me), value);
+ }
+ }
+
+ #[test]
+ fn every_spelling_expandvars_takes_is_expanded_here_too() {
+ let lookup = |name: &str| match name {
+ "LOCALAPPDATA" => Some("C:\\Users\\me\\AppData\\Local".to_string()),
+ // ntpath counts the hyphen as part of a $ name, so this one has to
+ // win over a lookup of "CACHE".
+ "CACHE-ROOT" => Some("C:\\right".to_string()),
+ "CACHE" => Some("C:\\wrong".to_string()),
+ "TWO WORDS" => Some("C:\\spaced".to_string()),
+ _ => None,
+ };
+ // The three forms os.path.expandvars takes on a Windows path.
+ for value in [
+ "%LOCALAPPDATA%\\hf",
+ "$LOCALAPPDATA\\hf",
+ "${LOCALAPPDATA}\\hf",
+ ] {
+ assert_eq!(
+ expand_windows_vars(value, &lookup),
+ "C:\\Users\\me\\AppData\\Local\\hf",
+ "{value} did not expand the way the CLI guard expands it"
+ );
+ }
+ assert_eq!(expand_windows_vars("$CACHE-ROOT\\hf", &lookup), "C:\\right\\hf");
+ // A percent name may hold spaces; a dollar name stops at the dot.
+ assert_eq!(expand_windows_vars("%TWO WORDS%\\x", &lookup), "C:\\spaced\\x");
+ assert_eq!(expand_windows_vars("$CACHE.d", &lookup), "C:\\wrong.d");
+ // Doubled markers stand for one character.
+ assert_eq!(expand_windows_vars("100%%", &lookup), "100%");
+ assert_eq!(expand_windows_vars("$$HOME", &lookup), "$HOME");
+ // A quoted run is copied through, so what is inside it is not expanded.
+ assert_eq!(
+ expand_windows_vars("'%LOCALAPPDATA%'\\hf", &lookup),
+ "'%LOCALAPPDATA%'\\hf"
+ );
+ // Unset names, unterminated references and a lone marker stay as written.
+ for value in [
+ "%NOT_SET%\\hub",
+ "$NOT_SET\\hub",
+ "${LOCALAPPDATA\\hf",
+ "%LOCALAPPDATA\\hf",
+ "a$b",
+ "$",
+ "50% off",
+ // Non-ASCII, which \w under re.ASCII does not match: the byte walk
+ // must step over it whole rather than split the character.
+ "caché\\modèles",
+ ] {
+ assert_eq!(
+ expand_windows_vars(value, &lookup),
+ value,
+ "{value} was rewritten and should not have been"
+ );
+ }
+ }
+
+ #[test]
+ fn the_pythonpath_spellings_that_follow_the_process_are_anchored() {
+ // An empty component is the working directory, and `~` is never expanded
+ // in PYTHONPATH, so Python reads it as an ordinary relative folder.
+ let cwd = PathBuf::from("C:\\Windows\\System32");
+ let work_dir = PathBuf::from("C:\\Users\\me\\.unsloth");
+ let pins = relative_override_pins_from(
+ Some(cwd.clone()),
+ &work_dir,
+ |name| match name {
+ "PYTHONPATH" => Some(";~\\plugins;C:\\shared\\lib".to_string()),
+ _ => None,
+ },
+ |_| None,
+ Some(std::path::Path::new("C:\\Users\\me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true,
+ )
+ .unwrap();
+ // `~\plugins` is anchored as the literal relative folder Python reads,
+ // not turned into the profile the interpreter was never looking at.
+ let expected = format!(
+ "{};{};C:\\shared\\lib",
+ cwd.to_string_lossy(),
+ // join, like the anchoring does, so the separator is the host's.
+ cwd.join("~\\plugins").to_string_lossy()
+ );
+ assert_eq!(pins, vec![("PYTHONPATH", PathBuf::from(expected))]);
+ }
+
+ #[test]
+ fn a_cache_override_is_expanded_before_it_is_judged() {
+ // One reader expands %LOCALAPPDATA% and one does not, so the value is
+ // written out here and both then see the same folder.
+ let cwd = PathBuf::from("C:\\Windows\\System32");
+ let work_dir = PathBuf::from("C:\\Users\\me\\.unsloth");
+ let pins = relative_override_pins_from(
+ Some(cwd.clone()),
+ &work_dir,
+ |name| match name {
+ "LOCALAPPDATA" => Some("C:\\Users\\me\\AppData\\Local".to_string()),
+ "HF_HOME" => Some("%LOCALAPPDATA%\\hf".to_string()),
+ // A name this machine does not set stays as written, and is
+ // anchored like any other relative value.
+ "HF_HUB_CACHE" => Some("%NOT_SET%\\hub".to_string()),
+ _ => None,
+ },
+ |_| None,
+ Some(std::path::Path::new("C:\\Users\\me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true,
+ )
+ .unwrap();
+ assert_eq!(
+ pins,
+ vec![
+ (
+ "HF_HOME",
+ PathBuf::from("C:\\Users\\me\\AppData\\Local\\hf")
+ ),
+ ("HF_HUB_CACHE", cwd.join("%NOT_SET%\\hub")),
+ ],
+ "an expanded cache override must name one folder for both readers"
+ );
+ }
+
+ #[test]
+ fn an_exemption_only_applies_to_the_variable_that_supports_it() {
+ // A directory really called "[llama]" or "%data%" is legal on Windows,
+ // and the readers of these two names take it as exactly that.
+ let cwd = PathBuf::from("C:\\Windows\\System32");
+ let work_dir = PathBuf::from("C:\\Users\\me\\.unsloth");
+ let pins = relative_override_pins_from(
+ Some(cwd.clone()),
+ &work_dir,
+ |name| match name {
+ "UNSLOTH_LLAMA_CPP_PATH" => Some("[llama]".to_string()),
+ "UNSLOTH_COMPILE_LOCATION" => Some("%data%".to_string()),
+ _ => None,
+ },
+ |_| None,
+ Some(std::path::Path::new("C:\\Users\\me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true,
+ )
+ .unwrap();
+ assert_eq!(
+ pins,
+ vec![
+ ("UNSLOTH_LLAMA_CPP_PATH", cwd.join("[llama]")),
+ ("UNSLOTH_COMPILE_LOCATION", cwd.join("%data%")),
+ ],
+ "a legal directory name was mistaken for JSON or a placeholder"
+ );
+ }
+
+ #[test]
+ fn a_value_the_working_directory_does_not_resolve_is_left_alone() {
+ // Three readers in the tree treat these as something other than a path,
+ // so anchoring one would change its meaning rather than preserve it.
+ let cwd = PathBuf::from("C:\\Windows\\System32");
+ let work_dir = PathBuf::from("C:\\Users\\me\\.unsloth");
+ let pins = relative_override_pins_from(
+ Some(cwd),
+ &work_dir,
+ |name| match name {
+ // MLX_HOSTFILE holds either a filename or the host list itself.
+ "MLX_HOSTFILE" => Some("[{\"ssh\": \"node0\"}]".to_string()),
+ // A bare toggle is ignored on purpose: there is no "allow all".
+ "UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH" => Some("1".to_string()),
+ _ => None,
+ },
+ |_| None,
+ Some(std::path::Path::new("C:\\Users\\me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true,
+ )
+ .unwrap();
+ assert!(pins.is_empty(), "a non-path value was rewritten: {pins:?}");
+ }
+
+ #[test]
+ fn each_entry_of_a_path_list_is_anchored_on_its_own() {
+ let cwd = PathBuf::from("C:\\Windows\\System32");
+ let work_dir = PathBuf::from("C:\\Users\\me\\.unsloth");
+ let pins = relative_override_pins_from(
+ Some(cwd.clone()),
+ &work_dir,
+ |name| match name {
+ "UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH" => {
+ Some("trusted;D:\\shared;~\\mine".to_string())
+ }
+ _ => None,
+ },
+ |_| None,
+ Some(std::path::Path::new("C:\\Users\\me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true,
+ )
+ .unwrap();
+ // `~` is written out: only some readers of these names expand it.
+ let expected = format!(
+ "{};D:\\shared;C:\\Users\\me\\mine",
+ cwd.join("trusted").to_string_lossy()
+ );
+ assert_eq!(
+ pins,
+ vec![(
+ "UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH",
+ PathBuf::from(expected)
+ )],
+ "a relative entry must not authorise a different directory after the move"
+ );
+ }
+
+ #[test]
+ fn configuring_a_command_twice_changes_nothing() {
+ // relative_override_pins reads the ambient environment, which another
+ // test may be swapping, so this takes the crate-wide env lock.
+ let _env = crate::native_path_policy::PROCESS_ENV_LOCK
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
+ let work_dir = scratch("cwd-command-twice");
+
+ let mut once = Command::new("unsloth");
+ apply_managed_cli_context_at(&mut once, &work_dir).unwrap();
+ let mut twice = Command::new("unsloth");
+ apply_managed_cli_context_at(&mut twice, &work_dir).unwrap();
+ apply_managed_cli_context_at(&mut twice, &work_dir).unwrap();
+
+ let envs = |cmd: &Command| {
+ let mut pairs: Vec<(String, Option<String>)> = cmd
+ .get_envs()
+ .map(|(key, value)| {
+ (
+ key.to_string_lossy().into_owned(),
+ value.map(|v| v.to_string_lossy().into_owned()),
+ )
+ })
+ .collect();
+ pairs.sort();
+ pairs.dedup();
+ pairs
+ };
+ assert_eq!(envs(&once), envs(&twice));
+ assert_eq!(twice.get_current_dir(), Some(work_dir.as_path()));
+ fs::remove_dir_all(&work_dir).ok();
+ }
+
+ #[test]
+ fn pinning_an_already_pinned_value_is_a_no_op() {
+ // The child's environment reaches grandchildren, and the desktop
+ // resolves the directory again on every spawn, so the rewrite has to
+ // land on the same value however many times it runs.
+ let cwd = PathBuf::from("C:\\Windows\\System32");
+ let work_dir = PathBuf::from("C:\\Users\\me\\.unsloth");
+ let absolute = |_: &str| Some(PathBuf::from("D:\\work\\datasets"));
+
+ let mut values = vec![
+ ("HF_HOME", "cache".to_string()),
+ ("HF_DATASETS_CACHE", "D:datasets".to_string()),
+ ];
+ for round in 0..3 {
+ let pins = relative_override_pins_from(
+ Some(cwd.clone()),
+ &work_dir,
+ |name| {
+ values
+ .iter()
+ .find(|(key, _)| *key == name)
+ .map(|(_, value)| value.clone())
+ },
+ absolute,
+ Some(std::path::Path::new("C:\\Users\\me")),
+ MANAGED_CHILD_SCRUBBED_ENV,
+ true,
+ )
+ .unwrap();
+ if round == 0 {
+ assert_eq!(pins.len(), 2, "the first pass rewrites both values");
+ } else {
+ assert!(pins.is_empty(), "pass {round} rewrote an anchored value");
+ }
+ for (name, pinned) in pins {
+ let slot = values.iter_mut().find(|(key, _)| *key == name).unwrap();
+ slot.1 = pinned.to_string_lossy().into_owned();
+ }
+ }
+ // The separator is whatever this platform's join produces; the point is
+ // that the value stopped moving after the first pass.
+ assert_eq!(values[0].1, cwd.join("cache").to_string_lossy());
+ assert_eq!(values[1].1, "D:\\work\\datasets");
+ assert!(is_fully_qualified(&values[0].1) && is_fully_qualified(&values[1].1));
+ }
+
+ #[test]
+ fn a_configured_tokio_command_carries_the_directory_and_the_marker() {
+ // relative_override_pins reads the ambient environment, which another
+ // test may be swapping, so this takes the crate-wide env lock.
+ let _env = crate::native_path_policy::PROCESS_ENV_LOCK
+ .lock()
+ .unwrap_or_else(|e| e.into_inner());
+ let expected = managed_cli_working_dir().expect("home must resolve");
+ let mut tokio_cmd = tokio::process::Command::new("unsloth");
+ apply_managed_cli_context_tokio(&mut tokio_cmd).expect("context must apply");
+ // Under test the resolver keeps this process's own directory, and the
+ // child inherits it rather than reopening it by name.
+ let configured = tokio_cmd.as_std().get_current_dir();
+ match std::env::current_dir() {
+ Ok(cwd) if cwd == expected => assert_eq!(configured, None),
+ _ => assert_eq!(configured, Some(expected.as_path())),
+ }
+ assert!(
+ tokio_cmd
+ .as_std()
+ .get_envs()
+ .any(|(key, value)| key == DESKTOP_MANAGED_ENV && value == Some("1".as_ref())),
+ "the desktop marker must be set on tokio commands too"
+ );
+ }
+
+ // The marker only helps if the Python side reads the same name; a rename on
+ // either side degrades silently to argv matching, which is the fallback path.
+ #[test]
+ fn the_marker_name_matches_the_python_guard() {
+ let guard = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
+ .join("../../unsloth_cli/_system_dir_guard.py");
+ let source = fs::read_to_string(&guard).expect("the Python guard must be readable");
+ assert!(
+ source.contains(&format!("DESKTOP_MANAGED_ENV = \"{DESKTOP_MANAGED_ENV}\"")),
+ "{} must define the same marker name",
+ guard.display()
+ );
+ }
+
+ // Configuring a child must not move the desktop process itself: a global chdir
+ // would change relative path resolution for dialogs, the updater and cleanup.
+ #[test]
+ fn configuring_a_child_leaves_the_parent_directory_alone() {
+ let before = std::env::current_dir().unwrap();
+ let work_dir = scratch("cwd-parent-untouched");
+ let mut cmd = Command::new("unsloth");
+ apply_managed_cli_context_at(&mut cmd, &work_dir).unwrap();
+ assert_eq!(std::env::current_dir().unwrap(), before);
+ fs::remove_dir_all(&work_dir).ok();
+ }
+
+ #[test]
+ fn backend_args_are_unchanged_by_the_working_directory_fix() {
+ assert_eq!(
+ backend_args(8888),
+ vec!["studio", "--api-only", "-H", "127.0.0.1", "-p", "8888"]
+ );
+ }
+
+ // 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)]
+ #[test]
+ fn a_spawned_child_runs_from_the_resolved_directory_on_windows() {
+ let expected = scratch("cwd-spawned-child-win");
+
+ let mut cmd = Command::new("cmd.exe");
+ cmd.args(["/C", "cd"]).stdout(Stdio::piped());
+ apply_managed_cli_context_at(&mut cmd, &expected).unwrap();
+ let output = cmd.output().expect("spawn test child");
+ let reported = String::from_utf8_lossy(&output.stdout).trim().to_string();
+
+ assert_eq!(
+ normalize_windows_path(std::path::Path::new(&reported)),
+ normalize_windows_path(&expected)
+ );
+ fs::remove_dir_all(&expected).ok();
+ }
+
+ // The end of the chain the bug actually broke: the child must observe the chosen
+ // directory, including through the unix process-group wrapper used by start_backend.
+ #[cfg(unix)]
+ #[test]
+ fn a_spawned_child_runs_from_the_resolved_directory() {
+ let expected = scratch("cwd-spawned-child");
+
+ let mut cmd = Command::new("/bin/sh");
+ cmd.args(["-c", "pwd -P"]).stdout(Stdio::piped());
+ apply_managed_cli_context_at(&mut cmd, &expected).unwrap();
+ let mut wrap = CommandWrap::from(cmd);
+ wrap.wrap(ProcessGroup::leader());
+ let mut child = wrap.spawn().expect("spawn test child");
+ let mut out = String::new();
+ std::io::Read::read_to_string(child.stdout().as_mut().unwrap(), &mut out).unwrap();
+ let _ = child.wait();
+
+ assert_eq!(
+ std::fs::canonicalize(out.trim()).unwrap(),
+ std::fs::canonicalize(&expected).unwrap()
+ );
+ }
+}
+
// The race this pins is not visible from the type system, so it uses real processes
// rather than a mock: a child's stdout pipe can EOF a moment before the kernel reports
// the exit, and a single non-blocking try_wait() at that instant returns Ok(None). The
diff --git a/studio/src-tauri/src/update.rs b/studio/src-tauri/src/update.rs
index fffdf3493be..5cf36deb757 100644
--- a/studio/src-tauri/src/update.rs
+++ b/studio/src-tauri/src/update.rs
@@ -97,6 +97,18 @@ fn spawn_update(
let mut cmd = build_update_command(bin)?;
cmd.stdout(Stdio::piped()).stderr(Stdio::piped());
+ // 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.
+ crate::process::apply_managed_cli_context(&mut cmd).map_err(|error| {
+ format!(
+ "Failed to pick a working directory for the update: {}",
+ error
+ )
+ })?;
+
+ // 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);
diff --git a/tests/test_installer_system32_guard.py b/tests/test_installer_system32_guard.py
index 07608e28b79..8112050584a 100644
--- a/tests/test_installer_system32_guard.py
+++ b/tests/test_installer_system32_guard.py
@@ -7,12 +7,14 @@ download, then roll back), and the CLI guard must name the folder and how to get
from __future__ import annotations
+import importlib.util
import ntpath
import os
import re
import shutil
import subprocess
import types
+from unittest import mock
from pathlib import Path
import pytest
@@ -22,6 +24,18 @@ INSTALL_PS1 = REPO_ROOT / "install.ps1"
CLI_INIT = REPO_ROOT / "unsloth_cli" / "__init__.py"
+def _load_guard_module():
+ """Load the guard by path: importing the package would drag in typer and every command."""
+ path = REPO_ROOT / "unsloth_cli" / "_system_dir_guard.py"
+ spec = importlib.util.spec_from_file_location("unsloth_cli_system_dir_guard", path)
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
+
+
+_system_dir_guard = _load_guard_module()
+
+
# ── install.ps1: relocate before doing any work ──
@@ -306,60 +320,134 @@ def test_relocation_block_fails_fast_when_every_candidate_is_a_system_directory(
# ── unsloth_cli: the message the user actually reads ──
-class _FakeExit(Exception):
- def __init__(self, code: int = 0):
- self.code = code
+def _expand_windows_user(value: str, environ: dict[str, str]) -> str:
+ """The real ntpath.expanduser, against the fake environment."""
+ with mock.patch.dict(os.environ, environ, clear = True):
+ return ntpath.expanduser(value)
-def _run_cli_guard(
- cwd: str,
- argv: list[str] | None = None,
- userprofile: str = r"C:\Users\me",
- public: str | None = None,
-) -> tuple[str | None, int | None]:
- """Exec the CLI's win32 guard block with ntpath semantics; returns (message, exit code)."""
- src = CLI_INIT.read_text(encoding = "utf-8")
- start = src.index(' if (\n _sys.platform == "win32"\n ):')
- end = src.index("\n\n", src.index("raise typer.Exit(code = 1)", start))
- block = "\n".join(
- line[4:] if line.startswith(" ") else line for line in src[start:end].split("\n")
- )
+def _expand_windows_vars(value: str, environ: dict[str, str]) -> str:
+ """The real ntpath.expandvars, against the fake environment.
- captured: dict[str, object] = {}
+ Reimplementing it here would test the reimplementation: the guard is given
+ the same function it gets in production, reading the environment the test
+ describes rather than the host's.
+ """
+ with mock.patch.dict(os.environ, environ, clear = True):
+ return ntpath.expandvars(value)
- def _secho(
- message,
- fg = None,
- err = False,
- ):
- captured["message"] = message
+def _guard_outcome(
+ cwd: str | None,
+ argv: list[str] | None = None,
+ userprofile: str = r"C:\Users\me",
+ public: str | None = None,
+ environ_extra: dict[str, str] | None = None,
+ chdir_error: OSError | None = None,
+ getcwd_error: OSError | None = None,
+ makedirs_error: OSError | None = None,
+ windows_dirs: tuple[str, ...] = (r"C:\Windows",),
+ environ_out: dict[str, str] | None = None,
+ drive_cwd: dict[str, str] | None = None,
+ missing_homes: tuple[str, ...] = (),
+ syspath: list[str] | None = None,
+ real_paths: tuple[str, ...] = (),
+ pass_syspath: bool = True,
+ chdir_lands_in: str | None = None,
+) -> tuple[str | None, str | None, list[str]]:
+ """Run the guard with ntpath semantics; returns (message, colour, chdir calls)."""
+ real_windows_dirs = {
+ ntpath.normcase(ntpath.join(directory, "System32")) for directory in windows_dirs
+ }
environ = {"WINDIR": r"C:\Windows", "USERPROFILE": userprofile}
if public is not None:
environ["PUBLIC"] = public
- fake_typer = types.SimpleNamespace(secho = _secho, Exit = _FakeExit)
+ if environ_extra:
+ environ.update(environ_extra)
+
# ntpath for the path semantics, with expanduser pinned: the real one reads the host's
# HOME, and on Windows "~" is USERPROFILE, SYSTEM's included.
fake_path = types.SimpleNamespace(
normcase = ntpath.normcase,
normpath = ntpath.normpath,
join = ntpath.join,
+ isabs = ntpath.isabs,
+ splitdrive = ntpath.splitdrive,
expanduser = lambda _p: userprofile,
)
- fake_os = types.SimpleNamespace(
- path = fake_path,
+
+ def _abspath(value):
+ """Windows keeps a current directory per drive; only it can resolve these."""
+ drive, tail = ntpath.splitdrive(value)
+ base = (drive_cwd or {}).get(drive.upper())
+ if base is None:
+ raise OSError(f"no current directory for {drive}")
+ return ntpath.join(base, tail)
+
+ chdir_calls: list[str] = []
+ # The guard re-reads the directory after moving, so the fake has to move too.
+ current = {"cwd": cwd}
+
+ def _chdir(target):
+ chdir_calls.append(target)
+ if chdir_error is not None:
+ raise chdir_error
+ # A junction, or a profile that is itself inside the Windows tree: the
+ # call succeeds and the process ends up somewhere else than it asked for.
+ current["cwd"] = (
+ chdir_lands_in if chdir_lands_in is not None and target == _RELOCATED else target
+ )
+
+ def _getcwd():
+ if getcwd_error is not None:
+ raise getcwd_error
+ return current["cwd"]
+
+ def _makedirs(target, exist_ok = False):
+ if makedirs_error is not None:
+ raise makedirs_error
+
+ message, colour, fatal = _system_dir_guard.check_working_directory(
+ (argv or ["unsloth", "studio", "setup"])[1:],
+ environ,
+ "win32",
+ getcwd = _getcwd,
+ chdir = _chdir,
+ pathmod = fake_path,
sep = "\\",
- getcwd = lambda: cwd,
- environ = environ,
+ expanduser = lambda path: _expand_windows_user(path, environ),
+ makedirs = _makedirs,
+ # Only a folder that really holds System32 counts as a Windows directory.
+ isdir = lambda path: ntpath.normcase(path) in real_windows_dirs,
+ # sys.path entries are on disk only when the caller says so, the way the
+ # filesystem would answer.
+ exists = lambda path: ntpath.normcase(path) in {ntpath.normcase(p) for p in real_paths},
+ abspath = _abspath,
+ home_isdir = lambda path: ntpath.normcase(path)
+ not in {ntpath.normcase(home) for home in missing_homes},
+ # Windows expansion, from the same environment the guard is reading.
+ expandvars = lambda value: _expand_windows_vars(value, environ),
+ # The real sys.path belongs to pytest, so the guard gets a copy to pin.
+ # pass_syspath = False leaves it out, which is what the console script
+ # does: only then does the guard reach the real list.
+ **({"syspath": syspath if syspath is not None else []} if pass_syspath else {}),
)
- fake_sys = types.SimpleNamespace(platform = "win32", argv = argv or ["unsloth", "studio", "setup"])
+ if environ_out is not None:
+ environ_out.clear()
+ environ_out.update(environ)
+ assert fatal == (colour == "red"), "only a red message may stop the command"
+ return message, colour, chdir_calls
- namespace = {"_os": fake_os, "_sys": fake_sys, "typer": fake_typer}
- try:
- exec(compile(block, "cli_guard", "exec"), namespace)
- except _FakeExit as exit_signal:
- return captured.get("message"), exit_signal.code
- return captured.get("message"), None
+
+def _run_cli_guard(
+ cwd: str,
+ argv: list[str] | None = None,
+ userprofile: str = r"C:\Users\me",
+ public: str | None = None,
+) -> tuple[str | None, int | None]:
+ """(message, exit code) for a hand-typed command, which is never relocated."""
+ message, colour, _ = _guard_outcome(cwd, argv, userprofile, public)
+ return message, 1 if colour == "red" else None
@pytest.mark.parametrize(
@@ -471,3 +559,996 @@ def test_cli_guard_message_repeats_the_actual_command():
assert (
'unsloth train --model "my model"' in message
), "the retry line must reproduce the invoked command, re-quoting arguments with spaces"
+
+
+# ── "Run Unsloth at login" (issue #8510): the desktop cannot choose its own cwd ──
+#
+# Windows registers login startup as an HKCU Run value, which carries no working
+# directory, so Unsloth Desktop and every CLI child it spawns start in System32.
+# The commands it runs take no path from the user, so they move out of the folder
+# instead of refusing and leaving the user with a tray icon and no server.
+
+_RELOCATED = r"C:\Users\me\.unsloth"
+
+
+ "argv",
+ [
+ ["unsloth", "studio", "--api-only", "-H", "127.0.0.1", "-p", "8888"],
+ ["unsloth", "studio", "--api-only"],
+ ["unsloth", "studio", "provision-desktop-auth"],
+ ["unsloth", "studio", "desktop-capabilities", "--json"],
+ # The command that upgrades a desktop too old to set the marker; without
+ # it such a user gets a working backend and no way to update from the tray.
+ ["unsloth", "studio", "update"],
+ ["unsloth", "studio", "--help"],
+ ],
+)
+def test_cli_guard_relocates_a_desktop_managed_command(argv: list[str]):
+ message, colour, chdir_calls = _guard_outcome(r"C:\Windows\System32", argv = argv)
+ assert colour == "yellow", f"{argv} must continue, not exit"
+ assert chdir_calls == [_RELOCATED]
+ assert message is not None and _RELOCATED in message
+
+
+def test_cli_guard_lands_where_the_desktop_puts_its_children():
+ """studio/src-tauri/src/process.rs pins ~/.unsloth; both halves must agree, or the
+ cwd-relative ./models scan finds different folders depending on which half ran."""
+ _, _, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32", argv = ["unsloth", "studio", "--api-only"]
+ )
+ assert chdir_calls == [_RELOCATED]
+
+
+def test_cli_guard_relocates_when_the_desktop_marks_the_child():
+ """Newer desktop builds set the marker; the argv rules above cover older ones.
+
+ The marker exists for a command shape this CLI does not know yet, so it is
+ tried here with one.
+ """
+ message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "desktop-handshake", "--json"],
+ environ_extra = {"UNSLOTH_DESKTOP_MANAGED": "1"},
+ )
+ assert colour == "yellow"
+ assert chdir_calls == [_RELOCATED]
+ assert message is not None
+
+
+ "rest",
+ [
+ ["run", "some-model"],
+ ["run", "--model", r".\local.gguf", "--api-only"],
+ ["update", "--local", r".\checkout"],
+ ],
+)
+def test_cli_guard_marker_does_not_authorise_a_command_carrying_a_path(rest: list[str]):
+ """The backend and everything below it inherit the marker, so it must not
+ widen the set to commands that resolve a path the caller gave them."""
+ _, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", *rest],
+ environ_extra = {"UNSLOTH_DESKTOP_MANAGED": "1"},
+ )
+ assert (colour, chdir_calls) == ("red", [])
+
+
+ "argv",
+ [
+ ["unsloth", "train", "--dataset", "data.json"],
+ ["unsloth", "export", "--output", "out"],
+ ["unsloth", "studio", "setup"],
+ ["unsloth", "start", "claude"],
+ # `studio run` declares its own --api-only and takes user paths, so it
+ # must not be mistaken for the desktop's backend launch.
+ ["unsloth", "studio", "run", "--model", "./local.gguf", "--api-only"],
+ ["unsloth", "studio", "run", "--api-only"],
+ # The top-level alias for `studio run`, same reasoning.
+ ["unsloth", "run", "--api-only"],
+ ],
+)
+def test_cli_guard_still_refuses_commands_that_take_relative_paths(argv: list[str]):
+ """Relocating these would silently resolve the user's own relative paths elsewhere."""
+ message, colour, chdir_calls = _guard_outcome(r"C:\Windows\System32", argv = argv)
+ assert colour == "red"
+ assert chdir_calls == [], "a user command must never be moved out from under its paths"
+ assert message is not None
+
+
+def test_cli_guard_marker_must_be_exactly_one():
+ _, colour, _ = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "train"],
+ environ_extra = {"UNSLOTH_DESKTOP_MANAGED": "yes"},
+ )
+ assert colour == "red", "only the value the desktop sets authorises a move"
+
+
+def test_cli_guard_fails_closed_when_the_chdir_fails():
+ message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "--api-only"],
+ chdir_error = PermissionError("denied"),
+ )
+ assert colour == "red", "a failed move must not continue in the system folder"
+ assert chdir_calls == [_RELOCATED]
+ assert message is not None
+
+
+def test_cli_guard_fails_closed_when_the_work_dir_cannot_be_created():
+ """Studio has to write under the home anyway, and the Rust half stops here too."""
+ _, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "--api-only"],
+ makedirs_error = PermissionError("denied"),
+ )
+ assert colour == "red"
+ assert chdir_calls == []
+
+
+def test_cli_guard_never_relocates_into_the_public_profile():
+ """A SYSTEM or service profile must not send one account's caches, scans and
+ outputs into a folder every other account on the machine can write."""
+ _, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "--api-only"],
+ userprofile = r"C:\Windows\System32\config\systemprofile",
+ public = r"C:\Users\Public",
+ )
+ assert colour == "red"
+ assert chdir_calls == []
+
+
+def test_cli_guard_still_suggests_the_public_profile_to_a_person():
+ """It is a fine folder to type by hand, just not one to be moved into silently."""
+ message, colour, _ = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "train"],
+ userprofile = r"C:\Windows\System32\config\systemprofile",
+ public = r"C:\Users\Public",
+ )
+ assert colour == "red"
+ assert message is not None
+ assert _cd_line(message, "PowerShell") == "cd 'C:\\Users\\Public'"
+
+
[email protected]("home", [".", r"..\Users\me", r"C:Users\me"])
+def test_cli_guard_rejects_a_home_that_is_not_rooted(home: str):
+ """A relative home resolves against the folder being escaped."""
+ _, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "--api-only"],
+ userprofile = home,
+ )
+ assert colour == "red"
+ assert chdir_calls == []
+
+
+def test_cli_guard_sees_through_an_extended_length_path():
+ r"""\\?\C:\Windows\System32 is the same folder spelled the long way."""
+ _, colour, _ = _guard_outcome(r"\\?\C:\Windows\System32", argv = ["unsloth", "train"])
+ assert colour == "red"
+
+
+ "argv",
+ [
+ # A relative repo path here is resolved against the working directory.
+ ["unsloth", "studio", "update", "--local", "./repo"],
+ ["unsloth", "studio", "desktop-capabilities", "--out", "./x"],
+ ],
+)
+def test_cli_guard_only_relocates_the_exact_desktop_argv(argv: list[str]):
+ _, colour, chdir_calls = _guard_outcome(r"C:\Windows\System32", argv = argv)
+ assert colour == "red"
+ assert chdir_calls == []
+
+
+def test_cli_guard_marker_does_not_cover_path_taking_commands():
+ """The marker is inherited by everything the backend spawns, so it authorises
+ the studio commands the desktop runs and nothing else."""
+ _, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "train", "--dataset", ".\\data.json"],
+ environ_extra = {"UNSLOTH_DESKTOP_MANAGED": "1"},
+ )
+ assert colour == "red"
+ assert chdir_calls == []
+
+
+def test_cli_guard_fails_closed_when_every_home_is_a_system_directory():
+ message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "--api-only"],
+ userprofile = r"C:\Windows\System32\config\systemprofile",
+ public = r"C:\Windows\Temp",
+ )
+ assert colour == "red"
+ assert chdir_calls == []
+ assert message is not None
+ # This one is read in the desktop's logs, not a terminal, so it must not tell
+ # the reader to cd somewhere or claim they used "Run as administrator".
+ assert "Run as administrator" not in message
+
+
+def test_cli_guard_reports_a_deleted_working_directory_for_what_it_is():
+ """getcwd() itself raises if the launch directory was removed; that used to be an
+ uncaught traceback, and it must not be described as a Windows system folder."""
+ message, colour, chdir_calls = _guard_outcome(
+ None,
+ argv = ["unsloth", "studio", "--api-only"],
+ getcwd_error = FileNotFoundError("gone"),
+ )
+ assert colour == "red"
+ assert chdir_calls == []
+ assert message is not None
+ assert "cannot determine its current folder" in message
+ assert r"C:\Windows" not in message, "the user was never in a Windows folder"
+
+
+def test_cli_guard_finds_the_real_windows_folder_past_a_shadowed_windir():
+ """WINDIR can be shadowed from HKCU\\Environment; SystemRoot cannot."""
+ _, colour, _ = _guard_outcome(
+ r"D:\Windows\System32",
+ argv = ["unsloth", "train"],
+ environ_extra = {"SystemRoot": r"D:\Windows", "WINDIR": r"C:\Users\me"},
+ windows_dirs = (r"D:\Windows",),
+ )
+ assert colour == "red", "the real Windows folder must still be caught"
+
+
+def test_cli_guard_ignores_a_windir_that_holds_no_system32():
+ """A WINDIR pointed at the user's own profile must not turn their project
+ folders into system folders, which would block every command they run."""
+ message, colour, _ = _guard_outcome(
+ r"C:\Users\me\projects\llm",
+ argv = ["unsloth", "train"],
+ environ_extra = {"SystemRoot": r"C:\Windows", "WINDIR": r"C:\Users\me"},
+ windows_dirs = (r"C:\Windows",),
+ )
+ assert (message, colour) == (None, None)
+
+
+def test_cli_guard_keeps_working_when_nothing_looks_like_windows():
+ """No candidate holds System32 (an unusual image, or a test): fall back to
+ SystemRoot rather than trusting the settable value."""
+ _, colour, _ = _guard_outcome(
+ r"E:\Windows\System32",
+ argv = ["unsloth", "train"],
+ environ_extra = {"SystemRoot": r"E:\Windows", "WINDIR": r"C:\Users\me"},
+ windows_dirs = (),
+ )
+ assert colour == "red"
+
+
+def test_cli_guard_pins_a_relative_studio_home_before_moving():
+ """Studio resolves the override with Path.resolve(), which anchors a relative
+ value to the working directory, so moving first would retarget it."""
+ environ_out: dict[str, str] = {}
+ _, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "update"],
+ environ_extra = {"UNSLOTH_STUDIO_HOME": r".\custom"},
+ environ_out = environ_out,
+ )
+ assert colour == "yellow"
+ assert chdir_calls == [_RELOCATED]
+ assert (
+ environ_out["UNSLOTH_STUDIO_HOME"] == r"C:\Windows\System32\.\custom"
+ ), "the override must keep naming the folder the caller meant"
+
+
[email protected]("name", _system_dir_guard._RELATIVE_PATH_ENV)
+def test_cli_guard_pins_every_relative_path_override(name: str):
+ environ_out: dict[str, str] = {}
+ _, colour, _ = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "--api-only"],
+ environ_extra = {name: "cache"},
+ environ_out = environ_out,
+ )
+ assert colour == "yellow"
+ assert environ_out[name] == r"C:\Windows\System32\cache"
+
+
+def test_cli_guard_does_not_recreate_a_profile_that_is_not_mounted():
+ """A roaming profile that has not arrived yet has a writable parent, so
+ makedirs would build an empty second one that shadows the real profile."""
+ _, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "--api-only"],
+ missing_homes = (r"C:\Users\me",),
+ )
+ assert (colour, chdir_calls) == ("red", [])
+
+
+def test_cli_guard_never_relocates_into_the_public_profile_from_userprofile():
+ """The public profile is readable and writable by every account on the
+ machine, so it is no place for one account's caches, scans and outputs."""
+ public = r"C:\Users\Public"
+ _, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "--api-only"],
+ userprofile = public,
+ environ_extra = {"PUBLIC": public},
+ )
+ assert (colour, chdir_calls) == ("red", [])
+
+
[email protected]("public", [r"C:\Users\Public", r"c:\users\public\\"])
+def test_safe_user_dir_rejects_the_public_profile_from_either_candidate(public: str):
+ """It is the folder that is shared, not the variable that named it, so `~`
+ resolving there is refused exactly as USERPROFILE is."""
+ environ = {"USERPROFILE": r"C:\Windows\System32\config\systemprofile", "PUBLIC": public}
+ chosen = _system_dir_guard.safe_user_dir(
+ environ,
+ [r"C:\Windows"],
+ pathmod = ntpath,
+ sep = "\\",
+ expanduser = lambda _p: r"C:\Users\Public",
+ )
+ assert chosen is None
+ # A human can still be told about it, which is what allow_public is for.
+ assert (
+ _system_dir_guard.safe_user_dir(
+ environ,
+ [r"C:\Windows"],
+ pathmod = ntpath,
+ sep = "\\",
+ expanduser = lambda _p: r"C:\Users\Public",
+ allow_public = True,
+ )
+ == public
+ )
+
+
+def test_cli_guard_pins_the_local_checkout_update_reads():
+ """`studio update` relocates, and commands/studio.py resolves a relative
+ STUDIO_LOCAL_REPO against the working directory, so it has to be pinned."""
+ environ_out: dict[str, str] = {}
+ _, colour, _ = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "update"],
+ environ_extra = {"STUDIO_LOCAL_REPO": r"..\src\unsloth"},
+ environ_out = environ_out,
+ )
+ assert colour == "yellow"
+ assert environ_out["STUDIO_LOCAL_REPO"] == r"C:\Windows\System32\..\src\unsloth"
+
+
+ ("value", "qualified"),
+ [
+ (r"C:\cache", True),
+ ("C:/cache", True),
+ (r"\\server\share\cache", True),
+ (r"\\?\C:\cache", True),
+ (r"\\?\unc\server\share", True),
+ # Rooted, but only to the drive of the current directory.
+ (r"\cache", False),
+ ("/cache", False),
+ # Relative to the current directory on drive D.
+ ("D:cache", False),
+ ("cache", False),
+ (r".\cache", False),
+ ],
+)
+def test_only_a_value_naming_one_folder_counts_as_fully_qualified(value: str, qualified: bool):
+ """isabs() answered True for a leading separator until Python 3.13 and False
+ after it, so the folder a value names must not be decided by it."""
+ assert _system_dir_guard._is_fully_qualified(value, ntpath) is qualified
+
+
+def test_cli_guard_resolves_a_root_relative_override_through_the_os():
+ r"""A single leading separator takes the drive of the current directory, so
+ moving to a profile on another drive would move the folder with it."""
+ environ_out: dict[str, str] = {}
+ _, colour, _ = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "--api-only"],
+ environ_extra = {"HF_HOME": r"\hf-cache"},
+ environ_out = environ_out,
+ drive_cwd = {"": "C:\\"},
+ )
+ assert colour == "yellow"
+ assert environ_out["HF_HOME"] == r"C:\hf-cache"
+
+
+def test_cli_guard_anchors_each_entry_of_a_path_list():
+ """One relative entry decides what the whole allowlist authorises."""
+ environ_out: dict[str, str] = {}
+ _, colour, _ = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "--api-only"],
+ environ_extra = {"UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH": r"trusted;D:\shared"},
+ environ_out = environ_out,
+ )
+ assert colour == "yellow"
+ assert environ_out["UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH"] == (
+ r"C:\Windows\System32\trusted;D:\shared"
+ )
+
+
+ "profile",
+ [r"\\?\UNC\server\profiles\me", r"\\?\unc\server\profiles\me"],
+)
+def test_cli_guard_accepts_an_extended_unc_profile_in_either_case(profile: str):
+ r"""The object manager is case-insensitive, so reading \\?\unc\ as a relative
+ name would reject a profile Windows itself resolves."""
+ chosen = _system_dir_guard.safe_user_dir(
+ {"USERPROFILE": profile},
+ [r"C:\Windows"],
+ pathmod = ntpath,
+ sep = "\\",
+ expanduser = lambda _p: profile,
+ )
+ assert chosen == profile
+
+
+def test_cli_guard_resolves_a_drive_relative_override_through_the_os():
+ """ "D:cache" means the current directory on drive D, which join() cannot know
+ and which the move changes, so Windows itself has to resolve it first."""
+ environ_out: dict[str, str] = {}
+ _, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "--api-only"],
+ environ_extra = {"HF_HOME": "D:cache"},
+ environ_out = environ_out,
+ drive_cwd = {"D:": r"D:\work"},
+ )
+ assert (colour, chdir_calls) == ("yellow", [_RELOCATED])
+ assert environ_out["HF_HOME"] == r"D:\work\cache"
+
+
+def test_cli_guard_refuses_to_move_when_a_drive_relative_override_cannot_be_resolved():
+ """Moving anyway would silently retarget it, which is what the pinning exists
+ to prevent, so the guard fails closed instead."""
+ _, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "--api-only"],
+ environ_extra = {"HF_HOME": "D:cache"},
+ drive_cwd = {},
+ )
+ assert (colour, chdir_calls) == ("red", [])
+
+
+def test_cli_guard_pins_every_storage_root_override_studio_reads():
+ """storage_roots.py owns the Studio folders, and each of its overrides is a
+ plain user-supplied path, so a relative one must be pinned before the move.
+ Reading them from the module keeps the guard honest as roots are added."""
+ storage_roots = REPO_ROOT / "studio" / "backend" / "utils" / "paths" / "storage_roots.py"
+ source = storage_roots.read_text(encoding = "utf-8")
+ overrides = set(re.findall(r'environ\.get\(\s*"(UNSLOTH_[A-Z_]*(?:HOME|PATH|DIR))"', source))
+ assert overrides, "no storage root overrides found: has storage_roots.py moved?"
+ missing = sorted(overrides - set(_system_dir_guard._RELATIVE_PATH_ENV))
+ assert not missing, f"relative values of {missing} would be retargeted by the move"
+
+
[email protected]("value", [r"C:\elsewhere\custom", r"\\server\share\c"])
+def test_cli_guard_leaves_an_already_anchored_override_alone(value: str):
+ """An absolute or UNC value does not depend on the working directory."""
+ environ_out: dict[str, str] = {}
+ _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "studio", "--api-only"],
+ environ_extra = {"UNSLOTH_STUDIO_HOME": value},
+ environ_out = environ_out,
+ )
+ assert environ_out["UNSLOTH_STUDIO_HOME"] == value
+
+
+def test_cli_guard_does_not_touch_overrides_when_it_refuses():
+ """No move, nothing to pin: the command runs where the caller left it."""
+ environ_out: dict[str, str] = {}
+ _, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ argv = ["unsloth", "train"],
+ environ_extra = {"UNSLOTH_STUDIO_HOME": r".\custom"},
+ environ_out = environ_out,
+ )
+ assert (colour, chdir_calls) == ("red", [])
+ assert environ_out["UNSLOTH_STUDIO_HOME"] == r".\custom"
+
+
+def test_cli_guard_does_nothing_off_windows():
+ outcome = _system_dir_guard.check_working_directory(
+ ["studio", "--api-only"],
+ {"WINDIR": r"C:\Windows"},
+ "linux",
+ getcwd = lambda: r"C:\Windows\System32",
+ chdir = lambda _target: pytest.fail("must not move on non-Windows platforms"),
+ )
+ assert outcome == (None, None, False)
+
+
+def test_cli_guard_runs_before_the_command_modules_are_imported():
+ """unsloth_cli.commands.studio resolves STUDIO_HOME at import time, so a chdir in
+ the callback would come too late for a relative UNSLOTH_STUDIO_HOME."""
+ source = CLI_INIT.read_text(encoding = "utf-8")
+ guard_call = source.index("_check_working_directory(_sys.argv[1:]")
+ first_command_import = source.index("from unsloth_cli.commands.")
+ assert guard_call < first_command_import
+ assert source.index("import typer") > guard_call
+
+
+def test_cli_callback_exits_only_on_a_fatal_outcome():
+ """The callback must key the exit on the guard's own fatal flag, not on the colour."""
+ source = CLI_INIT.read_text(encoding = "utf-8")
+ assert "_message, _colour, _fatal = _guard" in source
+ assert "if _fatal:\n raise typer.Exit(code = 1)" in source
+
+
+def test_cli_guard_leaves_values_the_working_directory_does_not_resolve():
+ r"""Two readers in the tree take these as something other than a path, so
+ anchoring one would change its meaning instead of preserving it: MLX_HOSTFILE
+ holds either a filename or the host list itself, and a bare on/off token is
+ ignored by the pre-quant allowlist precisely so there is no "allow all" mode."""
+ environ_out: dict[str, str] = {}
+ values = {
+ "MLX_HOSTFILE": '[{"ssh": "node0"}]',
+ "UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH": "1",
+ }
+ _message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ environ_extra = dict(values),
+ environ_out = environ_out,
+ )
+ assert (colour, chdir_calls) == ("yellow", [_RELOCATED])
+ for name, value in values.items():
+ assert environ_out[name] == value, f"{name} was rewritten to {environ_out[name]}"
+
+
+def test_cli_guard_expands_a_cache_override_before_deciding():
+ r"""huggingface_hub expands %LOCALAPPDATA% in HF_HOME and Studio's own
+ hf_cache_settings does not, so leaving the value as written sends the two
+ readers to different folders once the process moves. Expanding here settles
+ it; a variable this machine does not set stays literal and is anchored."""
+ environ_out: dict[str, str] = {}
+ _message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ environ_extra = {
+ "LOCALAPPDATA": r"C:\Users\me\AppData\Local",
+ "HF_HOME": r"%LOCALAPPDATA%\hf",
+ "HF_HUB_CACHE": r"%NOT_SET%\hub",
+ },
+ environ_out = environ_out,
+ )
+ assert (colour, chdir_calls) == ("yellow", [_RELOCATED])
+ assert environ_out["HF_HOME"] == r"C:\Users\me\AppData\Local\hf"
+ assert environ_out["HF_HUB_CACHE"] == r"C:\Windows\System32\%NOT_SET%\hub"
+
+
+def test_cli_guard_refuses_a_path_attached_to_its_own_option():
+ r"""`--frontend=.\dist` carries a path inside the option token, so a marked
+ grandchild running it must be refused rather than moved: relocating would
+ silently rebase that path under the profile."""
+ _message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", r"--frontend=.\dist"],
+ environ_extra = {_system_dir_guard.DESKTOP_MANAGED_ENV: "1"},
+ )
+ assert (colour, chdir_calls) == ("red", [])
+
+
+def test_cli_guard_refuses_a_root_relative_system_profile():
+ r"""SYSTEM's profile spelled without a drive still names SYSTEM's profile, and
+ it compares equal to no drive-qualified Windows root, so a rooted-only test
+ would send the caller back into the folder it is leaving."""
+ _message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ userprofile = r"\Windows\System32\config\systemprofile",
+ )
+ assert (colour, chdir_calls) == ("red", [])
+
+
+def test_cli_guard_anchors_relative_import_roots_before_it_moves():
+ r"""PYTHONPATH entries reach sys.path as written and are resolved on every
+ import, so a move would let whatever sits in ~/.unsloth shadow them."""
+ environ_out: dict[str, str] = {}
+ syspath = [
+ r"C:\Python\Lib",
+ "lib",
+ "",
+ r".\plugins",
+ # setuptools registers this for an editable namespace install and its own
+ # path hook accepts it by exact string; it names no directory.
+ "__editable__.unsloth-2026.8.15.finder.__path_hook__",
+ # A relative archive: importable, so it moves with the process.
+ "modules.zip",
+ ]
+ _message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ environ_extra = {"PYTHONPATH": r"lib;C:\shared\lib"},
+ environ_out = environ_out,
+ syspath = syspath,
+ real_paths = ("lib", r".\plugins", "modules.zip"),
+ )
+ assert (colour, chdir_calls) == ("yellow", [_RELOCATED])
+ assert environ_out["PYTHONPATH"] == r"C:\Windows\System32\lib;C:\shared\lib"
+ assert syspath == [
+ r"C:\Python\Lib",
+ r"C:\Windows\System32\lib",
+ # An empty entry means the working directory, which is about to change.
+ r"C:\Windows\System32",
+ # join, not normpath: the same spelling the environment pinning uses.
+ r"C:\Windows\System32\.\plugins",
+ # Names nothing on disk: setuptools' editable sentinel, which its own
+ # path hook accepts back by exact string.
+ "__editable__.unsloth-2026.8.15.finder.__path_hook__",
+ # An archive that is really there is anchored like any other root.
+ r"C:\Windows\System32\modules.zip",
+ ]
+
+
+def test_cli_guard_writes_back_only_an_expansion_the_reader_agrees_with():
+ r"""Every reader expands once, so the guard expands once and writes the result
+ back only when expanding it again would change nothing. When one pass still
+ names one folder the value is left alone; when it does not, the folder depends
+ on where the process is standing, so the move is refused rather than taken
+ with the value silently following it."""
+ environ_out: dict[str, str] = {}
+ _message, colour, _chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ environ_extra = {
+ "LOCALAPPDATA": r"C:\Users\me\AppData\Local",
+ "HF_HUB_CACHE": r"%LOCALAPPDATA%\hub",
+ # One pass leaves another reference, but it already names a drive,
+ # so it means the same folder from anywhere.
+ "HF_ASSETS_CACHE": r"C:\cache\%UNSET%\assets",
+ },
+ environ_out = environ_out,
+ )
+ assert colour == "yellow"
+ # One pass settles it, so it names one folder and is written back.
+ assert environ_out["HF_HUB_CACHE"] == r"C:\Users\me\AppData\Local\hub"
+ assert environ_out["HF_ASSETS_CACHE"] == r"C:\cache\%UNSET%\assets"
+
+
+def test_cli_guard_refuses_to_move_under_an_expansion_that_stays_relative():
+ r"""A nested reference, an escaped %%NAME%% and a self-reference all leave one
+ pass holding another reference, and the reader resolves what it gets against
+ the working directory. Moving would take the value with it, so each of these
+ refuses instead, naming the setting that could not be preserved."""
+ for name, value, extra in (
+ ("HF_ASSETS_CACHE", r"%NESTED%\assets", {"NESTED": r"%USERPROFILE%\AppData\Local"}),
+ ("XDG_CACHE_HOME", r"%%USERPROFILE%%\xdg", {}),
+ ("HF_HOME", r"%HF_HOME%\cache", {}),
+ ):
+ environ_out: dict[str, str] = {}
+ message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ environ_extra = {name: value, **extra},
+ environ_out = environ_out,
+ )
+ assert (colour, chdir_calls) == ("red", []), name
+ assert "path settings" in message, name
+ assert name in message, name
+ # Nothing is left rewritten by the attempt.
+ assert environ_out[name] == value
+
+
+def test_cli_guard_refuses_a_value_that_would_not_fit_in_the_environment():
+ r"""A scalar that was already near the 32767-character limit crosses it once
+ it names its folder in full, and a variable Windows will not accept is a
+ failure to report here rather than in the next process."""
+ message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ environ_extra = {"HF_HOME": "x" * 32767},
+ )
+ assert (colour, chdir_calls) == ("red", [])
+ assert "path settings" in message
+ assert "HF_HOME" in message
+
+
+def test_cli_guard_refuses_a_list_that_would_not_fit_in_the_environment():
+ r"""Windows caps a variable at 32767 characters, and a list of relative
+ entries can cross that once each names its folder in full. Reporting it here
+ names the setting; discovering it when the next process starts does not."""
+ entries = ";".join(["entry"] * 7000)
+ message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ environ_extra = {"PYTHONPATH": entries},
+ )
+ assert (colour, chdir_calls) == ("red", [])
+ assert "path settings" in message
+ assert "PYTHONPATH" in message
+
+
+def test_cli_guard_never_refuses_an_update_over_the_local_checkout_setting():
+ r"""A stale STUDIO_LOCAL_REPO on a drive that is gone must not stop the one
+ update form that relocates: the bare update drops the value before anything
+ reads it, so refusing over it would defeat the fallback this guard exists
+ for. Every other setting still refuses, because something does read those."""
+ environ_out: dict[str, str] = {}
+ _message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "update"],
+ # Z: has no current directory, so this one cannot be resolved at all.
+ environ_extra = {"STUDIO_LOCAL_REPO": "Z:checkout"},
+ environ_out = environ_out,
+ )
+ assert (colour, chdir_calls) == ("yellow", [_RELOCATED])
+ # Left exactly as written, and the update proceeds.
+ assert environ_out["STUDIO_LOCAL_REPO"] == "Z:checkout"
+
+ # The same value under a name something reads still stops the move.
+ message, colour, _chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "update"],
+ environ_extra = {"HF_HOME": "Z:cache"},
+ )
+ assert colour == "red"
+ assert "path settings" in message
+
+
+def test_cli_guard_refuses_a_path_attached_to_a_short_option():
+ r"""Click reads `-f.\dist` as a value the same way it reads
+ `--frontend=.\dist`, so a marked invocation carrying one is refused rather
+ than rebased under the new folder."""
+ for argv in (
+ ["unsloth", "studio", "-f.\\dist"],
+ ["unsloth", "studio", "--frontend=.\\dist"],
+ ["unsloth", "studio", "-f", ".\\dist"],
+ ):
+ message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ argv,
+ environ_extra = {"UNSLOTH_DESKTOP_MANAGED": "1"},
+ )
+ assert (colour, chdir_calls) == ("red", []), argv
+ assert "cannot run from" in message
+ # The bare marked form the desktop actually runs still relocates.
+ _message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "desktop-handshake"],
+ environ_extra = {"UNSLOTH_DESKTOP_MANAGED": "1"},
+ )
+ assert (colour, chdir_calls) == ("yellow", [_RELOCATED])
+
+
+def test_cli_guard_goes_back_when_the_move_lands_somewhere_still_refused():
+ r"""chdir can succeed into a folder the guard still refuses, through a
+ junction or a profile that is itself inside the Windows tree. The process
+ has to end up where it started, or the values written for the move would
+ name folders under a directory nobody chose."""
+ environ_out: dict[str, str] = {}
+ message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ environ_extra = {"HF_HOME": "cache"},
+ environ_out = environ_out,
+ # A junction under the profile: the move succeeds and the process is
+ # still inside the folder the guard refuses.
+ chdir_lands_in = r"C:\Windows\System32\config\systemprofile",
+ )
+ assert colour == "red"
+ assert "cannot run from" in message
+ # Back where it started, and the override is exactly as the caller wrote it.
+ assert chdir_calls[-1] == r"C:\Windows\System32"
+ assert environ_out["HF_HOME"] == "cache"
+
+
+def test_cli_guard_restores_the_real_sys_path_when_the_move_fails():
+ """The console script passes no list, so the guard has to snapshot the real
+ sys.path before pinning it, or a chdir that then fails leaves the process
+ carrying import roots it never agreed to."""
+ import sys
+
+ before = list(sys.path)
+ sys.path.insert(0, "lib")
+ try:
+ _message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ chdir_error = PermissionError("denied"),
+ real_paths = ("lib",),
+ pass_syspath = False,
+ )
+ assert colour == "red"
+ assert chdir_calls == [_RELOCATED]
+ assert sys.path[0] == "lib"
+ finally:
+ sys.path[:] = before
+
+
+def test_cli_guard_pins_the_model_paths_llama_server_reads_for_itself():
+ r"""llama-server resolves LLAMA_ARG_MODEL, LLAMA_ARG_MMPROJ and the draft
+ spellings against its own working directory, and Studio reads them back when
+ it sizes a launch, so a relative one has to move with the process. The URL
+ spelling names no local file and is left alone."""
+ environ_out: dict[str, str] = {}
+ _message, colour, _chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ environ_extra = {
+ "LLAMA_ARG_MODEL": r"models\qwen.gguf",
+ "LLAMA_ARG_MMPROJ": r".\mmproj.gguf",
+ "LLAMA_ARG_MODEL_DRAFT": "draft.gguf",
+ "LLAMA_ARG_SPEC_DRAFT_MODEL": r"D:\drafts\small.gguf",
+ "LLAMA_ARG_MMPROJ_URL": "https://example.invalid/proj.gguf",
+ },
+ environ_out = environ_out,
+ )
+ assert colour == "yellow"
+ assert environ_out["LLAMA_ARG_MODEL"] == r"C:\Windows\System32\models\qwen.gguf"
+ assert environ_out["LLAMA_ARG_MMPROJ"] == r"C:\Windows\System32\.\mmproj.gguf"
+ assert environ_out["LLAMA_ARG_MODEL_DRAFT"] == r"C:\Windows\System32\draft.gguf"
+ assert environ_out["LLAMA_ARG_SPEC_DRAFT_MODEL"] == r"D:\drafts\small.gguf"
+ assert environ_out["LLAMA_ARG_MMPROJ_URL"] == "https://example.invalid/proj.gguf"
+
+
+def test_cli_guard_leaves_a_bracketed_directory_alone_only_where_it_is_json():
+ r"""A folder really called "[llama]" is legal, so the inline-JSON exemption is
+ scoped to the one variable whose reader accepts JSON."""
+ environ_out: dict[str, str] = {}
+ _message, colour, _chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ environ_extra = {
+ "UNSLOTH_LLAMA_CPP_PATH": "[llama]",
+ "MLX_HOSTFILE": "[llama]",
+ "UNSLOTH_STUDIO_HOME": "%data%",
+ },
+ environ_out = environ_out,
+ )
+ assert colour == "yellow"
+ assert environ_out["UNSLOTH_LLAMA_CPP_PATH"] == r"C:\Windows\System32\[llama]"
+ assert environ_out["UNSLOTH_STUDIO_HOME"] == r"C:\Windows\System32\%data%"
+ assert environ_out["MLX_HOSTFILE"] == "[llama]"
+
+
[email protected](importlib.util.find_spec("typer") is None, reason = "typer is not installed")
+def test_cli_guard_reads_the_invocation_not_the_hosts_argv():
+ """A host that imports the app and calls it never touches sys.argv, so the
+ callback has to classify the arguments Click was given: `studio --api-only`
+ from a host whose own argv says `train --dataset .\\d.json`, and the reverse."""
+ from typer.testing import CliRunner
+
+ import unsloth_cli
+
+ seen: list[list[str]] = []
+ original = unsloth_cli._check_working_directory
+ unsloth_cli._check_working_directory = lambda argv, environ, platform, **kw: (
+ seen.append(list(argv)) or (None, None, False)
+ )
+ try:
+ CliRunner().invoke(unsloth_cli.app, ["studio", "--help"])
+ CliRunner().invoke(unsloth_cli.app, ["train", "--help"])
+ finally:
+ unsloth_cli._check_working_directory = original
+ assert seen == [["studio", "--help"], ["train", "--help"]]
+
+
+def test_cli_guard_pins_the_token_path_and_the_special_pythonpath_entries():
+ r"""HF_TOKEN_PATH is where huggingface_hub reads the credential file, and
+ PYTHONPATH has two spellings that follow the process: an empty component means
+ the working directory, and `~` is never expanded there."""
+ environ_out: dict[str, str] = {}
+ _message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ environ_extra = {
+ "HF_TOKEN_PATH": r"secrets\token",
+ "PYTHONPATH": r";~\plugins;C:\shared\lib",
+ },
+ environ_out = environ_out,
+ )
+ assert (colour, chdir_calls) == ("yellow", [_RELOCATED])
+ assert environ_out["HF_TOKEN_PATH"] == r"C:\Windows\System32\secrets\token"
+ assert environ_out["PYTHONPATH"] == (
+ # The empty component is the folder being left; `~` is anchored as the
+ # literal relative folder Python reads there, not as the profile.
+ r"C:\Windows\System32;C:\Windows\System32\~\plugins;C:\shared\lib"
+ )
+
+
+def test_cli_guard_says_which_setting_stopped_the_move():
+ r"""A value that cannot be pinned is a different failure from a missing
+ profile: an oversized PYTHONPATH (Windows caps a variable at 32767 chars) or
+ a drive with no current directory of its own. Blaming the user folder for it
+ sends the reader looking in the wrong place."""
+ _message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ # No current directory for drive D, so the OS cannot resolve this.
+ environ_extra = {"HF_HOME": "D:cache"},
+ drive_cwd = {},
+ )
+ assert (colour, chdir_calls) == ("red", [])
+ assert _message is not None
+ assert "path settings" in _message
+ assert "user profile" not in _message
+
+
+def test_cli_guard_expands_a_hyphenated_name_the_way_ntpath_does():
+ r"""ntpath counts the hyphen as part of a $ name, so $CACHE-ROOT is one
+ variable and not $CACHE followed by -ROOT. The desktop twin has to agree, or
+ the two layers send the same install to two different folders."""
+ environ_out: dict[str, str] = {}
+ _message, colour, _chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ environ_extra = {
+ "CACHE": r"C:\wrong",
+ "CACHE-ROOT": r"C:\right",
+ "HF_HOME": r"$CACHE-ROOT\hf",
+ },
+ environ_out = environ_out,
+ )
+ assert colour == "yellow"
+ assert environ_out["HF_HOME"] == r"C:\right\hf"
+
+
+def test_cli_guard_puts_back_what_it_pinned_when_the_move_fails():
+ r"""Inside a host process the environment and sys.path are the caller's, so a
+ chdir that fails must not leave them rewritten as though it had moved."""
+ environ_out: dict[str, str] = {}
+ syspath = ["lib", r"C:\Python\Lib"]
+ _message, colour, chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ environ_extra = {"HF_HOME": "cache", "PYTHONPATH": "lib"},
+ environ_out = environ_out,
+ syspath = syspath,
+ real_paths = ("lib",),
+ chdir_error = PermissionError("access denied"),
+ )
+ assert (colour, chdir_calls) == ("red", [_RELOCATED])
+ assert environ_out["HF_HOME"] == "cache"
+ assert environ_out["PYTHONPATH"] == "lib"
+ assert syspath == ["lib", r"C:\Python\Lib"]
+
+
+def test_cli_guard_will_not_relocate_once_the_commands_are_imported():
+ r"""A host that imports the app has already resolved STUDIO_HOME, so a move
+ from the callback would leave that cached root in the folder being left."""
+ outcome = _system_dir_guard.check_working_directory(
+ ["studio", "--api-only"],
+ {"WINDIR": r"C:\Windows", "USERPROFILE": r"C:\Users\me"},
+ "win32",
+ getcwd = lambda: r"C:\Windows\System32",
+ chdir = lambda _target: pytest.fail("a library call must not move the host"),
+ pathmod = ntpath,
+ sep = "\\",
+ expanduser = lambda _p: r"C:\Users\me",
+ isdir = lambda path: ntpath.normcase(path) == ntpath.normcase(r"C:\Windows\System32"),
+ relocate = False,
+ )
+ message, colour, fatal = outcome
+ assert (colour, fatal) == ("red", True)
+ assert message is not None
+
+
+def test_cli_guard_treats_the_jaccl_device_file_like_the_host_file():
+ r"""MLX_IBV_DEVICES is read exactly like MLX_HOSTFILE (`_json_rank_count_from_env`):
+ either inline JSON or a filename, so it is pinned and the JSON left alone."""
+ environ_out: dict[str, str] = {}
+ _message, colour, _chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ environ_extra = {"MLX_IBV_DEVICES": "devices.json"},
+ environ_out = environ_out,
+ )
+ assert colour == "yellow"
+ assert environ_out["MLX_IBV_DEVICES"] == r"C:\Windows\System32\devices.json"
+
+ environ_out.clear()
+ _message, colour, _chdir_calls = _guard_outcome(
+ r"C:\Windows\System32",
+ ["unsloth", "studio", "--api-only"],
+ environ_extra = {"MLX_IBV_DEVICES": '[{"device": "mlx5_0"}]'},
+ environ_out = environ_out,
+ )
+ assert environ_out["MLX_IBV_DEVICES"] == '[{"device": "mlx5_0"}]'
diff --git a/unsloth_cli/__init__.py b/unsloth_cli/__init__.py
index 5dacb5b26ad..37d854e3385 100644
--- a/unsloth_cli/__init__.py
+++ b/unsloth_cli/__init__.py
@@ -26,6 +26,20 @@ if _is_entry_point:
pass
del _name, _stream, _to_utf8
+from unsloth_cli._system_dir_guard import check_working_directory as _check_working_directory
+
+# Running from System32 or any subdir WILL cause errors if not prevented. A
+# command the folder cannot affect (the ones Unsloth Desktop spawns, issue #8510)
+# moves out of it; everything else stops in the callback below.
+#
+# Before the command imports, since unsloth_cli.commands.studio resolves
+# STUDIO_HOME at import time and a relative UNSLOTH_STUDIO_HOME would otherwise
+# be pinned to the folder we are leaving. The message waits for typer to render
+# it. A library import reaches the same check from the callback instead.
+_startup_guard = (
+ _check_working_directory(_sys.argv[1:], _os.environ, _sys.platform) if _is_entry_point else None
+)
+
import typer
from importlib.metadata import version as package_version, PackageNotFoundError
@@ -59,14 +73,60 @@ def show_version(value: bool):
raise typer.Exit()
+_ARGV_META_KEY = "unsloth.invocation_args"
+
+try:
+ from typer.core import TyperGroup as _TyperGroup
+except Exception: # pragma: no cover - a typer without the public group class
+ _TyperGroup = None
+
+if _TyperGroup is not None:
+
+ class _ArgvCapturingGroup(_TyperGroup):
+ """Remember the tokens this invocation was given.
+
+ Click hands the group its full argument list here and then keeps the tail
+ on the child context, out of the callback's reach. Both `app(args = [...])`
+ and CliRunner reach this, so a library call is classified by its own
+ arguments rather than by the host's argv.
+ """
+
+ def parse_args(self, ctx, args):
+ ctx.meta.setdefault(_ARGV_META_KEY, list(args))
+ return super().parse_args(ctx, args)
+
+else: # pragma: no cover
+ _ArgvCapturingGroup = None
+
+
app = typer.Typer(
help = "Command-line interface for Unsloth training, inference, and export.",
context_settings = {"help_option_names": ["-h", "--help"]},
+ **({"cls": _ArgvCapturingGroup} if _ArgvCapturingGroup is not None else {}),
)
+def _invocation_args(ctx):
+ """The arguments this invocation was given, not the host process's argv.
+
+ A library calling `app(args = [...])` or CliRunner never touches sys.argv, so
+ reading it there would classify somebody else's command line and could move
+ the process out from under the caller's relative paths. The `unsloth` console
+ script never reaches here: it is classified at import, from the real argv.
+ """
+ captured = ctx.meta.get(_ARGV_META_KEY)
+ if captured is not None:
+ return list(captured)
+ if not ctx.invoked_subcommand:
+ return _sys.argv[1:]
+ # No capture and no tail to read: assume it holds a path, so an invocation
+ # that cannot be read in full is refused rather than relocated.
+ return [ctx.invoked_subcommand, *(list(getattr(ctx, "args", None) or []) or ["..."])]
+
+
@app.callback()
def main(
+ ctx: typer.Context,
version: bool = typer.Option(
None,
"--version",
@@ -76,61 +136,24 @@ def main(
help = "Show version and exit.",
),
):
- if (
- _sys.platform == "win32"
- ): # this block catches unsloth running inside of System32 or any subdirs, this WILL cause errors if not prevented.
- _windir = _os.environ.get("WINDIR", r"C:\Windows")
- # SysWOW64 too: a 32-bit elevated shell opens there, same unwritable folder.
- _system_dirs = [
- _os.path.normcase(_os.path.normpath(_os.path.join(_windir, _name)))
- for _name in ("System32", "SysWOW64")
- ]
- _cwd_raw = _os.getcwd()
- _cwd = _os.path.normcase(_os.path.normpath(_cwd_raw))
- if any(_cwd == _dir or _cwd.startswith(_dir + _os.sep) for _dir in _system_dirs):
- # Users land here via "Run as administrator", so name the folder and hand back
- # a runnable fix. SYSTEM's USERPROFILE is under System32 and would send them
- # straight back, so take the first home outside the Windows tree, or none.
- _windir_norm = _os.path.normcase(_os.path.normpath(_windir))
- _home = None
- for _candidate in (
- _os.environ.get("USERPROFILE"),
- _os.environ.get("PUBLIC"),
- _os.path.expanduser("~"),
- ):
- _norm = _os.path.normcase(_os.path.normpath(_candidate)) if _candidate else ""
- if _norm and _norm != _windir_norm and not _norm.startswith(_windir_norm + _os.sep):
- _home = _candidate
- break
- if _home:
- # Quote it, or C:\Users\Jane Doe reaches Set-Location as two arguments.
- # PowerShell single quotes are verbatim ('' escapes an apostrophe); cmd
- # needs double quotes once extensions are off. " is not legal in a path.
- _home_ps = "'" + _home.replace("'", "''") + "'"
- _home_cmd = '"' + _home + '"'
- _cd_lines = (
- f" cd {_home_ps} (PowerShell)\n"
- f" cd /d {_home_cmd} (cmd.exe)\n"
- )
- else:
- _cd_lines = f" (any folder outside {_windir})\n"
- _argv = " ".join((f'"{_arg}"' if " " in _arg else _arg) for _arg in _sys.argv[1:])
- _retry = ("unsloth " + _argv).rstrip()
- typer.secho(
- f"Unsloth cannot run from {_cwd_raw}\n"
- "\n"
- "That is a Windows system folder. Unsloth writes caches, configs and model\n"
- "downloads into the current working directory, and Windows blocks that here.\n"
- "Opening a terminal with 'Run as administrator' starts you in a folder like\n"
- "this one, which is how most people end up here.\n"
- "\n"
- "Change to a normal folder and run the command again:\n"
- f"{_cd_lines}"
- f" {_retry}",
- fg = "red",
- err = True,
- )
- raise typer.Exit(code = 1)
+ # Consume the import-time result once: a host calling the app repeatedly can
+ # chdir between calls, so each later call is checked afresh.
+ global _startup_guard
+ _guard, _startup_guard = _startup_guard, None
+ if _guard is None:
+ # A host reaches this after commands.studio has resolved STUDIO_HOME at
+ # import time, so moving now would leave that cached root behind.
+ _guard = _check_working_directory(
+ _invocation_args(ctx),
+ _os.environ,
+ _sys.platform,
+ relocate = False,
+ )
+ _message, _colour, _fatal = _guard
+ if _message is not None:
+ typer.secho(_message, fg = _colour, err = True)
+ if _fatal:
+ raise typer.Exit(code = 1)
app.command()(train)
diff --git a/unsloth_cli/_system_dir_guard.py b/unsloth_cli/_system_dir_guard.py
new file mode 100644
index 00000000000..ebb63d5f11c
--- /dev/null
+++ b/unsloth_cli/_system_dir_guard.py
@@ -0,0 +1,848 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Windows system-folder guard for the `unsloth` console script.
+
+C:\\Windows\\System32 is unwritable for a normal user, and cwd-relative paths
+(`./models`, `unsloth_compiled_cache`) would resolve inside the Windows tree.
+
+Two ways in. "Run as administrator" opens a terminal there, a mistake that still
+stops with an actionable error. And "Run Unsloth at login" starts the desktop
+from an HKCU Run value, which carries no working directory, so it and every CLI
+child inherit System32 (issue #8510). That one is not the user's mistake: the
+desktop's own commands take no paths from the user, so they move to ~/.unsloth
+rather than leaving a tray icon and no server.
+
+Imports stay at `os`: this runs before the command modules, which resolve
+STUDIO_HOME against the working directory.
+"""
+
+import os as _os
+
+# Set by Unsloth Desktop on every CLI child it owns (process.rs). Forging it
+# grants nothing: anyone who can set a child's environment can set its working
+# directory, and the move lands inside the caller's own account.
+DESKTOP_MANAGED_ENV = "UNSLOTH_DESKTOP_MANAGED"
+
+# The directory process.rs pins, so an older desktop lands in the same place.
+WORK_DIR_NAME = ".unsloth"
+
+
+def windows_root(
+ environ,
+ pathmod = _os.path,
+ isdir = None,
+):
+ """Where Windows is installed, for messages."""
+ return windows_roots(environ, pathmod, isdir)[0]
+
+
+def windows_roots(
+ environ,
+ pathmod = _os.path,
+ isdir = None,
+):
+ """Every real Windows directory.
+
+ Candidates are checked, not trusted: a WINDIR aimed at the user's profile
+ would make ordinary folders look like system ones, and one aimed elsewhere
+ would disarm the guard. So a directory counts only if it holds System32.
+ """
+ if isdir is None:
+ isdir = pathmod.isdir
+ system_root = environ.get("SystemRoot")
+ candidates = [system_root, environ.get("WINDIR"), r"C:\Windows"]
+
+ roots = []
+ for value in candidates:
+ if value and value not in roots and isdir(pathmod.join(value, "System32")):
+ roots.append(value)
+ if roots:
+ return roots
+ # No Windows installation found: keep the guard alive on SystemRoot or the
+ # default, never on a user-settable value.
+ return [system_root or r"C:\Windows"]
+
+
+def _strip_extended_prefix(path):
+ r"""Drop the \\?\ (and \\?\UNC\) form so it compares like an ordinary path.
+
+ Matched case-insensitively: the object manager accepts \\?\unc\server\share,
+ and reading that as relative would reject a profile Windows itself resolves.
+ """
+ lowered = path.lower()
+ if lowered.startswith("\\\\?\\unc\\"):
+ return "\\\\" + path[8:]
+ if lowered.startswith("\\\\?\\"):
+ return path[4:]
+ return path
+
+
+def _normalize(path, pathmod):
+ return pathmod.normcase(pathmod.normpath(_strip_extended_prefix(path)))
+
+
+def system_dirs(windir, pathmod = _os.path):
+ """The Windows folders Unsloth refuses to run from."""
+ # SysWOW64 too: a 32-bit elevated shell opens there, same unwritable folder.
+ return [_normalize(pathmod.join(windir, name), pathmod) for name in ("System32", "SysWOW64")]
+
+
+def is_system_dir(
+ cwd,
+ windir,
+ pathmod = _os.path,
+ sep = _os.sep,
+):
+ """True for a system folder itself or anything under it.
+
+ `windir` may be a single directory or several candidates. The separator keeps
+ the match on a path boundary, so C:\\Windows2\\System32x is an ordinary folder.
+ """
+ if not cwd:
+ return False
+ roots = [windir] if isinstance(windir, str) else list(windir)
+ normalized = _normalize(cwd, pathmod)
+ return any(
+ normalized == directory or normalized.startswith(directory + sep)
+ for root in roots
+ for directory in system_dirs(root, pathmod)
+ )
+
+
+def _is_rooted(path, pathmod):
+ """Absolute, or at least rooted at a drive.
+
+ "." and "C:sub" name no directory on their own, so they are no escape
+ (pin_relative_overrides resolves the drive-relative form separately). A
+ leading separator is not absolute, but can never resolve back into System32.
+ """
+ stripped = _strip_extended_prefix(path)
+ return pathmod.isabs(stripped) or stripped.startswith(("\\", "/"))
+
+
+def _is_fully_qualified(path, pathmod):
+ r"""Whether the value names one directory whatever the process does next.
+
+ Narrower than _is_rooted: "\cache" is rooted only to the drive of the current
+ directory, so a profile on another drive silently moves it too. Spelled out
+ rather than deferred to isabs(), which answered True for a leading separator
+ until Python 3.13 and False after: the folder a value names cannot depend on
+ the interpreter running the guard.
+ """
+ stripped = _strip_extended_prefix(path)
+ if stripped.startswith(("\\\\", "//")):
+ # A UNC share names its own root.
+ return True
+ drive, rest = pathmod.splitdrive(stripped)
+ return bool(drive) and rest.startswith(("\\", "/"))
+
+
+def _outside_windows(candidate, windirs, pathmod, sep):
+ if not candidate or not _is_rooted(candidate, pathmod):
+ return False
+ norm = _normalize(candidate, pathmod)
+ for windir in windirs:
+ windir_norm = _normalize(windir, pathmod)
+ # A root-relative candidate carries no drive, so it equals no
+ # drive-qualified root: "\Windows\System32\config\systemprofile" is
+ # SYSTEM's profile on whichever drive, so compare that spelling too.
+ for form in (windir_norm, pathmod.splitdrive(windir_norm)[1]):
+ if not form:
+ continue
+ if norm == form or norm.startswith(form + sep):
+ return False
+ return True
+
+
+def safe_user_dir(
+ environ,
+ windir,
+ pathmod = _os.path,
+ sep = _os.sep,
+ expanduser = None,
+ allow_public = False,
+):
+ """First home outside the Windows tree, or None.
+
+ SYSTEM's USERPROFILE is C:\\Windows\\System32\\config\\systemprofile, so a naive
+ pick lands back in the rejected folder. %PUBLIC% is only ever a suggestion a
+ human can type: moving there would put one account's caches and outputs in a
+ folder every other account can read and write.
+ """
+ if expanduser is None:
+ expanduser = pathmod.expanduser
+ windirs = [windir] if isinstance(windir, str) else list(windir)
+ public = (environ.get("PUBLIC") or "").strip()
+ candidates = [environ.get("USERPROFILE")]
+ if allow_public:
+ candidates.append(public)
+ candidates.append(expanduser("~"))
+ for candidate in candidates:
+ if not _outside_windows(candidate, windirs, pathmod, sep):
+ continue
+ # USERPROFILE and ~ can name the public profile themselves, so the check
+ # is on the folder, not on which variable it came from.
+ if (
+ not allow_public
+ and public
+ and _normalize(candidate, pathmod) == _normalize(public, pathmod)
+ ):
+ continue
+ return candidate
+ return None
+
+
+# Commands the desktop runs that take no path from a user: Studio resolves its
+# venv, llama.cpp, auth, pid files and logs from the Studio home. `update` is here
+# so an older desktop can still upgrade from the tray. Everything else keeps the
+# hard error. Matched whole, not on the first word, since `studio update --local
+# <path>` resolves that path against the working directory.
+_STUDIO_COMMANDS = (
+ ("provision-desktop-auth",),
+ ("desktop-capabilities",),
+ ("desktop-capabilities", "--json"),
+ ("update",),
+)
+_HELP_FLAGS = ("-h", "--help", "--version", "-V")
+_API_ONLY_FLAGS = ("--api-only", "-H", "--host", "-p", "--port")
+
+
+def _is_desktop_backend_launch(rest):
+ """`studio --api-only -H 127.0.0.1 -p 8888` and nothing else: matching
+ --api-only anywhere would also match `studio run --model ./m.gguf --api-only`,
+ a user command with user paths.
+ """
+ if "--api-only" not in rest:
+ return False
+ expects_value = False
+ for arg in rest:
+ if expects_value:
+ expects_value = False
+ continue
+ if arg not in _API_ONLY_FLAGS:
+ return False
+ expects_value = arg != "--api-only"
+ return True
+
+
+# Subcommands that take a path from the caller, by argument or by environment.
+# `run` takes --model and a raw llama-server tail; `update --local` installs
+# from a checkout the caller names.
+_PATH_TAKING_STUDIO_COMMANDS = ("run", "update")
+
+
+def _carries_a_value(arg):
+ """Whether this token can hold a value, attached or not."""
+ if not arg.startswith("-"):
+ return True
+ if arg.startswith("--"):
+ return "=" in arg
+ # A short option carries its value in the same token from the second
+ # character on: `-f.\dist` is Click's spelling of `--frontend .\dist`.
+ return len(arg) > 2
+
+
+def _takes_a_path(rest):
+ """Whether this `studio` invocation can carry a caller's path. Blunt on
+ purpose: the bare forms the desktop runs carry none, so anything else might.
+ """
+ if not rest:
+ return False
+ if rest[0] in _PATH_TAKING_STUDIO_COMMANDS:
+ return tuple(rest) not in _STUDIO_COMMANDS
+ # rest[0] is the subcommand name, skipped unless it is a flag (then there is
+ # no subcommand). An attached value hides inside its own token, so a leading
+ # dash does not clear it: Click reads both `--frontend=.\dist` and the short
+ # `-f.\dist` as a value, and either carries a path a relocation would rebase.
+ tail = rest if rest[0].startswith("-") else rest[1:]
+ return any(_carries_a_value(arg) for arg in tail)
+
+
+def is_relocatable_invocation(argv, environ):
+ """True when this invocation is desktop-managed or provably cwd-independent.
+
+ The argv arm matters on its own: it fixes users whose desktop build predates
+ the Rust-side fix and so sets no marker.
+ """
+ args = [arg for arg in argv if arg]
+ if not args:
+ return False
+ # Click handles top-level -h/--help/--version eagerly, before the callback
+ # this runs from, so only `studio --help` actually arrives here.
+ if all(arg in _HELP_FLAGS for arg in args):
+ return True
+ if args[0] != "studio":
+ # The marker is inherited by everything the backend spawns, so it
+ # authorises the desktop's studio commands and nothing else: rebasing
+ # `train --dataset .\data.json` under a stray one would be worse than the
+ # refusal it replaced.
+ return False
+ rest = args[1:]
+ if environ.get(DESKTOP_MANAGED_ENV) == "1" and not _takes_a_path(rest):
+ # The marker covers a desktop build whose command shape this CLI does not
+ # know yet, but must not widen the set to path-carrying commands: `studio
+ # run --model .\local.gguf` from a marked shell would be rebased.
+ return True
+ if rest and all(arg in _HELP_FLAGS for arg in rest):
+ return True
+ if _is_desktop_backend_launch(rest):
+ return True
+ return tuple(rest) in _STUDIO_COMMANDS
+
+
+# Path overrides the caller may have written relative to the folder being left.
+# Studio resolves them with Path.resolve(), which anchors a relative value to the
+# working directory, so moving first would silently retarget them.
+_RELATIVE_PATH_ENV = (
+ # Studio roots: storage_roots.py.
+ "UNSLOTH_STUDIO_HOME",
+ "STUDIO_HOME",
+ "UNSLOTH_STUDIO_DOCUMENTS_HOME",
+ "UNSLOTH_STUDIO_PROJECTS_HOME",
+ "UNSLOTH_STUDIO_SANDBOX_HOME",
+ # `studio update` reads it, and that command relocates.
+ "STUDIO_LOCAL_REPO",
+ # Engine and tool locations the user may point somewhere of their own.
+ "UNSLOTH_LLAMA_CPP_PATH",
+ "UNSLOTH_LLAMA_CPP_SCRIPTS_DIR",
+ "UNSLOTH_SD_CPP_PATH",
+ "UNSLOTH_WHISPER_CPP_PATH",
+ "LLAMA_SERVER_PATH",
+ "WHISPER_SERVER_PATH",
+ "SD_CLI_PATH",
+ "SD_SERVER_PATH",
+ # Model files llama-server reads straight from the environment, and Studio
+ # reads back when it sizes a launch (llama_cpp.py). The URL and HF-repo
+ # spellings are deliberately absent: they name no local file.
+ "LLAMA_ARG_MODEL",
+ "LLAMA_ARG_MMPROJ",
+ "LLAMA_ARG_MODEL_DRAFT",
+ "LLAMA_ARG_SPEC_DRAFT_MODEL",
+ # Read straight from the environment as a file path: the ASIC table by
+ # unsloth/import_fixes.py, the vLLM cache root by Studio when the caller set
+ # it themselves (storage_roots.py only fills a blank one).
+ "AMDGPU_ASIC_ID_TABLE_PATH",
+ "VLLM_CACHE_ROOT",
+ # A custom ggml backend, preserved into the llama.cpp child (llama_cpp.py).
+ "GGML_BACKEND_PATH",
+ # GPU SDK roots, joined with bin/ for DLL discovery.
+ "CUDA_PATH",
+ "HIP_PATH",
+ "HIP_PATH_57",
+ "ROCM_PATH",
+ "MLX_HOSTFILE",
+ # Read exactly like MLX_HOSTFILE: either inline JSON or a filename.
+ "MLX_IBV_DEVICES",
+ "OLLAMA_MODELS",
+ "DG_VISUAL_BIN",
+ "UNSLOTH_DG_SHIM",
+ # Caches.
+ "UNSLOTH_COMPILE_LOCATION",
+ "TORCHINDUCTOR_CACHE_DIR",
+ "UNSLOTH_DIFFUSION_COMPILE_CACHE_DIR",
+ "UNSLOTH_DIFFUSION_COND_CACHE_DIR",
+ "HF_HOME",
+ "HF_HUB_CACHE",
+ "HUGGINGFACE_HUB_CACHE",
+ "HF_XET_CACHE",
+ "HF_DATASETS_CACHE",
+ "HF_ASSETS_CACHE",
+ # The credential file: a relative value would follow the child and lose
+ # access to gated repos.
+ "HF_TOKEN_PATH",
+ # Read as written, and authoritative when non-blank (storage_roots.py), so
+ # `unsloth studio update` would install from a different cache after a move.
+ "UV_CACHE_DIR",
+ "TRANSFORMERS_CACHE",
+ "SENTENCE_TRANSFORMERS_HOME",
+ "XDG_CACHE_HOME",
+ "XDG_CONFIG_HOME",
+ "XDG_DATA_HOME",
+ "UNSLOTH_STUDIO_CHILD_RECORD",
+ "UNSLOTH_LLAMA_INSTALLER",
+ "CUDA_HOME",
+ "CUDA_ROOT",
+)
+
+# Pinned when it can be, but never at the cost of the move. `studio update
+# --local` is the only command that reads STUDIO_LOCAL_REPO and it takes a path,
+# so it keeps the hard error; the bare update that does relocate drops the value
+# before anything reads it (commands/studio.py). Refusing a System32 update over
+# a stale setting nothing was going to look at would defeat the fallback this
+# guard exists for, so an unresolvable one is left behind instead.
+_BEST_EFFORT_ENV = frozenset(("STUDIO_LOCAL_REPO",))
+
+# The most a Windows environment variable holds, terminator included.
+_WINDOWS_ENV_VALUE_LIMIT = 32767
+
+# The separator is Windows', not the host's: this guard only ever runs on
+# Windows, and os.pathsep would split "D:\\shared" apart anywhere else.
+_PATH_LIST_SEPARATOR = ";"
+
+# Values holding several separated directories, anchored entry by entry. A
+# relative PYTHONPATH entry is resolved at import time, so a move would let
+# whatever sits in the new directory shadow a managed import. PATH is left out on
+# purpose: refusing the whole move over one unresolvable entry in a list that long
+# would cost more than it protects.
+_PATH_LIST_ENV = (
+ "UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH",
+ "CUDA_RUNTIME_DLL_DIR",
+ "PYTHONPATH",
+)
+
+
+def pin_relative_overrides(
+ environ,
+ cwd,
+ pathmod = _os.path,
+ abspath = None,
+ expandvars = None,
+ expanduser = None,
+):
+ """Rewrite relative path overrides so they keep naming the same folder.
+
+ Returns the names pinned. A `~` value is written out, since only some readers
+ expand it themselves.
+ """
+ pinned = []
+ for name in _RELATIVE_PATH_ENV:
+ value = (environ.get(name) or "").strip()
+ try:
+ anchored = _anchor(name, value, cwd, pathmod, abspath, expandvars, expanduser)
+ except Exception:
+ if name not in _BEST_EFFORT_ENV:
+ raise
+ continue
+ if anchored is not None:
+ if len(anchored) >= _WINDOWS_ENV_VALUE_LIMIT:
+ # Anchoring a value that was already near the limit can cross it,
+ # and a variable Windows will not accept is a failure to report
+ # here rather than one to discover in the next process.
+ raise ValueError(
+ f"{name} does not fit in an environment variable once it "
+ "names its folder in full"
+ )
+ environ[name] = anchored
+ pinned.append(name)
+ for name in _PATH_LIST_ENV:
+ raw = environ.get(name) or ""
+ if not raw.strip():
+ continue
+ # Each entry is anchored on its own: one relative entry changes what the
+ # whole list means.
+ entries = raw.split(_PATH_LIST_SEPARATOR)
+ anchored_entries = [
+ _anchor_list_entry(name, e, cwd, pathmod, abspath, expandvars, expanduser)
+ for e in entries
+ ]
+ if anchored_entries != entries:
+ joined = _PATH_LIST_SEPARATOR.join(anchored_entries)
+ if len(joined) >= _WINDOWS_ENV_VALUE_LIMIT:
+ # A value Windows will not accept is a failure to report here,
+ # not one to discover when the next process is started.
+ raise ValueError(
+ f"{name} does not fit in an environment variable once each "
+ "entry names its folder in full"
+ )
+ environ[name] = joined
+ pinned.append(name)
+ return pinned
+
+
+# Values a consumer deliberately does not read as a plain path: anchoring one
+# changes what it means rather than moving a folder. Each exemption names the
+# variables whose reader proves it, since the syntax is only special there and a
+# directory really called "[llama]" or "%data%" is legal on Windows.
+
+# MLX_HOSTFILE holds either a filename or the host list itself, as JSON
+# (`unsloth_cli/_inference.py`, `_json_rank_count_from_env`).
+_INLINE_JSON_ENV = frozenset(("MLX_HOSTFILE", "MLX_IBV_DEVICES"))
+
+# Names whose readers disagree about %VAR% and $VAR: huggingface_hub calls
+# expandvars on HF_HOME (and on the XDG_CACHE_HOME it defaults from), HF_HUB_CACHE
+# and HF_ASSETS_CACHE, and Studio calls it on SENTENCE_TRANSFORMERS_HOME, but
+# Studio's own hf_cache_settings._canonical() does not, so it would read
+# %LOCALAPPDATA%\hf as a relative folder. Expanding here before deciding settles
+# it: both readers then see one absolute path. Scoped to these names because a
+# directory really called "%data%" is legal, and every other name is read as one.
+_EXPANDED_ENV = frozenset(
+ (
+ "HF_HOME",
+ "HF_HUB_CACHE",
+ "HUGGINGFACE_HUB_CACHE",
+ "HF_ASSETS_CACHE",
+ "HF_TOKEN_PATH",
+ "XDG_CACHE_HOME",
+ "SENTENCE_TRANSFORMERS_HOME",
+ )
+)
+
+# The pre-quant allowlist skips a bare on/off token precisely so there is no
+# "allow all" mode (`diffusion_prequant.py`); anchoring one would turn it into a
+# real allowlisted directory.
+_TOGGLE_ENV = frozenset(("UNSLOTH_ALLOW_LOCAL_PREQUANT_PATH",))
+_TOGGLE_TOKENS = frozenset(("1", "true", "yes", "on", "0", "false", "no", "off"))
+
+
+def _names_a_path(name, value):
+ """Whether the working directory is what resolves this variable's value."""
+ if name in _INLINE_JSON_ENV and value.startswith(("[", "{")):
+ return False
+ if name in _TOGGLE_ENV and value.lower() in _TOGGLE_TOKENS:
+ return False
+ return True
+
+
+def pin_relative_sys_path(
+ cwd,
+ pathmod = _os.path,
+ syspath = None,
+ abspath = None,
+ exists = None,
+ expanduser = None,
+):
+ """Anchor the relative import roots this interpreter already carries.
+
+ sys.path holds PYTHONPATH entries as written, including the two spellings that
+ follow the process rather than the caller: an empty entry means the working
+ directory, and a leading `~` is never expanded there.
+
+ Only an entry naming something on disk is touched, folder or archive. The rest
+ are other people's strings rather than paths, such as the relative sentinel
+ setuptools registers for an editable install and accepts back by exact
+ equality; rewriting one breaks the import it was meant to protect, and leaving
+ a real archive breaks the next import from it.
+ """
+ if syspath is None:
+ import sys as _sys
+ syspath = _sys.path
+ if exists is None:
+ exists = _os.path.exists
+ pinned = []
+ for index, entry in enumerate(syspath):
+ if not isinstance(entry, str):
+ continue
+ try:
+ # The empty entry is the working directory by definition; anything
+ # else has to name something that is really there.
+ if entry.strip() and not exists(entry):
+ continue
+ anchored = _anchor_list_entry(
+ "PYTHONPATH", entry, cwd, pathmod, abspath, None, expanduser
+ )
+ except Exception:
+ # Best effort, unlike the environment: an import root this process
+ # already holds is not worth refusing the move over.
+ continue
+ if anchored != entry:
+ syspath[index] = anchored
+ pinned.append(anchored)
+ return pinned
+
+
+def _anchor_list_entry(
+ name,
+ entry,
+ cwd,
+ pathmod,
+ abspath,
+ expandvars,
+ expanduser = None,
+):
+ r"""One entry of a path list, anchored, or left as written.
+
+ PYTHONPATH has two spellings that follow the process rather than the caller:
+ an empty component is the working directory itself, and `~` is never expanded
+ there, so Python reads `~\plugins` as an ordinary relative folder and so does
+ this.
+ """
+ entry = entry.strip()
+ if name == "PYTHONPATH":
+ if not entry:
+ return cwd
+ expanduser = lambda value: value
+ return _anchor(name, entry, cwd, pathmod, abspath, expandvars, expanduser) or entry
+
+
+def _expand_settled(value, expandvars):
+ """The value expanded exactly once, or None if one pass does not settle it.
+
+ One pass is what every reader does, so one pass is what the guard does. The
+ result is only usable if expanding it again would change nothing, because the
+ reader expands whatever gets written back: a value that still holds a
+ reference (a nested %LOCALAPPDATA% that itself holds %USERPROFILE%, an escaped
+ %%NAME%%, a self-reference) would be expanded a second time by the reader and
+ read as a folder with another drive in the middle of it. Those are left
+ exactly as written instead.
+ """
+ expanded = expandvars(value)
+ return expanded if expandvars(expanded) == expanded else None
+
+
+def _anchor(
+ name,
+ value,
+ cwd,
+ pathmod,
+ abspath = None,
+ expandvars = None,
+ expanduser = None,
+):
+ """The value rewritten to name the same folder from anywhere, or None.
+
+ None means no rewriting is needed: empty, or already fully qualified.
+ """
+ original = value = (value or "").strip()
+ if value.startswith("~"):
+ # Written out rather than skipped: only some readers call expanduser
+ # first, and llama_cpp.py hands UNSLOTH_LLAMA_CPP_PATH straight to Path(),
+ # so a move would leave it naming a folder called "~" under the new
+ # directory. It is what the caller meant either way.
+ value = (expanduser or pathmod.expanduser)(value)
+ if name in _EXPANDED_ENV and value:
+ # Written out, so the reader that expands and the one that does not land
+ # in the same folder. An unset variable is left exactly as written.
+ expandvars = expandvars or _os.path.expandvars
+ settled = _expand_settled(value, expandvars)
+ if settled is None:
+ # One pass does not settle it, so writing the result back would have
+ # the reader expand it a second time. What the reader does see is one
+ # pass: if that names a folder on its own the value is safe to leave
+ # alone, and if it does not, the folder it names depends on where the
+ # process is standing and the move has to be refused instead.
+ once = expandvars(value)
+ if _is_fully_qualified(once, pathmod):
+ return None
+ raise ValueError(f"{name} does not expand to one folder")
+ value = settled
+ if not value:
+ return None
+ if _is_fully_qualified(value, pathmod):
+ # Already names one folder, but still worth writing back if expanding is
+ # what made it name one: the reader that does not expand cannot see that.
+ return value if value != original else None
+ if not _names_a_path(name, value):
+ return None
+ if pathmod.splitdrive(value)[0] or value.startswith(("\\", "/")):
+ # "D:cache" is drive D's own current directory and "\cache" the root of
+ # the current drive, neither of which join() knows, so ask the OS. A
+ # failure reaches the caller, which then declines to move at all.
+ return (abspath or pathmod.abspath)(value)
+ return pathmod.join(cwd, value)
+
+
+def relocation_target(
+ environ,
+ windir,
+ pathmod = _os.path,
+ sep = _os.sep,
+ expanduser = None,
+ makedirs = _os.makedirs,
+ home_isdir = None,
+):
+ """Where a desktop-managed command should run instead, or None."""
+ home = safe_user_dir(environ, windir, pathmod, sep, expanduser)
+ if not home:
+ return None
+ if home_isdir is None:
+ home_isdir = pathmod.isdir
+ # A profile that has not mounted yet still has a writable parent, so makedirs
+ # would build an empty second one that shadows the real one when it arrives.
+ if not home_isdir(home):
+ return None
+ work_dir = pathmod.join(home, WORK_DIR_NAME)
+ try:
+ makedirs(work_dir, exist_ok = True)
+ except OSError:
+ # An unwritable home is a broken profile and Studio must write there
+ # anyway, so stop now rather than failing later.
+ return None
+ return work_dir
+
+
+def blocked_message(
+ cwd,
+ argv,
+ environ,
+ windir,
+ pathmod = _os.path,
+ sep = _os.sep,
+ expanduser = None,
+):
+ """The error shown to someone who ran Unsloth from a system folder by hand."""
+ # allow_public here only: a person can sensibly `cd C:\Users\Public`, but
+ # relocating there would share one account's state with every other account.
+ home = safe_user_dir(environ, windir, pathmod, sep, expanduser, allow_public = True)
+ if home:
+ # Quote it, or C:\Users\Jane Doe reaches Set-Location as two arguments.
+ # PowerShell single quotes are verbatim ('' escapes an apostrophe); cmd
+ # needs double quotes once extensions are off.
+ home_ps = "'" + home.replace("'", "''") + "'"
+ home_cmd = '"' + home + '"'
+ cd_lines = (
+ f" cd {home_ps} (PowerShell)\n" f" cd /d {home_cmd} (cmd.exe)\n"
+ )
+ else:
+ cd_lines = f" (any folder outside {windir if isinstance(windir, str) else windir[0]})\n"
+ rendered_argv = " ".join((f'"{arg}"' if " " in arg else arg) for arg in argv)
+ retry = ("unsloth " + rendered_argv).rstrip()
+ return (
+ f"Unsloth cannot run from {cwd}\n"
+ "\n"
+ "That is a Windows system folder. Windows blocks writes here, and any\n"
+ "relative path you pass would resolve inside the Windows folder.\n"
+ "Opening a terminal with 'Run as administrator' starts you in a folder like\n"
+ "this one, which is how most people end up here.\n"
+ "\n"
+ "Change to a normal folder and run the command again:\n"
+ f"{cd_lines}"
+ f" {retry}"
+ )
+
+
+def check_working_directory(
+ argv,
+ environ,
+ platform,
+ getcwd = _os.getcwd,
+ chdir = _os.chdir,
+ pathmod = _os.path,
+ sep = _os.sep,
+ expanduser = None,
+ makedirs = _os.makedirs,
+ isdir = None,
+ abspath = None,
+ home_isdir = None,
+ exists = None,
+ syspath = None,
+ expandvars = None,
+ relocate = True,
+):
+ """Decide what to do about the current working directory.
+
+ Returns (message, colour, fatal). `fatal` is the caller's cue to exit 1;
+ a message with fatal False is a warning printed after a successful move.
+ """
+ if platform != "win32":
+ return None, None, False
+
+ windirs = windows_roots(environ, pathmod, isdir)
+ windir = windirs[0]
+ try:
+ cwd = getcwd()
+ except OSError:
+ # The launch directory is gone: say so rather than name a folder they
+ # were never in.
+ return (
+ (
+ "Unsloth cannot determine its current folder. It may have been deleted,\n"
+ "or it may be on a drive that is no longer available.\n"
+ "Change to a folder that exists and run the command again."
+ ),
+ "red",
+ True,
+ )
+
+ if not is_system_dir(cwd, windirs, pathmod, sep):
+ return None, None, False
+
+ if not relocate or not is_relocatable_invocation(argv, environ):
+ # `relocate = False` is the imported-as-a-library case: the command
+ # modules are already loaded, so a move now is too late for the roots they
+ # resolved at import time.
+ return blocked_message(cwd, argv, environ, windirs, pathmod, sep, expanduser), "red", True
+
+ target = relocation_target(environ, windirs, pathmod, sep, expanduser, makedirs, home_isdir)
+ unpinnable = None
+ # The caller's own process state when the guard runs inside a host, so nothing
+ # stays rewritten unless the move actually happens.
+ environ_before = dict(environ)
+ if syspath is None:
+ # Resolved here rather than inside the pinning, or the console script,
+ # which passes nothing, would rewrite the real sys.path with no snapshot
+ # to put back when the move then fails.
+ import sys as _sys
+ syspath = _sys.path
+ syspath_before = list(syspath)
+ if target is not None:
+ try:
+ # Before moving, or a relative override would end up naming a folder
+ # under the new directory instead of theirs.
+ pin_relative_overrides(environ, cwd, pathmod, abspath, expandvars, expanduser)
+ # This interpreter read PYTHONPATH before the guard ran and keeps the
+ # entries as written, resolving a relative one on every import, so it
+ # needs anchoring here as well as in the environment.
+ pin_relative_sys_path(cwd, pathmod, syspath, abspath, exists, expanduser)
+ except Exception as error:
+ # An environment we cannot pin is one we must not move underneath.
+ # Both reasons are real: a drive with no current directory, and a list
+ # that no longer fits in a Windows variable once fully qualified.
+ unpinnable = error
+ target = None
+ moved = False
+ if target is not None:
+ try:
+ chdir(target)
+ except OSError:
+ target = None
+ else:
+ moved = True
+ # Confirm where it landed rather than trusting chdir not to raise.
+ try:
+ if is_system_dir(getcwd(), windirs, pathmod, sep):
+ target = None
+ except OSError:
+ target = None
+ if target is None:
+ # It landed somewhere the CLI still refuses, so go back: the
+ # values written for the move only mean the same folder from the
+ # directory they were written in.
+ try:
+ chdir(cwd)
+ except OSError:
+ pass
+ else:
+ moved = False
+ if target is None and not moved:
+ # Nothing moved, so nothing stays rewritten: put back what pinning wrote.
+ if environ_before != environ:
+ environ.clear()
+ environ.update(environ_before)
+ if syspath_before != syspath:
+ syspath[:] = syspath_before
+ if unpinnable is not None:
+ # Named separately from the profile case below: blaming the user folder
+ # for an unpinnable override sends them looking in the wrong place.
+ return (
+ (
+ f"Unsloth cannot run from {cwd}, and could not move out of it\n"
+ "without changing where one of its path settings points\n"
+ f"({type(unpinnable).__name__}: {unpinnable}).\n"
+ "Set that value to a full path, or start Unsloth from a normal folder."
+ ),
+ "red",
+ True,
+ )
+ if target is None:
+ # Fail closed: nowhere usable outside the Windows tree. This text lands in
+ # the desktop's logs, so it describes that case, not a shell.
+ return (
+ (
+ f"Unsloth cannot run from {cwd}, and no folder outside {windir} was\n"
+ "available to run from instead. Check that the user profile for this\n"
+ "account exists and is writable."
+ ),
+ "red",
+ True,
+ )
+
+ return (
+ (
+ f"Unsloth was started from {cwd}, which is a Windows system folder,\n"
+ f"so it switched to {target} instead.\n"
+ "This happens when Unsloth Desktop is started by 'Run Unsloth at login'."
+ ),
+ "yellow",
+ False,
+ )