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.

Desktop: explain Windows Long Paths before its UAC prompt (#13523)

Daniel Han9f5b133254e7
diff --git a/studio/frontend/scripts/check-bundle-budget.ts b/studio/frontend/scripts/check-bundle-budget.ts
index 4bd03b237a7..832185588d5 100644
--- a/studio/frontend/scripts/check-bundle-budget.ts
+++ b/studio/frontend/scripts/check-bundle-budget.ts
@@ -150,8 +150,12 @@ export const BUDGET = {
// Opening the OS folder dialog for model folders on Desktop (#13843) adds 235 B raw / 336 B transfer
// (6,777,794 -> 6,778,029 B raw, 2,037,725 -> 2,038,061 B transfer against 199987c63, one machine and build,
// Node 24, chunk count unchanged at 95). Raised by that growth.
- transferBytes: 2_037_157,
- rawBytes: 6_775_132,
+ // The Windows Long Paths explainer on the first-run startup screen (#13523) adds 1,816 B raw / 519 B
+ // transfer (6,778,788 -> 6,780,604 B raw, 2,038,337 -> 2,038,856 B transfer against 62e063618, one machine
+ // and build, Node 24, chunk count unchanged at 95). Main already measured 3,656 B raw / 1,180 B transfer over
+ // the previous limits there, so they are set to the measured build.
+ transferBytes: 2_038_856,
+ rawBytes: 6_780_604,
};
// 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/startup-screen.tsx b/studio/frontend/src/components/tauri/startup-screen.tsx
index 6c6c6649472..515f3955471 100644
--- a/studio/frontend/src/components/tauri/startup-screen.tsx
+++ b/studio/frontend/src/components/tauri/startup-screen.tsx
@@ -15,9 +15,13 @@ import { Spinner } from "@/components/ui/spinner";
import type { BackendStatus } from "@/hooks/use-tauri-backend";
import { useDocumentFlag } from "@/lib/document-flag";
import type { CopySupportDiagnosticsResult } from "@/lib/tauri-diagnostics";
+import {
+ enableWindowsLongPaths,
+ windowsLongPathsNeedPrompt,
+} from "@/lib/windows-long-paths";
import { AnimatePresence, motion } from "motion/react";
-import { type ReactNode, useEffect, useState } from "react";
+import { type ReactNode, useEffect, useRef, useState } from "react";
interface StartupScreenProps {
status: BackendStatus;
@@ -28,7 +32,7 @@ interface StartupScreenProps {
progressDetail: string | null;
startupMessage: StartupMessage;
elevationPackages: string[];
- onInstall: () => void;
+ onInstall: (options?: InstallOptions) => void;
onRetry: () => void;
onRetryInstall: () => void;
onApproveElevation: () => void;
@@ -79,8 +83,63 @@ function CheckingContent() {
);
}
-function NotInstalledContent({ onInstall }: { onInstall: () => void }) {
- const [starting, setStarting] = useState(false);
+type InstallOptions = { skipLongPaths?: boolean };
+
+function NotInstalledContent({
+ onInstall,
+}: {
+ onInstall: (options?: InstallOptions) => void;
+}) {
+ const [phase, setPhase] = useState<
+ "idle" | "checking" | "explain" | "elevating"
+ >("idle");
+
+ // Synchronous: a double click lands before the re-render that disables the buttons.
+ const busy = useRef(false);
+
+ async function getStarted() {
+ if (busy.current) {
+ return;
+ }
+ busy.current = true;
+ setPhase("checking");
+ if (await windowsLongPathsNeedPrompt()) {
+ busy.current = false;
+ setPhase("explain");
+ } else {
+ onInstall();
+ }
+ }
+
+ async function allowLongPaths() {
+ if (busy.current) {
+ return;
+ }
+ busy.current = true;
+ setPhase("elevating");
+ const outcome = await enableWindowsLongPaths();
+ // "failed" leaves setup.ps1's own UAC as the fallback.
+ onInstall({ skipLongPaths: outcome === "declined" });
+ }
+
+ function skipLongPaths() {
+ if (busy.current) {
+ return;
+ }
+ busy.current = true;
+ onInstall({ skipLongPaths: true });
+ }
+
+ if (phase === "explain" || phase === "elevating") {
+ return (
+ <LongPathsExplainer
+ waiting={phase === "elevating"}
+ onContinue={allowLongPaths}
+ onSkip={skipLongPaths}
+ />
+ );
+ }
+
return (
<div className="flex h-full flex-col items-center">
<div className="flex flex-1 flex-col items-center justify-center">
@@ -95,19 +154,62 @@ function NotInstalledContent({ onInstall }: { onInstall: () => void }) {
</p>
<Button
size="hero"
- onClick={() => {
- setStarting(true);
- onInstall();
- }}
+ onClick={getStarted}
+ disabled={phase === "checking"}
>
Get Started
</Button>
- <InstallLocation disabled={starting} />
+ <InstallLocation disabled={phase !== "idle"} />
</div>
</div>
);
}
+function LongPathsExplainer({
+ waiting,
+ onContinue,
+ onSkip,
+}: {
+ waiting: boolean;
+ onContinue: () => void;
+ onSkip: () => void;
+}) {
+ return (
+ <>
+ <Logo />
+ <div className="mt-8 flex max-w-md flex-col items-center gap-2">
+ <p className="text-sm font-medium text-foreground">
+ Windows will ask for permission
+ </p>
+ <p className="text-xs text-muted-foreground">
+ Approve{" "}
+ <span className="font-medium text-foreground">
+ Registry Console Tool
+ </span>{" "}
+ once to turn on long file paths for compiled kernels.
+ </p>
+ {waiting ? (
+ <div className="mt-4 flex items-center gap-2">
+ <Spinner className="size-4 text-primary" />
+ <p className="text-xs text-muted-foreground" aria-live="polite">
+ Waiting for Windows permission...
+ </p>
+ </div>
+ ) : (
+ <div className="mt-4 flex gap-3">
+ <Button variant="muted" size="hero" onClick={onSkip}>
+ Skip
+ </Button>
+ <Button size="hero" onClick={onContinue}>
+ Continue
+ </Button>
+ </div>
+ )}
+ </div>
+ </>
+ );
+}
+
function useRotatingMessageIndex(): number {
const [messageIndex, setMessageIndex] = useState(0);
diff --git a/studio/frontend/src/hooks/use-tauri-backend.ts b/studio/frontend/src/hooks/use-tauri-backend.ts
index 0ea976897e4..8ebadec21cd 100644
--- a/studio/frontend/src/hooks/use-tauri-backend.ts
+++ b/studio/frontend/src/hooks/use-tauri-backend.ts
@@ -570,7 +570,9 @@ export function useTauriBackend() {
setBackendStatus("stopped");
}
- async function startInstall() {
+ // Strict check: onClick passes a click event here.
+ async function startInstall(options?: { skipLongPaths?: boolean }) {
+ const skipLongPaths = options?.skipLongPaths === true;
elevationResumeRef.current = null;
setCurrentStepIndex(-1);
setProgressDetail(null);
@@ -580,7 +582,7 @@ export function useTauriBackend() {
clearBackendError();
const { invoke } = await import("@tauri-apps/api/core");
try {
- await invoke("start_install");
+ await invoke("start_install", { skipLongPaths });
// Install done: start the managed backend we just installed. Don't run the general preflight
// here, it can attach to an unrelated running CLI/backend before launching ours. The
// install-complete listener does NOT call startServer() to avoid a double-start race.
diff --git a/studio/frontend/src/lib/windows-long-paths.ts b/studio/frontend/src/lib/windows-long-paths.ts
new file mode 100644
index 00000000000..2551ad9ddc6
--- /dev/null
+++ b/studio/frontend/src/lib/windows-long-paths.ts
@@ -0,0 +1,25 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+export type LongPathsStatus = "enabled" | "disabled" | "unsupported";
+export type EnableLongPathsOutcome = "enabled" | "declined" | "failed";
+
+// Only a definite "disabled" prompts; an error installs as before.
+export async function windowsLongPathsNeedPrompt(): Promise<boolean> {
+ try {
+ const { invoke } = await import("@tauri-apps/api/core");
+ const status = await invoke<LongPathsStatus>("windows_long_paths_status");
+ return status === "disabled";
+ } catch {
+ return false;
+ }
+}
+
+export async function enableWindowsLongPaths(): Promise<EnableLongPathsOutcome> {
+ try {
+ const { invoke } = await import("@tauri-apps/api/core");
+ return await invoke<EnableLongPathsOutcome>("enable_windows_long_paths");
+ } catch {
+ return "failed";
+ }
+}
diff --git a/studio/frontend/tests/install-disk-full-flag.test.ts b/studio/frontend/tests/install-disk-full-flag.test.ts
index bd19b7b0514..1caad8c46d9 100644
--- a/studio/frontend/tests/install-disk-full-flag.test.ts
+++ b/studio/frontend/tests/install-disk-full-flag.test.ts
@@ -28,7 +28,7 @@ const errorBody = lift(
"setBackendError",
);
const installBody = lift(
- / async function startInstall\(\) \{[\s\S]*?\n \}\n/,
+ / async function startInstall\([^)]*\) \{[\s\S]*?\n \}\n/,
"startInstall",
);
const listenerBody = lift(
@@ -80,7 +80,9 @@ async function failInstall(order: "event-first" | "reject-first") {
const source = `
${statusBody.replace(": BackendStatus", "")}
${errorBody.replace(/: (string|BackendStatus)/g, "")}
-${installBody.replace('await import("@tauri-apps/api/core")', "await importTauriCore()")}
+${installBody
+ .replace(/startInstall\([^)]*\)/, "startInstall(options)")
+ .replace('await import("@tauri-apps/api/core")', "await importTauriCore()")}
return { startInstall, onInstallFailed: (e) => {${listenerBody}} };
`;
const keys = Object.keys(scope);
@@ -108,6 +110,50 @@ ${installBody.replace('await import("@tauri-apps/api/core")', "await importTauri
return state;
}
+async function installArgs(options: unknown): Promise<unknown> {
+ let args: unknown;
+ const noop = () => {};
+ const scope: Record<string, unknown> = {
+ elevationResumeRef: { current: null },
+ seenStepsRef: { current: new Set() },
+ statusRef: { current: "not-installed" },
+ setCurrentStepIndex: noop,
+ setProgressDetail: noop,
+ setBackendStatus: noop,
+ setBackendError: noop,
+ setLogs: noop,
+ clearBackendError: noop,
+ startServer: () => Promise.resolve(),
+ importTauriCore: () =>
+ Promise.resolve({
+ invoke: (_cmd: string, a: unknown) => {
+ args = a;
+ return Promise.resolve();
+ },
+ }),
+ };
+ const source = `
+${installBody
+ .replace(/startInstall\([^)]*\)/, "startInstall(options)")
+ .replace('await import("@tauri-apps/api/core")', "await importTauriCore()")}
+ return startInstall;
+ `;
+ const keys = Object.keys(scope);
+ const startInstall = new Function(...keys, source)(
+ ...keys.map((key) => scope[key]),
+ ) as (options: unknown) => Promise<void>;
+ await startInstall(options);
+ return args;
+}
+
+test("a skipped Long Paths explainer reaches start_install", async () => {
+ assert.deepEqual(await installArgs({ skipLongPaths: true }), { skipLongPaths: true });
+ assert.deepEqual(await installArgs(undefined), { skipLongPaths: false });
+ assert.deepEqual(await installArgs({ type: "click", skipLongPaths: "x" }), {
+ skipLongPaths: false,
+ });
+});
+
for (const order of ["event-first", "reject-first"] as const) {
test(`a disk-full install keeps its dialog (${order})`, async () => {
const state = await failInstall(order);
diff --git a/studio/setup.ps1 b/studio/setup.ps1
index 11c87852a99..86afbd513a8 100644
--- a/studio/setup.ps1
+++ b/studio/setup.ps1
@@ -5202,12 +5202,19 @@ if ($LongPathsEnabled) {
step "long paths" "disabled; unchanged during staging" "Yellow"
} elseif ($env:UNSLOTH_SETUP_RERUN -eq '1') {
step "long paths" "disabled; already asked earlier in this update" "Yellow"
+} elseif ($env:UNSLOTH_SKIP_LONG_PATHS -eq '1') {
+ # Declined on the desktop app's explainer: no second UAC.
+ step "long paths" "disabled; skipped at your request" "Yellow"
+ substep "torch.compile / Triton may fail on very long paths. To enable later, in an Admin terminal:" "Yellow"
+ substep 'reg add "HKLM\SYSTEM\CurrentControlSet\Control\FileSystem" /v LongPathsEnabled /t REG_DWORD /d 1 /f' "Yellow"
} else {
Write-StudioLine "Windows Long Paths not enabled (required for Triton compilation and deep dependency paths)." -ForegroundColor Yellow
Write-StudioLine " This turns on LongPathsEnabled under HKLM, a machine-wide setting, so Windows asks for admin approval." -ForegroundColor Yellow
+ Write-StudioLine " Windows will show a 'Registry Console Tool' prompt (reg.exe, verified publisher Microsoft Windows)." -ForegroundColor Yellow
Write-StudioLine " Requesting admin access to fix..." -ForegroundColor Yellow
try {
- $proc = Start-Process -FilePath "reg.exe" `
+ # The system directory itself, not a PATH lookup: this is the binary the prompt names.
+ $proc = Start-Process -FilePath "$([Environment]::SystemDirectory)\reg.exe" `
-ArgumentList 'add "HKLM\SYSTEM\CurrentControlSet\Control\FileSystem" /v LongPathsEnabled /t REG_DWORD /d 1 /f' `
-Verb RunAs -Wait -PassThru -ErrorAction Stop
if ($proc.ExitCode -eq 0) {
diff --git a/studio/src-tauri/Cargo.toml b/studio/src-tauri/Cargo.toml
index 093321ce8ae..3ae00cd06a4 100644
--- a/studio/src-tauri/Cargo.toml
+++ b/studio/src-tauri/Cargo.toml
@@ -85,7 +85,7 @@ webview2-com = "0.39.1"
winreg = "0.55"
windows = { version = "0.62.2", features = ["Win32_System_Threading"] }
windows-core = "0.62.2"
-windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse"] }
+windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Globalization", "Win32_Security", "Win32_Storage_FileSystem", "Win32_System_Com", "Win32_System_Console", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Threading", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_Shell"] }
[build-dependencies]
tauri-build = { version = "~2.7.0", features = [] }
diff --git a/studio/src-tauri/src/commands.rs b/studio/src-tauri/src/commands.rs
index 10fac51e1e6..35ea362a800 100644
--- a/studio/src-tauri/src/commands.rs
+++ b/studio/src-tauri/src/commands.rs
@@ -889,6 +889,7 @@ pub async fn start_install(
backend_state: tauri::State<'_, BackendState>,
update_state: tauri::State<'_, update::UpdateState>,
diagnostics: tauri::State<'_, DiagnosticsState>,
+ skip_long_paths: Option<bool>,
) -> Result<(), String> {
if has_owned_backend(&backend_state)? {
return Err(
@@ -904,9 +905,12 @@ pub async fn start_install(
let state = state.inner().clone();
let diagnostics_state = diagnostics.inner().clone();
- tokio::task::spawn_blocking(move || install::run_install(app, state, diagnostics_state))
- .await
- .map_err(|e| format!("Install task panicked: {e}"))?
+ let skip_long_paths = skip_long_paths.unwrap_or(false);
+ tokio::task::spawn_blocking(move || {
+ install::run_install(app, state, diagnostics_state, skip_long_paths)
+ })
+ .await
+ .map_err(|e| format!("Install task panicked: {e}"))?
}
/// Record that the user canceled a pending system-package elevation flow.
diff --git a/studio/src-tauri/src/install.rs b/studio/src-tauri/src/install.rs
index 33af79cf5bb..a17b3d644f8 100644
--- a/studio/src-tauri/src/install.rs
+++ b/studio/src-tauri/src/install.rs
@@ -952,8 +952,13 @@ pub fn run_install(
app: AppHandle,
state: InstallState,
diagnostics: DiagnosticsState,
+ skip_long_paths: bool,
) -> Result<(), String> {
- run_install_with_event_mode(app, state, diagnostics, InstallEventMode::Full, None, false)
+ let env = InstallerEnv {
+ upgrade_torch: false,
+ skip_long_paths,
+ };
+ run_install_with_event_mode(app, state, diagnostics, InstallEventMode::Full, None, env)
}
/// `upgrade_torch` is Settings' manual "Repair installation": the user asked for a reinstall,
@@ -972,18 +977,31 @@ pub(crate) fn run_install_for_repair(
diagnostics,
InstallEventMode::Repair,
Some(repair_group_id),
- upgrade_torch,
+ InstallerEnv {
+ upgrade_torch,
+ skip_long_paths: false,
+ },
)
}
+#[derive(Debug, Clone, Copy, Default)]
+struct InstallerEnv {
+ upgrade_torch: bool,
+ skip_long_paths: bool,
+}
+
/// Extra environment for the installer child. UNSLOTH_TORCH_UPGRADE=1 is install.sh's and
/// install.ps1's opt-out from keeping an existing install's torch release.
-fn installer_env(upgrade_torch: bool) -> Vec<(&'static str, &'static str)> {
- if upgrade_torch {
- vec![("UNSLOTH_TORCH_UPGRADE", "1")]
- } else {
- Vec::new()
+/// UNSLOTH_SKIP_LONG_PATHS=1: Long Paths declined on the startup screen, so setup.ps1 skips its UAC.
+fn installer_env(env: InstallerEnv) -> Vec<(&'static str, &'static str)> {
+ let mut vars = Vec::new();
+ if env.upgrade_torch {
+ vars.push(("UNSLOTH_TORCH_UPGRADE", "1"));
}
+ if env.skip_long_paths {
+ vars.push(("UNSLOTH_SKIP_LONG_PATHS", "1"));
+ }
+ vars
}
fn run_install_with_event_mode(
@@ -992,7 +1010,7 @@ fn run_install_with_event_mode(
diagnostics: DiagnosticsState,
event_mode: InstallEventMode,
repair_group_id: Option<String>,
- upgrade_torch: bool,
+ env: InstallerEnv,
) -> Result<(), String> {
let attempt = match repair_group_id.as_deref() {
Some(group_id) => diagnostics::begin_repair_child(&diagnostics, group_id, "install"),
@@ -1037,7 +1055,7 @@ fn run_install_with_event_mode(
&format!("Using script: {}", script.display()),
);
- let extra_env = installer_env(upgrade_torch);
+ let extra_env = installer_env(env);
let (stdout, stderr) = match spawn_script(&script, &args, &state, &extra_env) {
Ok(handles) => handles,
Err(msg) => {
@@ -1665,8 +1683,29 @@ mod tests {
#[test]
fn only_a_manual_repair_asks_the_installer_for_a_newer_torch() {
- assert_eq!(installer_env(true), vec![("UNSLOTH_TORCH_UPGRADE", "1")]);
- assert!(installer_env(false).is_empty());
+ let upgrade = InstallerEnv {
+ upgrade_torch: true,
+ ..Default::default()
+ };
+ assert_eq!(installer_env(upgrade), vec![("UNSLOTH_TORCH_UPGRADE", "1")]);
+ assert!(installer_env(InstallerEnv::default()).is_empty());
+ }
+
+ #[test]
+ fn a_declined_long_paths_prompt_reaches_setup_ps1() {
+ let skip = InstallerEnv {
+ skip_long_paths: true,
+ ..Default::default()
+ };
+ assert_eq!(installer_env(skip), vec![("UNSLOTH_SKIP_LONG_PATHS", "1")]);
+ let both = InstallerEnv {
+ upgrade_torch: true,
+ skip_long_paths: true,
+ };
+ assert_eq!(
+ installer_env(both),
+ vec![("UNSLOTH_TORCH_UPGRADE", "1"), ("UNSLOTH_SKIP_LONG_PATHS", "1")]
+ );
}
#[test]
diff --git a/studio/src-tauri/src/long_paths.rs b/studio/src-tauri/src/long_paths.rs
new file mode 100644
index 00000000000..aa6a2f46004
--- /dev/null
+++ b/studio/src-tauri/src/long_paths.rs
@@ -0,0 +1,222 @@
+// 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 Long Paths, elevated from the startup screen instead of mid-install by setup.ps1.
+
+use serde::Serialize;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "lowercase")]
+#[cfg_attr(not(windows), allow(dead_code))]
+pub enum LongPathsStatus {
+ Enabled,
+ Disabled,
+ Unsupported,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "lowercase")]
+#[cfg_attr(not(windows), allow(dead_code))]
+pub enum EnableLongPathsOutcome {
+ Enabled,
+ Declined,
+ Failed,
+}
+
+#[tauri::command]
+pub fn windows_long_paths_status() -> LongPathsStatus {
+ status()
+}
+
+#[tauri::command]
+pub async fn enable_windows_long_paths(webview: tauri::Webview) -> EnableLongPathsOutcome {
+ let owner = owner_window(&webview);
+ tokio::task::spawn_blocking(move || enable(owner))
+ .await
+ .unwrap_or(EnableLongPathsOutcome::Failed)
+}
+
+/// Owning the consent prompt keeps it in front of the app instead of flashing in the taskbar.
+#[cfg(windows)]
+fn owner_window(webview: &tauri::Webview) -> isize {
+ webview.window().hwnd().map_or(0, |hwnd| hwnd.0 as isize)
+}
+
+#[cfg(not(windows))]
+fn owner_window(_webview: &tauri::Webview) -> isize {
+ 0
+}
+
+#[cfg(windows)]
+fn status() -> LongPathsStatus {
+ use winreg::enums::{HKEY_LOCAL_MACHINE, KEY_QUERY_VALUE};
+ use winreg::RegKey;
+
+ let enabled = RegKey::predef(HKEY_LOCAL_MACHINE)
+ .open_subkey_with_flags(
+ r"SYSTEM\CurrentControlSet\Control\FileSystem",
+ KEY_QUERY_VALUE,
+ )
+ .and_then(|key| key.get_value::<u32, _>("LongPathsEnabled"))
+ .is_ok_and(|value| value == 1);
+ if enabled {
+ LongPathsStatus::Enabled
+ } else {
+ LongPathsStatus::Disabled
+ }
+}
+
+#[cfg(not(windows))]
+fn status() -> LongPathsStatus {
+ LongPathsStatus::Unsupported
+}
+
+#[cfg(windows)]
+fn enable(owner: isize) -> EnableLongPathsOutcome {
+ use std::ffi::OsStr;
+ use std::os::windows::ffi::OsStrExt;
+ use windows_sys::Win32::Foundation::{
+ CloseHandle, GetLastError, ERROR_CANCELLED, HWND, WAIT_TIMEOUT,
+ };
+ use windows_sys::Win32::System::Com::{
+ CoInitializeEx, CoUninitialize, COINIT_APARTMENTTHREADED, COINIT_DISABLE_OLE1DDE,
+ };
+ use windows_sys::Win32::System::Threading::{GetExitCodeProcess, WaitForSingleObject};
+ use windows_sys::Win32::UI::Shell::{
+ ShellExecuteExW, SEE_MASK_NOASYNC, SEE_MASK_NOCLOSEPROCESS, SHELLEXECUTEINFOW,
+ };
+
+ fn wide(s: &OsStr) -> Vec<u16> {
+ s.encode_wide().chain(std::iter::once(0)).collect()
+ }
+
+ if status() == LongPathsStatus::Enabled {
+ return EnableLongPathsOutcome::Enabled;
+ }
+ let Some(reg_exe) = system_reg_exe() else {
+ log::warn!("long paths: no system directory");
+ return EnableLongPathsOutcome::Failed;
+ };
+ let verb = wide(OsStr::new("runas"));
+ let file = wide(reg_exe.as_os_str());
+ let params = wide(OsStr::new(
+ r#"add "HKLM\SYSTEM\CurrentControlSet\Control\FileSystem" /v LongPathsEnabled /t REG_DWORD /d 1 /f"#,
+ ));
+
+ let mut info: SHELLEXECUTEINFOW = unsafe { std::mem::zeroed() };
+ info.cbSize = std::mem::size_of::<SHELLEXECUTEINFOW>() as u32;
+ info.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC;
+ info.hwnd = owner as HWND;
+ info.lpVerb = verb.as_ptr();
+ info.lpFile = file.as_ptr();
+ info.lpParameters = params.as_ptr();
+ info.nShow = 0; // SW_HIDE
+
+ // ShellExecuteEx can route a verb through shell extensions, which expect COM on this thread.
+ let com = unsafe {
+ CoInitializeEx(
+ std::ptr::null(),
+ (COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE) as u32,
+ )
+ };
+ let launched = unsafe { ShellExecuteExW(&mut info) } != 0;
+ let error = if launched {
+ 0
+ } else {
+ unsafe { GetLastError() }
+ };
+ if com >= 0 {
+ unsafe { CoUninitialize() };
+ }
+ if !launched {
+ if error == ERROR_CANCELLED {
+ log::info!("long paths: UAC declined");
+ return EnableLongPathsOutcome::Declined;
+ }
+ log::warn!("long paths: ShellExecuteExW failed ({error})");
+ return EnableLongPathsOutcome::Failed;
+ }
+ if !info.hProcess.is_null() {
+ let mut code: u32 = 1;
+ unsafe {
+ if WaitForSingleObject(info.hProcess, 60_000) == WAIT_TIMEOUT {
+ log::warn!("long paths: reg.exe still running after 60 s");
+ } else if GetExitCodeProcess(info.hProcess, &mut code) != 0 && code != 0 {
+ log::warn!("long paths: reg.exe exited {code}");
+ }
+ CloseHandle(info.hProcess);
+ }
+ }
+ // The registry, not reg.exe's exit code, decides.
+ outcome_from_registry()
+}
+
+/// From the system directory itself: %SystemRoot% comes from the user's environment.
+#[cfg(windows)]
+fn system_reg_exe() -> Option<std::path::PathBuf> {
+ use std::os::windows::ffi::OsStringExt;
+ use windows_sys::Win32::System::SystemInformation::GetSystemDirectoryW;
+
+ let mut buffer = [0u16; 260];
+ let len = unsafe { GetSystemDirectoryW(buffer.as_mut_ptr(), buffer.len() as u32) } as usize;
+ if len == 0 || len >= buffer.len() {
+ return None;
+ }
+ let dir = std::ffi::OsString::from_wide(&buffer[..len]);
+ Some(std::path::Path::new(&dir).join("reg.exe"))
+}
+
+#[cfg(windows)]
+fn outcome_from_registry() -> EnableLongPathsOutcome {
+ if status() == LongPathsStatus::Enabled {
+ log::info!("long paths: enabled via UAC");
+ EnableLongPathsOutcome::Enabled
+ } else {
+ EnableLongPathsOutcome::Failed
+ }
+}
+
+#[cfg(not(windows))]
+fn enable(_owner: isize) -> EnableLongPathsOutcome {
+ EnableLongPathsOutcome::Failed
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn serializes_as_lowercase_strings_for_the_frontend() {
+ assert_eq!(
+ serde_json::to_string(&LongPathsStatus::Disabled).unwrap(),
+ "\"disabled\""
+ );
+ assert_eq!(
+ serde_json::to_string(&LongPathsStatus::Unsupported).unwrap(),
+ "\"unsupported\""
+ );
+ assert_eq!(
+ serde_json::to_string(&EnableLongPathsOutcome::Declined).unwrap(),
+ "\"declined\""
+ );
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn reg_exe_comes_from_the_system_directory() {
+ let reg_exe = system_reg_exe().expect("system directory");
+ assert!(reg_exe.is_file(), "{}", reg_exe.display());
+ let parent = reg_exe.parent().unwrap().file_name().unwrap();
+ assert!(
+ parent.eq_ignore_ascii_case("System32"),
+ "{}",
+ reg_exe.display()
+ );
+ }
+
+ #[cfg(not(windows))]
+ #[test]
+ fn other_platforms_never_ask() {
+ assert_eq!(status(), LongPathsStatus::Unsupported);
+ }
+}
diff --git a/studio/src-tauri/src/main.rs b/studio/src-tauri/src/main.rs
index a526843f15b..1592c278391 100644
--- a/studio/src-tauri/src/main.rs
+++ b/studio/src-tauri/src/main.rs
@@ -25,6 +25,7 @@ mod install;
mod install_watchdog;
#[cfg(target_os = "linux")]
mod linux_webkit;
+mod long_paths;
mod loopback_http;
#[cfg(target_os = "macos")]
mod macos_event_guard;
@@ -2335,6 +2336,8 @@ fn main() {
commands::native_path_leases_usable,
commands::cancel_pending_elevation,
commands::install_system_packages,
+ long_paths::windows_long_paths_status,
+ long_paths::enable_windows_long_paths,
desktop_auth::desktop_auth,
desktop_update_policy::check_desktop_manual_update,
desktop_update_policy::desktop_update_policy,
diff --git a/tests/studio_setup_ps1/Studio.Setup.SelfRerun.Tests.ps1 b/tests/studio_setup_ps1/Studio.Setup.SelfRerun.Tests.ps1
index dd60f2798f5..817d0f14bfa 100644
--- a/tests/studio_setup_ps1/Studio.Setup.SelfRerun.Tests.ps1
+++ b/tests/studio_setup_ps1/Studio.Setup.SelfRerun.Tests.ps1
@@ -298,7 +298,10 @@ Describe 'elevation prompts across the rerun' {
function Write-StudioLine { param([string]$Text) }
function Get-VcBuildCustomizationsDir { param($VsInstallPath, $Generator) $script:VsCustomDir }
}
- AfterEach { Remove-Item Env:UNSLOTH_SETUP_RERUN -ErrorAction SilentlyContinue }
+ AfterEach {
+ Remove-Item Env:UNSLOTH_SETUP_RERUN -ErrorAction SilentlyContinue
+ Remove-Item Env:UNSLOTH_SKIP_LONG_PATHS -ErrorAction SilentlyContinue
+ }
It 'Long Paths runs at top level before the handoff, so the first pass has already asked' {
$at = $script:SetupText.IndexOf('$LongPathsEnabled = $false')
@@ -318,6 +321,18 @@ Describe 'elevation prompts across the rerun' {
Should -Invoke Start-Process -Times $Expected -Exactly
}
+ It 'Long Paths: never asks again once the desktop app''s explainer was skipped (<Skip>)' -ForEach @(
+ @{ Skip = ''; Expected = 1 }, @{ Skip = '1'; Expected = 0 }
+ ) {
+ Mock Get-ItemProperty { [pscustomobject]@{ LongPathsEnabled = 0 } }
+ Mock Start-Process { [pscustomobject]@{ ExitCode = 0 } }
+ if ($Skip) { $env:UNSLOTH_SKIP_LONG_PATHS = $Skip }
+ $StageRoot = $null
+ . ([scriptblock]::Create($script:LongPathsBlock))
+ Should -Invoke Start-Process -Times $Expected -Exactly
+ $LongPathsEnabled | Should -Be ($Expected -eq 1)
+ }
+
It 'the VC++ runtime install runs at top level before the handoff' {
$calls = @($script:Ast.FindAll({ param($n)
$n -is [System.Management.Automation.Language.CommandAst] -and $n.GetCommandName() -eq 'Ensure-VCRedist' }, $true))