Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio Desktop: choose where Unsloth installs on Windows (#13446)

Daniel Han45b39168e64c
diff --git a/install.ps1 b/install.ps1
index aaa8fe4eeca..0750bf662f9 100644
--- a/install.ps1
+++ b/install.ps1
@@ -3154,8 +3154,11 @@ function Install-UnslothStudio {
}
# Custom Unsloth roots are not supported with --tauri (the desktop app uses
- # the Windows profile folder). Pass through if the override is that same root.
- if ($TauriMode -and $envOverride) {
+ # the Windows profile folder). Pass through if the override is that same root,
+ # or the one the desktop chose (UNSLOTH_DESKTOP_CHOSEN_STUDIO_HOME=1).
+ $tauriChosenRoot = ($TauriMode -and $envOverrideVar -eq "UNSLOTH_STUDIO_HOME" -and
+ $env:UNSLOTH_DESKTOP_CHOSEN_STUDIO_HOME -eq "1")
+ if ($TauriMode -and $envOverride -and -not $tauriChosenRoot) {
$_tauriOverride = $envOverride
if ($_tauriOverride -eq "~" -or $_tauriOverride -like "~/*" -or $_tauriOverride -like "~\*") {
$_tauriOverride = (Join-Path $env:USERPROFILE $_tauriOverride.Substring(1).TrimStart('/','\'))
@@ -3246,6 +3249,32 @@ function Install-UnslothStudio {
Restore-StudioTempEnvironment
throw "$envOverrideVar=$StudioHome is not writable."
}
+ # A new desktop-chosen root would inherit its drive's ACL (often writable by every
+ # account): give it the profile's access instead. An existing folder keeps its ACL.
+ if ($tauriChosenRoot -and -not $script:StudioEnvRootExisted) {
+ try {
+ $rootAcl = New-Object System.Security.AccessControl.DirectorySecurity
+ $rootAcl.SetAccessRuleProtection($true, $false)
+ $inherit = [System.Security.AccessControl.InheritanceFlags]"ContainerInherit, ObjectInherit"
+ foreach ($sid in @(
+ [System.Security.Principal.WindowsIdentity]::GetCurrent().User,
+ (New-Object System.Security.Principal.SecurityIdentifier "S-1-5-18"),
+ (New-Object System.Security.Principal.SecurityIdentifier "S-1-5-32-544"))) {
+ $rootAcl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule(
+ $sid, [System.Security.AccessControl.FileSystemRights]::FullControl, $inherit,
+ [System.Security.AccessControl.PropagationFlags]::None,
+ [System.Security.AccessControl.AccessControlType]::Allow)))
+ }
+ $rootInfo = New-Object System.IO.DirectoryInfo $StudioHome
+ if ($rootInfo.PSObject.Methods['SetAccessControl']) {
+ $rootInfo.SetAccessControl($rootAcl)
+ } else {
+ [System.IO.FileSystemAclExtensions]::SetAccessControl($rootInfo, $rootAcl)
+ }
+ } catch {
+ Write-StudioLine "[WARN] Could not restrict access to ${StudioHome}: $($_.Exception.Message)" -ForegroundColor Yellow
+ }
+ }
$StudioDataDir = Join-Path $StudioHome "share"
$StudioRedirectMode = 'env'
} elseif ($defaultProfile -and $env:USERPROFILE -and ($env:USERPROFILE -ne $defaultProfile)) {
diff --git a/scripts/uninstall.ps1 b/scripts/uninstall.ps1
index 36296561ea1..80062a643ed 100644
--- a/scripts/uninstall.ps1
+++ b/scripts/uninstall.ps1
@@ -815,6 +815,13 @@ Environment:
$confRoot = _RootFromConf (Join-Path $env:LOCALAPPDATA "Unsloth Studio\studio.conf")
if ($confRoot) { & $emit $confRoot }
}
+ # The folder Unsloth Desktop installed into (studio_home.rs).
+ if ($env:USERPROFILE) {
+ $desktopChoice = Join-Path $env:USERPROFILE ".unsloth\desktop_studio_home"
+ if (Test-Path -LiteralPath $desktopChoice -PathType Leaf) {
+ try { & $emit ([System.IO.File]::ReadAllText($desktopChoice).Trim()) } catch {}
+ }
+ }
}
# Return $true iff the PID's image path lives under one of $KnownRoots, so an unrelated
@@ -1311,6 +1318,17 @@ Environment:
}
}
}
+ # Desktop's install-location choice goes with the folder it names.
+ if ($defaultUnslothHome) {
+ $desktopChoice = Join-Path $defaultUnslothHome "desktop_studio_home"
+ if (Test-Path -LiteralPath $desktopChoice -PathType Leaf) {
+ $chosenRoot = $null
+ try { $chosenRoot = [System.IO.File]::ReadAllText($desktopChoice).Trim() } catch {}
+ if (-not $chosenRoot -or -not (Test-Path -LiteralPath $chosenRoot)) {
+ _RemovePath $desktopChoice
+ }
+ }
+ }
# Drop ~/.unsloth itself, but ONLY if now empty -- never nuke unrelated content.
if ($defaultUnslothHome -and (Test-Path -LiteralPath $defaultUnslothHome) -and
-not (Get-ChildItem -LiteralPath $defaultUnslothHome -Force -ErrorAction SilentlyContinue)) {
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index e1d0c36ae4a..3490a2269e6 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -143,8 +143,12 @@ export const BUDGET = {
// Hub Run refusing audio models neither Audio nor chat can run (#13812) adds 77 B raw / 65 B transfer
// (6,773,445 -> 6,773,522 B raw, 2,036,392 -> 2,036,457 B transfer against 59ab069b5, one machine and build,
// Node 24, chunk count unchanged at 95). Raised by that growth.
- transferBytes: 2_036_479,
- rawBytes: 6_773_573,
+ // The Windows Desktop install location row on the first-run screen (#13446) adds 1,324 B raw / 342 B
+ // transfer (6,773,496 -> 6,774,820 B raw, 2,036,386 -> 2,036,728 B transfer against 59ab069b5, one machine
+ // and build, Node 24, chunk count unchanged at 95). Lazy-loading it cost more transfer and a 96th startup
+ // chunk (Rollup split react-dom out), so it is imported statically and the budget raised by that growth.
+ transferBytes: 2_036_821,
+ rawBytes: 6_774_897,
};
// The chunk count is reported but not budgeted. Splitting a page out of the entry raises it while lowering the
diff --git a/studio/frontend/src/components/tauri/install-location.tsx b/studio/frontend/src/components/tauri/install-location.tsx
new file mode 100644
index 00000000000..0084fc73cc8
--- /dev/null
+++ b/studio/frontend/src/components/tauri/install-location.tsx
@@ -0,0 +1,81 @@
+// 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 { Button } from "@/components/ui/button";
+import { useEffect, useState } from "react";
+
+interface StudioInstallLocation {
+ path: string;
+ is_default: boolean;
+ can_change: boolean;
+}
+
+// Windows Desktop only: elsewhere, or on an older shell, nothing renders.
+export default function InstallLocation({ disabled }: { disabled: boolean }) {
+ const [location, setLocation] = useState<StudioInstallLocation | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ void (async () => {
+ try {
+ const { invoke } = await import("@tauri-apps/api/core");
+ const next = await invoke<StudioInstallLocation>(
+ "studio_install_location",
+ );
+ if (!cancelled) setLocation(next);
+ } catch {
+ // Older shell without the command.
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ if (!location?.can_change) return null;
+
+ async function run(command: string) {
+ setBusy(true);
+ setError(null);
+ try {
+ const { invoke } = await import("@tauri-apps/api/core");
+ const next = await invoke<StudioInstallLocation | null>(command);
+ if (next) setLocation(next);
+ } catch (e) {
+ setError(String(e));
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ return (
+ <div className="flex max-w-[min(560px,90vw)] flex-col items-center gap-1 text-center text-ui-12 text-muted-foreground">
+ <p className="break-all">
+ Install location: <span className="text-foreground">{location.path}</span>
+ </p>
+ <div className="flex items-center gap-3">
+ <Button
+ variant="link"
+ size="xs"
+ disabled={disabled || busy}
+ onClick={() => void run("choose_studio_install_location")}
+ >
+ Change
+ </Button>
+ {!location.is_default && (
+ <Button
+ variant="link"
+ size="xs"
+ disabled={disabled || busy}
+ onClick={() => void run("reset_studio_install_location")}
+ >
+ Use default
+ </Button>
+ )}
+ </div>
+ {error && <p className="text-xs text-destructive">{error}</p>}
+ </div>
+ );
+}
diff --git a/studio/frontend/src/components/tauri/startup-screen.tsx b/studio/frontend/src/components/tauri/startup-screen.tsx
index 368fcfc5d33..6c6c6649472 100644
--- a/studio/frontend/src/components/tauri/startup-screen.tsx
+++ b/studio/frontend/src/components/tauri/startup-screen.tsx
@@ -2,6 +2,7 @@
// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
import { DiagnosticsCopyActions } from "@/components/tauri/diagnostics-copy-actions";
+import InstallLocation from "@/components/tauri/install-location";
import { LogDetails } from "@/components/tauri/log-details";
import {
installProgressMessage,
@@ -79,6 +80,7 @@ function CheckingContent() {
}
function NotInstalledContent({ onInstall }: { onInstall: () => void }) {
+ const [starting, setStarting] = useState(false);
return (
<div className="flex h-full flex-col items-center">
<div className="flex flex-1 flex-col items-center justify-center">
@@ -91,9 +93,16 @@ function NotInstalledContent({ onInstall }: { onInstall: () => void }) {
>
To install Unsloth, click Get Started.
</p>
- <Button size="hero" onClick={onInstall}>
+ <Button
+ size="hero"
+ onClick={() => {
+ setStarting(true);
+ onInstall();
+ }}
+ >
Get Started
</Button>
+ <InstallLocation disabled={starting} />
</div>
</div>
);
diff --git a/studio/src-tauri/src/commands.rs b/studio/src-tauri/src/commands.rs
index 04f67dcfb53..10fac51e1e6 100644
--- a/studio/src-tauri/src/commands.rs
+++ b/studio/src-tauri/src/commands.rs
@@ -332,10 +332,12 @@ pub async fn check_install_status() -> bool {
#[cfg(target_os = "linux")]
crate::process::scrub_appimage_python_env_tokio(&mut cmd);
- // Tauri uses the legacy root regardless of UNSLOTH_STUDIO_HOME / STUDIO_HOME;
- // probe subprocesses must follow the same isolation as process.rs.
+ // Inherited roots are dropped; the desktop's own root is passed instead, as in process.rs.
cmd.env_remove("UNSLOTH_STUDIO_HOME");
cmd.env_remove("STUDIO_HOME");
+ if let Some(root) = crate::studio_home::chosen_root() {
+ cmd.env(crate::studio_home::STUDIO_HOME_ENV, root);
+ }
let mut child = match process::with_studio_runtime_launch_guard(|| {
cmd.spawn().map_err(|error| error.to_string())
diff --git a/studio/src-tauri/src/desktop_auth.rs b/studio/src-tauri/src/desktop_auth.rs
index 19f3188e19a..c9c221b1e18 100644
--- a/studio/src-tauri/src/desktop_auth.rs
+++ b/studio/src-tauri/src/desktop_auth.rs
@@ -86,8 +86,7 @@ impl AuthError {
}
fn auth_secret_path(home: &Path, filename: &str) -> PathBuf {
- home.join(".unsloth")
- .join("studio")
+ crate::studio_home::studio_root_for_home(home)
.join("auth")
.join(filename)
}
@@ -269,10 +268,13 @@ async fn provision_desktop_auth() -> Result<(), String> {
#[cfg(target_os = "linux")]
crate::process::scrub_appimage_python_env_tokio(&mut cmd);
- // Tauri uses the legacy root regardless of UNSLOTH_STUDIO_HOME / STUDIO_HOME.
- // Scrub so provisioning writes match what the Rust auth code reads.
+ // Inherited roots are dropped and the desktop's own root passed, so provisioning writes
+ // match what the Rust auth code reads.
cmd.env_remove("UNSLOTH_STUDIO_HOME");
cmd.env_remove("STUDIO_HOME");
+ if let Some(root) = crate::studio_home::chosen_root() {
+ cmd.env(crate::studio_home::STUDIO_HOME_ENV, root);
+ }
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
diff --git a/studio/src-tauri/src/desktop_backend_owner.rs b/studio/src-tauri/src/desktop_backend_owner.rs
index bf513e1ecc4..59889c1fce1 100644
--- a/studio/src-tauri/src/desktop_backend_owner.rs
+++ b/studio/src-tauri/src/desktop_backend_owner.rs
@@ -206,14 +206,13 @@ pub(crate) fn parse_studio_root_id(value: &str) -> Option<String> {
}
pub(crate) fn managed_studio_root_id_path(home: &Path) -> PathBuf {
- home.join(".unsloth")
- .join("studio")
+ crate::studio_home::studio_root_for_home(home)
.join("share")
.join("studio_install_id")
}
fn managed_run_dir(home: &Path) -> PathBuf {
- home.join(".unsloth").join("studio").join("run")
+ crate::studio_home::studio_root_for_home(home).join("run")
}
fn metadata_path_for_home(home: &Path) -> PathBuf {
@@ -221,8 +220,7 @@ fn metadata_path_for_home(home: &Path) -> PathBuf {
}
fn auth_secret_path_for_home(home: &Path) -> PathBuf {
- home.join(".unsloth")
- .join("studio")
+ crate::studio_home::studio_root_for_home(home)
.join("auth")
.join(".desktop_secret")
}
diff --git a/studio/src-tauri/src/diagnostics/mod.rs b/studio/src-tauri/src/diagnostics/mod.rs
index aca3befe6fa..c5b91ce51b4 100644
--- a/studio/src-tauri/src/diagnostics/mod.rs
+++ b/studio/src-tauri/src/diagnostics/mod.rs
@@ -53,11 +53,25 @@ pub(crate) fn new_id(prefix: &str) -> String {
format!("{}-{}-{}", sanitize_component(prefix), now_ms(), n)
}
+/// A chosen root only once it exists: creating it here would stop install.ps1 claiming it.
pub fn studio_dir() -> PathBuf {
- dirs::home_dir()
- .unwrap_or_else(|| PathBuf::from("."))
- .join(".unsloth")
- .join("studio")
+ let home = dirs::home_dir().unwrap_or_else(|| PathBuf::from("."));
+ crate::studio_home::chosen_root_for_home(&home)
+ .filter(|root| root.is_dir())
+ .unwrap_or_else(|| crate::studio_home::default_root_for_home(&home))
+}
+
+/// Plus the default root while a chosen one is in use: a first install logs there until it exists.
+pub fn log_roots() -> Vec<PathBuf> {
+ let current = studio_dir();
+ let mut roots = vec![current.clone()];
+ if let Some(home) = dirs::home_dir() {
+ let default = crate::studio_home::default_root_for_home(&home);
+ if default != current && default.is_dir() {
+ roots.push(default);
+ }
+ }
+ roots
}
pub fn logs_dir() -> PathBuf {
diff --git a/studio/src-tauri/src/diagnostics/phase_log.rs b/studio/src-tauri/src/diagnostics/phase_log.rs
index 70ab5478d2e..c2303cb6c94 100644
--- a/studio/src-tauri/src/diagnostics/phase_log.rs
+++ b/studio/src-tauri/src/diagnostics/phase_log.rs
@@ -429,7 +429,14 @@ struct PhaseLogMeta {
}
fn scan_phase_logs(warnings: &mut Vec<String>) -> Vec<PhaseLogMeta> {
- scan_phase_logs_in_dir(&logs_dir(), warnings)
+ let mut found = scan_phase_logs_in_dir(&logs_dir(), warnings);
+ for root in super::log_roots().into_iter().skip(1) {
+ let dir = root.join("logs");
+ if dir.is_dir() {
+ found.extend(scan_phase_logs_in_dir(&dir, warnings));
+ }
+ }
+ found
}
fn scan_phase_logs_in_dir(dir: &Path, warnings: &mut Vec<String>) -> Vec<PhaseLogMeta> {
diff --git a/studio/src-tauri/src/diagnostics/redaction.rs b/studio/src-tauri/src/diagnostics/redaction.rs
index 2cb5e8ac1db..2f310097b9c 100644
--- a/studio/src-tauri/src/diagnostics/redaction.rs
+++ b/studio/src-tauri/src/diagnostics/redaction.rs
@@ -185,6 +185,10 @@ fn looks_like_credential(value: &str) -> bool {
fn replace_known_paths(input: &str, report: &mut RedactionReport) -> String {
let mut out = input.to_string();
+ // The chosen root whether or not it exists yet: installer errors name it before it does.
+ if let Some(chosen) = crate::studio_home::chosen_root() {
+ out = replace_path_literal(&out, &chosen, "<studio_home>", report);
+ }
let studio = studio_dir();
out = replace_path_literal(&out, &studio, "<studio_home>", report);
if let Some(home) = dirs::home_dir() {
diff --git a/studio/src-tauri/src/diagnostics/report.rs b/studio/src-tauri/src/diagnostics/report.rs
index 184fb15c99a..53bee6d48a5 100644
--- a/studio/src-tauri/src/diagnostics/report.rs
+++ b/studio/src-tauri/src/diagnostics/report.rs
@@ -358,9 +358,14 @@ fn append_log_sections(
warnings: &mut Vec<String>,
) {
out.push_str("\n== Log tails ==\n");
- for name in ["tauri.log", "tauri.log.1"] {
- let path = studio_dir().join(name);
- append_tail_section(out, &path, name, "local-app-log", warnings);
+ for (index, root) in super::log_roots().into_iter().enumerate() {
+ for name in ["tauri.log", "tauri.log.1"] {
+ let path = root.join(name);
+ if index > 0 && !path.is_file() {
+ continue;
+ }
+ append_tail_section(out, &path, name, "local-app-log", warnings);
+ }
}
let server_log_dir = logs_dir().join("server");
diff --git a/studio/src-tauri/src/install.rs b/studio/src-tauri/src/install.rs
index d1015116105..33af79cf5bb 100644
--- a/studio/src-tauri/src/install.rs
+++ b/studio/src-tauri/src/install.rs
@@ -697,14 +697,21 @@ fn spawn_script(
#[cfg(target_os = "linux")]
crate::process::scrub_appimage_python_env(&mut cmd);
- // Tauri only does default-root installs; install.sh / install.ps1 reject
- // these under --tauri. Scrub so an inherited value can't trip the guard.
+ // install.sh / install.ps1 reject inherited custom roots under --tauri, so
+ // scrub them and pass only the desktop's chosen root, with its flag.
// Applied by hand here, the one managed spawn outside
// apply_managed_cli_context: the Python setup.sh starts reads whatever is
// exported, even though setup.sh assigns UNSLOTH_HOME itself.
for name in crate::process::MANAGED_CHILD_SCRUBBED_ENV {
cmd.env_remove(name);
}
+ if let Some(root) = crate::studio_home::chosen_root() {
+ // Re-checked here, not only when chosen: files may have landed in the folder since.
+ crate::studio_home::validate_root(&root)?;
+ cmd.env(crate::studio_home::STUDIO_HOME_ENV, root);
+ cmd.env(crate::studio_home::DESKTOP_CHOSEN_HOME_ENV, "1");
+ cmd.env("UNSLOTH_ISOLATE_UV_CACHE", "1");
+ }
cmd.env(
"UNSLOTH_DESKTOP_BACKEND_VERSION",
crate::preflight::expected_backend_version(),
@@ -1201,6 +1208,18 @@ pub fn record_install_intentional_stop(state: &InstallState, diagnostics: &Diagn
}
}
+/// Runs `operation` under the install lock with no installer running (spawn_script reads the root under it).
+pub fn while_install_idle<T>(
+ state: &InstallState,
+ operation: impl FnOnce() -> Result<T, String>,
+) -> Result<T, String> {
+ let install = state.lock().map_err(|e| e.to_string())?;
+ if install.child.is_some() {
+ return Err("Installation is already running.".to_string());
+ }
+ operation()
+}
+
/// True while an installer runs; quitting now would leave a broken venv.
pub fn is_install_running(state: &InstallState) -> bool {
state
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index 69e978e8ea7..6d3fd9003a9 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -40,6 +40,7 @@ mod process;
mod process_identity;
mod shell_path;
mod staged_update;
+mod studio_home;
mod update;
mod webview_permissions;
mod windows_job;
@@ -795,9 +796,11 @@ fn setup_logging() {
simplelog::ColorChoice::Auto,
));
- // Try to set up file logging to ~/.unsloth/studio/tauri.log
+ // Try to set up file logging to ~/.unsloth/studio/tauri.log (a chosen root once it exists).
if let Some(home) = dirs::home_dir() {
- let log_dir = home.join(".unsloth").join("studio");
+ let log_dir = studio_home::chosen_root_for_home(&home)
+ .filter(|root| root.is_dir())
+ .unwrap_or_else(|| studio_home::default_root_for_home(&home));
if fs::create_dir_all(&log_dir).is_ok() {
let log_path = log_dir.join("tauri.log");
let rotated_path = log_dir.join("tauri.log.1");
@@ -2312,6 +2315,9 @@ fn main() {
app_layout::reset_app_window_layout_initialized,
app_layout::take_native_layout_restored,
commands::check_install_status,
+ studio_home::studio_install_location,
+ studio_home::choose_studio_install_location,
+ studio_home::reset_studio_install_location,
commands::desktop_preflight,
commands::start_install,
commands::start_server,
diff --git a/studio/src-tauri/src/native_path_policy.rs b/studio/src-tauri/src/native_path_policy.rs
index 4b95202e96f..9d87b90a87e 100644
--- a/studio/src-tauri/src/native_path_policy.rs
+++ b/studio/src-tauri/src/native_path_policy.rs
@@ -1021,7 +1021,7 @@ fn ensure_artifact_root(kind: NativeArtifactKind, canonical_path: &Path) -> Resu
let Some(home) = dirs::home_dir() else {
return Err("Could not determine home directory.".to_string());
};
- let studio = home.join(".unsloth").join("studio");
+ let studio = crate::studio_home::studio_root_for_home(&home);
let allowed_root = match kind {
NativeArtifactKind::TrainingOutput => studio.join("outputs"),
NativeArtifactKind::Export => studio.join("exports"),
@@ -1125,6 +1125,13 @@ pub(crate) fn reject_sensitive_document_folder(path: &Path) -> Result<(), String
for relative in [".unsloth"] {
sensitive_roots.push(home.join(relative));
}
+ // Canonical as well: callers pass canonical paths, which carry \\?\ on Windows.
+ if let Some(chosen) = crate::studio_home::chosen_root_for_home(&home) {
+ if let Ok(canonical) = chosen.canonicalize() {
+ sensitive_roots.push(canonical);
+ }
+ sensitive_roots.push(chosen);
+ }
}
if let Some(config) = dirs::config_dir() {
sensitive_roots.push(config);
diff --git a/studio/src-tauri/src/preflight/managed.rs b/studio/src-tauri/src/preflight/managed.rs
index 640e3fa996b..4787f5528a0 100644
--- a/studio/src-tauri/src/preflight/managed.rs
+++ b/studio/src-tauri/src/preflight/managed.rs
@@ -707,6 +707,11 @@ fn llama_runtime_root(bin: &Path) -> Option<PathBuf> {
if let Some(inferred) = inferred_studio_llama_root(bin) {
return Some(inferred);
}
+ // The CLI keeps llama.cpp inside a custom root (_ensure_studio_env_exported).
+ #[cfg(not(test))]
+ if let Some(chosen) = crate::studio_home::chosen_root() {
+ return Some(chosen.join("llama.cpp"));
+ }
#[cfg(not(test))]
return Some(dirs::home_dir()?.join(".unsloth").join("llama.cpp"));
}
@@ -884,9 +889,7 @@ fn capability_cache_path() -> Option<PathBuf> {
}
dirs::home_dir().map(|home| {
- home.join(".unsloth")
- .join("studio")
- .join("desktop_capability_cache.json")
+ crate::studio_home::studio_root_for_home(&home).join("desktop_capability_cache.json")
})
}
@@ -1009,10 +1012,12 @@ async fn run_cli_probe(bin: &Path, args: &[&str]) -> Result<bool, String> {
#[cfg(target_os = "linux")]
crate::process::scrub_appimage_python_env_tokio(&mut cmd);
- // Tauri uses the legacy root regardless of UNSLOTH_STUDIO_HOME / STUDIO_HOME;
- // probe subprocesses must follow the same isolation as process.rs.
+ // Inherited roots are dropped; the desktop's own root is passed instead, as in process.rs.
cmd.env_remove("UNSLOTH_STUDIO_HOME");
cmd.env_remove("STUDIO_HOME");
+ if let Some(root) = crate::studio_home::chosen_root() {
+ cmd.env(crate::studio_home::STUDIO_HOME_ENV, root);
+ }
#[cfg(windows)]
{
@@ -1084,10 +1089,12 @@ async fn probe_cli_capability(bin: &Path) -> Result<Option<DesktopCapability>, S
#[cfg(target_os = "linux")]
crate::process::scrub_appimage_python_env_tokio(&mut cmd);
- // Tauri uses the legacy root regardless of UNSLOTH_STUDIO_HOME / STUDIO_HOME;
- // probe subprocesses must follow the same isolation as process.rs.
+ // Inherited roots are dropped; the desktop's own root is passed instead, as in process.rs.
cmd.env_remove("UNSLOTH_STUDIO_HOME");
cmd.env_remove("STUDIO_HOME");
+ if let Some(root) = crate::studio_home::chosen_root() {
+ cmd.env(crate::studio_home::STUDIO_HOME_ENV, root);
+ }
#[cfg(windows)]
{
diff --git a/studio/src-tauri/src/process.rs b/studio/src-tauri/src/process.rs
index 87d079c710c..1e2bbc47db9 100644
--- a/studio/src-tauri/src/process.rs
+++ b/studio/src-tauri/src/process.rs
@@ -515,9 +515,46 @@ fn current_windows_user_sid() -> Result<String, String> {
}
#[cfg(windows)]
-fn acquire_studio_runtime_launch_guard() -> Result<StudioManagedRuntimeLaunchGuard, String> {
+const STUDIO_MANAGED_RUNTIME_PATH_MUTEX_PREFIX: &str =
+ "Global\\UnslothStudioManagedEnvironmentPath-";
+
+/// Mirrors `_resolved_windows_path` in unsloth_cli/_studio_runtime_gate.py.
+#[cfg(windows)]
+fn resolved_windows_path_text(path: &std::path::Path) -> String {
+ let resolved = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
+ let mut text = resolved.to_string_lossy().into_owned();
+ if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
+ text = format!(r"\\{rest}");
+ } else if let Some(rest) = text.strip_prefix(r"\\?\") {
+ text = rest.to_string();
+ }
+ let trimmed = text.trim_end_matches(['\\', '/']);
+ if trimmed.len() == 2 && trimmed.ends_with(':') {
+ return format!("{trimmed}\\");
+ }
+ trimmed.to_string()
+}
+
+/// The CLI and install.ps1 lock a custom root by path hash, not SID; take that lock too.
+#[cfg(windows)]
+fn chosen_root_runtime_mutex_name() -> Option<String> {
+ use sha2::{Digest, Sha256};
+ let root = crate::studio_home::chosen_root()?;
+ let digest = Sha256::digest(resolved_windows_path_text(&root).as_bytes());
+ Some(format!(
+ "{STUDIO_MANAGED_RUNTIME_PATH_MUTEX_PREFIX}{}",
+ crate::native_backend_lease::hex_bytes(&digest)
+ ))
+}
+
+#[cfg(windows)]
+fn acquire_studio_runtime_launch_guard() -> Result<Vec<StudioManagedRuntimeLaunchGuard>, String> {
let name = studio_runtime_mutex_name_for_sid(&current_windows_user_sid()?);
- acquire_named_studio_runtime_launch_guard(&name)
+ let mut guards = vec![acquire_named_studio_runtime_launch_guard(&name)?];
+ if let Some(path_name) = chosen_root_runtime_mutex_name() {
+ guards.push(acquire_named_studio_runtime_launch_guard(&path_name)?);
+ }
+ Ok(guards)
}
#[cfg(unix)]
@@ -552,7 +589,7 @@ fn acquire_studio_runtime_launch_guard() -> Result<StudioManagedRuntimeLaunchGua
}
/// serialize managed-environment child creation with install and repair.
-#[cfg(windows)]
+#[cfg(all(windows, test))]
fn with_named_studio_runtime_launch_guard<T>(
name: &str,
operation: impl FnOnce() -> Result<T, String>,
@@ -566,8 +603,8 @@ pub(crate) fn with_studio_runtime_launch_guard<T>(
) -> Result<T, String> {
#[cfg(windows)]
{
- let name = studio_runtime_mutex_name_for_sid(&current_windows_user_sid()?);
- return with_named_studio_runtime_launch_guard(&name, operation);
+ let _runtime_launch_guards = acquire_studio_runtime_launch_guard()?;
+ return operation();
}
#[cfg(unix)]
{
@@ -1688,10 +1725,7 @@ pub(crate) fn find_unsloth_binary_in_studio_dir(
}
pub fn find_unsloth_binary() -> Option<std::path::PathBuf> {
- let home = dirs::home_dir()?;
- let studio = home.join(".unsloth").join("studio");
-
- find_unsloth_binary_in_studio_dir(&studio)
+ find_unsloth_binary_in_studio_dir(&crate::studio_home::studio_root()?)
}
/// The Windows console script is a generated, unsigned PE wrapper. Application
@@ -2903,6 +2937,9 @@ fn apply_managed_cli_context_inner(
for name in skipped {
cmd.env_remove(name);
}
+ if let Some(root) = crate::studio_home::chosen_root() {
+ cmd.env(crate::studio_home::STUDIO_HOME_ENV, root);
+ }
cmd.env(DESKTOP_MANAGED_ENV, "1");
Ok(())
}
@@ -2923,6 +2960,9 @@ pub(crate) fn apply_managed_cli_context_tokio(
for name in &skipped {
cmd.env_remove(name);
}
+ if let Some(root) = crate::studio_home::chosen_root() {
+ cmd.env(crate::studio_home::STUDIO_HOME_ENV, root);
+ }
cmd.env(DESKTOP_MANAGED_ENV, "1");
Ok(())
}
@@ -3722,13 +3762,16 @@ pub fn start_backend(
#[cfg(target_os = "linux")]
scrub_appimage_python_env(&mut cmd);
- // Tauri uses the legacy root whatever the environment says; scrub so the
+ // Tauri uses its own root whatever the environment says; scrub so the
// spawned Python backend can't diverge. Off the shared list, so a name added
// there cannot be honoured by the backend and missed here.
// UNSLOTH_LLAMA_CPP_PATH is a pre-existing user-controlled override; keep it.
for name in MANAGED_CHILD_SCRUBBED_ENV {
cmd.env_remove(name);
}
+ if let Some(root) = crate::studio_home::chosen_root() {
+ cmd.env(crate::studio_home::STUDIO_HOME_ENV, root);
+ }
// read_output_stream decodes as UTF-8; without these, Python encodes its
// redirected streams with the locale code page and non-ASCII lands as U+FFFD.
diff --git a/studio/src-tauri/src/studio_home.rs b/studio/src-tauri/src/studio_home.rs
new file mode 100644
index 00000000000..e6961c6175c
--- /dev/null
+++ b/studio/src-tauri/src/studio_home.rs
@@ -0,0 +1,367 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+//! Where the desktop keeps its Studio install: `~/.unsloth/studio`, or the folder picked on the
+//! Windows first-run screen, recorded in `~/.unsloth/desktop_studio_home` and passed to managed
+//! children as UNSLOTH_STUDIO_HOME. No pointer file means the default root.
+
+use std::fs;
+use std::path::{Path, PathBuf};
+
+const POINTER_FILE: &str = "desktop_studio_home";
+
+pub(crate) const STUDIO_HOME_ENV: &str = "UNSLOTH_STUDIO_HOME";
+
+/// Marks UNSLOTH_STUDIO_HOME as the desktop's choice; install.ps1 --tauri refuses any other.
+pub(crate) const DESKTOP_CHOSEN_HOME_ENV: &str = "UNSLOTH_DESKTOP_CHOSEN_STUDIO_HOME";
+
+pub(crate) fn default_root_for_home(home: &Path) -> PathBuf {
+ home.join(".unsloth").join("studio")
+}
+
+fn pointer_path(home: &Path) -> PathBuf {
+ home.join(".unsloth").join(POINTER_FILE)
+}
+
+/// A missing, empty or relative pointer falls back to the default root.
+pub(crate) fn chosen_root_for_home(home: &Path) -> Option<PathBuf> {
+ let text = fs::read_to_string(pointer_path(home)).ok()?;
+ let root = PathBuf::from(text.trim());
+ if root.as_os_str().is_empty() || !root.is_absolute() {
+ return None;
+ }
+ if same_path(&root, &default_root_for_home(home)) {
+ return None;
+ }
+ Some(root)
+}
+
+pub(crate) fn studio_root_for_home(home: &Path) -> PathBuf {
+ chosen_root_for_home(home).unwrap_or_else(|| default_root_for_home(home))
+}
+
+pub(crate) fn studio_root() -> Option<PathBuf> {
+ dirs::home_dir().map(|home| studio_root_for_home(&home))
+}
+
+pub(crate) fn chosen_root() -> Option<PathBuf> {
+ dirs::home_dir().and_then(|home| chosen_root_for_home(&home))
+}
+
+fn same_path(left: &Path, right: &Path) -> bool {
+ let normalize = |path: &Path| {
+ let text = path.to_string_lossy().replace('/', "\\");
+ let text = text.trim_end_matches('\\').to_string();
+ if cfg!(windows) {
+ text.to_lowercase()
+ } else {
+ text
+ }
+ };
+ normalize(left) == normalize(right)
+}
+
+/// `<picked>\studio` for a folder already named Unsloth, else `<picked>\Unsloth\studio`.
+pub(crate) fn root_for_picked_folder(picked: &Path) -> PathBuf {
+ let named_unsloth = picked
+ .file_name()
+ .map(|name| {
+ let name = name.to_string_lossy();
+ name.eq_ignore_ascii_case("unsloth") || name.eq_ignore_ascii_case(".unsloth")
+ })
+ .unwrap_or(false);
+ if named_unsloth {
+ picked.join("studio")
+ } else {
+ picked.join("Unsloth").join("studio")
+ }
+}
+
+/// UNC paths are refused: cmd.exe and the installer's child steps cannot run from one.
+pub(crate) fn validate_picked_folder(picked: &Path) -> Result<(), String> {
+ if !picked.is_absolute() {
+ return Err("Choose a folder on a local drive.".to_string());
+ }
+ let text = picked.to_string_lossy();
+ if text.starts_with("\\\\") && !text.starts_with("\\\\?\\") || text.starts_with("\\\\?\\UNC\\")
+ {
+ return Err(
+ "Network folders are not supported. Choose a folder on a local drive.".to_string(),
+ );
+ }
+ // create_new: never truncates or deletes an existing entry (or link) at the probe name.
+ let probe = picked.join(format!(".unsloth-write-probe-{}", std::process::id()));
+ fs::OpenOptions::new()
+ .write(true)
+ .create_new(true)
+ .open(&probe)
+ .map_err(|_| "Unsloth cannot write to this folder. Choose another folder.".to_string())?;
+ let _ = fs::remove_file(&probe);
+ Ok(())
+}
+
+/// A root that already holds files must be an Unsloth install: uninstall.ps1 removes an owned
+/// root whole, so installing into someone else's folder would take their files with it.
+pub(crate) fn validate_root(root: &Path) -> Result<(), String> {
+ let Ok(mut entries) = fs::read_dir(root) else {
+ return Ok(());
+ };
+ if entries.next().is_none()
+ || root.join(".unsloth-studio-owned").is_file()
+ || root.join("share").join("studio.conf").is_file()
+ || root.join("unsloth_studio").join(".unsloth-studio-owned").is_file()
+ {
+ return Ok(());
+ }
+ Err(format!(
+ "{} already contains other files. Choose another folder.",
+ root.display()
+ ))
+}
+
+/// Written to a temporary file and renamed; the default root removes the pointer instead.
+pub(crate) fn write_choice_for_home(home: &Path, root: &Path) -> Result<(), String> {
+ let pointer = pointer_path(home);
+ if same_path(root, &default_root_for_home(home)) {
+ return match fs::remove_file(&pointer) {
+ Ok(()) => Ok(()),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
+ Err(error) => Err(format!("Could not reset the install location: {error}")),
+ };
+ }
+ let parent = pointer
+ .parent()
+ .ok_or("Could not resolve the Unsloth folder.")?;
+ fs::create_dir_all(parent)
+ .map_err(|error| format!("Could not save the install location: {error}"))?;
+ let temp = parent.join(format!("{POINTER_FILE}.tmp-{}", std::process::id()));
+ fs::write(&temp, root.to_string_lossy().as_bytes())
+ .and_then(|()| fs::rename(&temp, &pointer))
+ .map_err(|error| {
+ let _ = fs::remove_file(&temp);
+ format!("Could not save the install location: {error}")
+ })
+}
+
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct StudioInstallLocation {
+ pub path: String,
+ pub is_default: bool,
+ pub can_change: bool,
+}
+
+fn location_for_home(home: &Path) -> StudioInstallLocation {
+ let chosen = chosen_root_for_home(home);
+ StudioInstallLocation {
+ is_default: chosen.is_none(),
+ path: chosen
+ .unwrap_or_else(|| default_root_for_home(home))
+ .to_string_lossy()
+ .into_owned(),
+ can_change: cfg!(windows),
+ }
+}
+
+fn home_dir() -> Result<PathBuf, String> {
+ dirs::home_dir().ok_or_else(|| "Could not determine home directory".to_string())
+}
+
+fn ensure_changeable(install: &crate::install::InstallState) -> Result<(), String> {
+ if !cfg!(windows) {
+ return Err("Choosing an install location is only available on Windows.".to_string());
+ }
+ if crate::install::is_install_running(install) {
+ return Err("Installation is already running.".to_string());
+ }
+ if crate::process::find_unsloth_binary().is_some() {
+ return Err("Unsloth is already installed in this location.".to_string());
+ }
+ Ok(())
+}
+
+/// Under the install lock: an install that already has the old root never sees it move.
+fn commit_choice(
+ install: &crate::install::InstallState,
+ home: &Path,
+ root: &Path,
+) -> Result<(), String> {
+ crate::install::while_install_idle(install, || {
+ if crate::process::find_unsloth_binary().is_some() {
+ return Err("Unsloth is already installed in this location.".to_string());
+ }
+ write_choice_for_home(home, root)
+ })
+}
+
+#[tauri::command]
+pub fn studio_install_location() -> Result<StudioInstallLocation, String> {
+ Ok(location_for_home(&home_dir()?))
+}
+
+/// The webview never names a path: the folder comes from the system dialog.
+#[tauri::command]
+pub async fn choose_studio_install_location(
+ webview: tauri::Webview,
+ app: tauri::AppHandle,
+ install: tauri::State<'_, crate::install::InstallState>,
+) -> Result<Option<StudioInstallLocation>, String> {
+ use tauri_plugin_dialog::DialogExt;
+
+ crate::native_intents::ensure_main_window(&webview)?;
+ ensure_changeable(install.inner())?;
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ app.dialog()
+ .file()
+ .set_title("Choose where to install Unsloth")
+ .pick_folder(move |path| {
+ let _ = tx.send(path);
+ });
+ let Some(picked) = rx.await.map_err(|_| "Dialog closed".to_string())? else {
+ return Ok(None);
+ };
+ let picked = picked
+ .into_path()
+ .map_err(|_| "Choose a folder on a local drive.".to_string())?;
+ validate_picked_folder(&picked)?;
+ let root = root_for_picked_folder(&picked);
+ validate_root(&root)?;
+ let home = home_dir()?;
+ commit_choice(install.inner(), &home, &root)?;
+ Ok(Some(location_for_home(&home)))
+}
+
+#[tauri::command]
+pub fn reset_studio_install_location(
+ webview: tauri::Webview,
+ install: tauri::State<'_, crate::install::InstallState>,
+) -> Result<StudioInstallLocation, String> {
+ crate::native_intents::ensure_main_window(&webview)?;
+ ensure_changeable(install.inner())?;
+ let home = home_dir()?;
+ commit_choice(install.inner(), &home, &default_root_for_home(&home))?;
+ Ok(location_for_home(&home))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn temp_home(name: &str) -> PathBuf {
+ let home = std::env::temp_dir().join(format!(
+ "unsloth-studio-home-{name}-{}-{}",
+ std::process::id(),
+ std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .unwrap()
+ .as_nanos()
+ ));
+ fs::create_dir_all(&home).unwrap();
+ home
+ }
+
+ #[test]
+ fn no_pointer_keeps_the_default_root() {
+ let home = temp_home("default");
+ assert_eq!(
+ studio_root_for_home(&home),
+ home.join(".unsloth").join("studio")
+ );
+ assert_eq!(chosen_root_for_home(&home), None);
+ let location = location_for_home(&home);
+ assert!(location.is_default);
+ fs::remove_dir_all(&home).unwrap();
+ }
+
+ #[test]
+ fn a_written_choice_is_read_back_and_reset_removes_it() {
+ let home = temp_home("choice");
+ let custom = home.join("other-drive").join("Unsloth").join("studio");
+ write_choice_for_home(&home, &custom).unwrap();
+ assert_eq!(studio_root_for_home(&home), custom);
+ assert_eq!(chosen_root_for_home(&home), Some(custom.clone()));
+ write_choice_for_home(&home, &custom).unwrap();
+ assert_eq!(chosen_root_for_home(&home), Some(custom));
+
+ write_choice_for_home(&home, &default_root_for_home(&home)).unwrap();
+ assert!(!pointer_path(&home).exists());
+ assert_eq!(chosen_root_for_home(&home), None);
+ write_choice_for_home(&home, &default_root_for_home(&home)).unwrap();
+ fs::remove_dir_all(&home).unwrap();
+ }
+
+ #[test]
+ fn damaged_pointers_fall_back_to_the_default_root() {
+ let home = temp_home("damaged");
+ fs::create_dir_all(home.join(".unsloth")).unwrap();
+ for text in ["", " \n", "relative\\studio"] {
+ fs::write(pointer_path(&home), text).unwrap();
+ assert_eq!(chosen_root_for_home(&home), None, "{text:?}");
+ assert_eq!(studio_root_for_home(&home), default_root_for_home(&home));
+ }
+ let default_text = default_root_for_home(&home).to_string_lossy().into_owned();
+ fs::write(pointer_path(&home), format!("{default_text}\n")).unwrap();
+ assert_eq!(chosen_root_for_home(&home), None);
+ fs::remove_dir_all(&home).unwrap();
+ }
+
+ #[test]
+ fn picked_folders_map_to_a_studio_folder_inside_them() {
+ let base = PathBuf::from(if cfg!(windows) {
+ "D:\\Apps"
+ } else {
+ "/mnt/d/Apps"
+ });
+ assert_eq!(
+ root_for_picked_folder(&base),
+ base.join("Unsloth").join("studio")
+ );
+ assert_eq!(
+ root_for_picked_folder(&base.join("Unsloth")),
+ base.join("Unsloth").join("studio")
+ );
+ assert_eq!(
+ root_for_picked_folder(&base.join("unsloth")),
+ base.join("unsloth").join("studio")
+ );
+ }
+
+ #[test]
+ fn unwritable_or_relative_folders_are_refused() {
+ assert!(validate_picked_folder(Path::new("relative")).is_err());
+ let home = temp_home("writable");
+ assert!(validate_picked_folder(&home).is_ok());
+ assert!(validate_picked_folder(&home.join("missing")).is_err());
+ fs::remove_dir_all(&home).unwrap();
+ }
+
+ #[test]
+ fn a_root_holding_foreign_files_is_refused() {
+ let home = temp_home("root");
+ let root = home.join("Unsloth").join("studio");
+ assert!(validate_root(&root).is_ok());
+ fs::create_dir_all(&root).unwrap();
+ assert!(validate_root(&root).is_ok());
+ fs::write(root.join("notes.txt"), b"mine").unwrap();
+ assert!(validate_root(&root).is_err());
+ fs::write(root.join(".unsloth-studio-owned"), b"").unwrap();
+ assert!(validate_root(&root).is_ok());
+ fs::remove_dir_all(&home).unwrap();
+ }
+
+ #[test]
+ fn the_write_probe_never_touches_an_existing_file() {
+ let home = temp_home("probe");
+ let existing = home.join(format!(".unsloth-write-probe-{}", std::process::id()));
+ fs::write(&existing, b"keep").unwrap();
+ assert!(validate_picked_folder(&home).is_err());
+ assert_eq!(fs::read(&existing).unwrap(), b"keep");
+ fs::remove_dir_all(&home).unwrap();
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn network_folders_are_refused() {
+ assert!(validate_picked_folder(Path::new(r"\\server\share\models")).is_err());
+ assert!(validate_picked_folder(Path::new(r"\\?\UNC\server\share")).is_err());
+ }
+}
diff --git a/studio/src-tauri/src/update.rs b/studio/src-tauri/src/update.rs
index 3a315d0f304..56ce57c530f 100644
--- a/studio/src-tauri/src/update.rs
+++ b/studio/src-tauri/src/update.rs
@@ -68,6 +68,9 @@ fn configure_tauri_update_environment(cmd: &mut Command) {
// The desktop owns its shortcuts and frontend bundle; this update needs only backend deps.
cmd.env_remove("UNSLOTH_STUDIO_HOME");
cmd.env_remove("STUDIO_HOME");
+ if let Some(root) = crate::studio_home::chosen_root() {
+ cmd.env(crate::studio_home::STUDIO_HOME_ENV, root);
+ }
cmd.env("UNSLOTH_TAURI_UPDATE", "1");
cmd.env("UNSLOTH_PROGRESS_PERCENT_STEP", "5");
cmd.env("SKIP_STUDIO_FRONTEND", "1");
diff --git a/tests/python/test_desktop_chosen_studio_home.py b/tests/python/test_desktop_chosen_studio_home.py
new file mode 100644
index 00000000000..6c3b78ef0e0
--- /dev/null
+++ b/tests/python/test_desktop_chosen_studio_home.py
@@ -0,0 +1,159 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""install.ps1 under --tauri: the desktop's chosen install folder is accepted, an inherited
+UNSLOTH_STUDIO_HOME / STUDIO_HOME is still refused, and the Rust side passes the folder."""
+
+from __future__ import annotations
+
+import os
+import shutil
+import tempfile
+from pathlib import Path
+
+import pytest
+
+from unsloth_pwsh_runner import run_pwsh
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+INSTALL_PS1 = REPO_ROOT / "install.ps1"
+TAURI_SRC = REPO_ROOT / "studio" / "src-tauri" / "src"
+PWSH = shutil.which("pwsh") or shutil.which("powershell")
+
+
+def _validation_block() -> str:
+ source = INSTALL_PS1.read_text(encoding = "utf-8")
+ start = source.index(" # Custom Unsloth roots are not supported with --tauri")
+ end = source.index(" # LOCALAPPDATA may be unset", start)
+ return source[start:end]
+
+
+def _run_validation(tmp_path: Path, override_var: str, chosen_flag: str | None) -> str:
+ # Path helpers are stubbed to "different directory", so only the chosen-root gate decides.
+ script = f"""
+$ErrorActionPreference = "Stop"
+function Write-StudioLine {{ param([string]$Text, $ForegroundColor) }}
+function Restore-StudioTempEnvironment {{ }}
+function Get-StudioFinalPath {{ param([string]$Path) return $Path }}
+function Test-StudioSameDirectoryByProbe {{ param($Left, $Right) return $false }}
+function Split-StudioExistingAncestor {{ param([string]$Path) return $null }}
+$TauriMode = $true
+$envOverride = $env:TEST_CHOSEN_ROOT
+$envOverrideVar = "{override_var}"
+$tauriProfile = $env:TEST_TAURI_PROFILE
+try {{
+{_validation_block()}
+ Write-Output "accepted"
+}} catch {{
+ Write-Output "refused: $($_.Exception.Message)"
+}}
+"""
+ env = os.environ.copy()
+ env.pop("UNSLOTH_DESKTOP_CHOSEN_STUDIO_HOME", None)
+ env["TEST_CHOSEN_ROOT"] = str(tmp_path / "Apps" / "Unsloth" / "studio")
+ env["TEST_TAURI_PROFILE"] = str(tmp_path / "profile")
+ if chosen_flag is not None:
+ env["UNSLOTH_DESKTOP_CHOSEN_STUDIO_HOME"] = chosen_flag
+ handle, name = tempfile.mkstemp(suffix = ".ps1")
+ os.close(handle)
+ try:
+ Path(name).write_text(script, encoding = "utf-8-sig")
+ result = run_pwsh(
+ [PWSH, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", name],
+ check = False,
+ capture_output = True,
+ text = True,
+ env = env,
+ verdict = "accepted",
+ )
+ finally:
+ os.unlink(name)
+ assert result.returncode == 0, result.stderr
+ return result.stdout.strip().splitlines()[-1]
+
+
[email protected](PWSH is None, reason = "PowerShell is required")
+def test_desktop_chosen_root_is_accepted_under_tauri(tmp_path: Path):
+ assert _run_validation(tmp_path, "UNSLOTH_STUDIO_HOME", "1") == "accepted"
+
+
[email protected](PWSH is None, reason = "PowerShell is required")
+ "override_var, chosen_flag",
+ [
+ ("UNSLOTH_STUDIO_HOME", None),
+ ("UNSLOTH_STUDIO_HOME", "0"),
+ ("STUDIO_HOME", "1"),
+ ],
+)
+def test_inherited_custom_root_is_still_refused_under_tauri(
+ tmp_path: Path, override_var: str, chosen_flag: str | None
+):
+ outcome = _run_validation(tmp_path, override_var, chosen_flag)
+ assert outcome == f"refused: {override_var} is not supported with --tauri."
+
+
+def test_desktop_passes_the_chosen_root_only_to_the_installer_with_its_flag():
+ install = (TAURI_SRC / "install.rs").read_text(encoding = "utf-8")
+ scrub = install.index("for name in crate::process::MANAGED_CHILD_SCRUBBED_ENV")
+ chosen = install.index("crate::studio_home::chosen_root()", scrub)
+ block = install[chosen : install.index("}", install.index("UNSLOTH_ISOLATE_UV_CACHE", chosen))]
+ assert "STUDIO_HOME_ENV" in block
+ assert "DESKTOP_CHOSEN_HOME_ENV" in block
+ studio_home = (TAURI_SRC / "studio_home.rs").read_text(encoding = "utf-8")
+ assert '"UNSLOTH_DESKTOP_CHOSEN_STUDIO_HOME"' in studio_home
+ assert "$env:UNSLOTH_DESKTOP_CHOSEN_STUDIO_HOME" in _validation_block()
+
+
+def _custom_uninstall_roots(tmp_path: Path, pointer: str | None) -> list[str]:
+ # Function definitions are lifted out of uninstall.ps1 by AST; its body stops processes and
+ # edits the registry, so it is never run here.
+ profile = tmp_path / "profile"
+ (profile / ".unsloth").mkdir(parents = True)
+ if pointer is not None:
+ (profile / ".unsloth" / "desktop_studio_home").write_text(pointer, encoding = "utf-8")
+ script = """
+$ErrorActionPreference = "Stop"
+$tokens = $null; $errors = $null
+$ast = [System.Management.Automation.Language.Parser]::ParseFile($env:TEST_UNINSTALL_PS1, [ref]$tokens, [ref]$errors)
+foreach ($fn in $ast.FindAll({ param($n) $n -is [System.Management.Automation.Language.FunctionDefinitionAst] }, $true)) {
+ . ([scriptblock]::Create($fn.Extent.Text))
+}
+foreach ($root in @(_CustomStudioRoots)) { Write-Output "ROOT=$root" }
+Write-Output "done"
+"""
+ env = os.environ.copy()
+ for name in ("UNSLOTH_STUDIO_HOME", "STUDIO_HOME", "UNSLOTH_HOME"):
+ env.pop(name, None)
+ env["USERPROFILE"] = str(profile)
+ env["LOCALAPPDATA"] = str(tmp_path / "localappdata")
+ env["TEST_UNINSTALL_PS1"] = str(REPO_ROOT / "scripts" / "uninstall.ps1")
+ handle, name = tempfile.mkstemp(suffix = ".ps1")
+ os.close(handle)
+ try:
+ Path(name).write_text(script, encoding = "utf-8-sig")
+ result = run_pwsh(
+ [PWSH, "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", name],
+ check = False,
+ capture_output = True,
+ text = True,
+ env = env,
+ verdict = "done",
+ )
+ finally:
+ os.unlink(name)
+ assert result.returncode == 0 and "done" in result.stdout, result.stderr
+ return [line[5:] for line in result.stdout.splitlines() if line.startswith("ROOT=")]
+
+
[email protected](PWSH is None, reason = "PowerShell is required")
+def test_uninstaller_finds_the_folder_desktop_installed_into(tmp_path: Path):
+ chosen = tmp_path / "D" / "Apps" / "Unsloth" / "studio"
+ chosen.mkdir(parents = True)
+ roots = _custom_uninstall_roots(tmp_path, f"{chosen}\n")
+ assert [Path(root) for root in roots] == [chosen]
+
+
[email protected](PWSH is None, reason = "PowerShell is required")
+def test_uninstaller_without_a_desktop_choice_finds_no_custom_root(tmp_path: Path):
+ assert _custom_uninstall_roots(tmp_path, None) == []