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.

108 KB
Raw Blame
use super::types::ManagedProbe;
use super::version::{
    compare_versions, expected_backend_version, managed_backend_version_stale_reason,
    parse_version, DESKTOP_MANAGEABILITY_VERSION, DESKTOP_PROTOCOL_VERSION,
};
use log::{info, warn};
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Stdio;
use std::time::{Duration, Instant, UNIX_EPOCH};
use tokio::io::AsyncReadExt;

// 4: fingerprint includes the llama.cpp runtime so quarantine invalidates the cache.
const MANAGED_CAPABILITY_CACHE_SCHEMA: u16 = 4;

/// 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";

/// Names the offending setting (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
}

/// The runtime gate was held, so the CLI was never probed. Mirrored in the frontend.
pub(super) const MANAGED_ENVIRONMENT_BUSY: &str = "managed_environment_busy";
/// This app's own install, update or repair is running. Mirrored in the frontend.
pub(super) const MANAGED_ENVIRONMENT_UPDATING: &str = "managed_environment_updating";

pub(super) fn blocks_auto_repair(reason: &str) -> bool {
    reason == MANAGED_ENVIRONMENT_BUSY || is_context_reason(reason)
}

fn unasked_reason(error: &str) -> String {
    if error == MANAGED_ENVIRONMENT_BUSY {
        return error.to_string();
    }
    working_directory_reason().unwrap_or_else(|| WORKING_DIRECTORY_UNAVAILABLE.to_string())
}

fn probe_spawn_error(error: String) -> String {
    if error == crate::process::STUDIO_RUNTIME_GATE_BUSY {
        MANAGED_ENVIRONMENT_BUSY.to_string()
    } else {
        error
    }
}

const FNV64_OFFSET_BASIS: u64 = 0xcbf29ce484222325;
const FNV64_PRIME: u64 = 0x100000001b3;
const HASHED_MARKER_MAX_BYTES: u64 = 64 * 1024;

const FALLBACK_MARKER_NAMES: &[&str] = &[
    // Fingerprinted so a repair dropping the manifest invalidates the cache. Mirrors MANIFEST_NAME.
    "unsloth_install_manifest.json",
    "pyvenv.cfg",
    "uv.lock",
    "requirements.txt",
    "python.exe",
    "python",
];

#[derive(Debug, Clone, Deserialize, Serialize)]
struct DesktopCapability {
    desktop_protocol_version: Option<u16>,
    desktop_manageability_version: Option<u16>,
    supports_api_only: Option<bool>,
    supports_provision_desktop_auth: Option<bool>,
    supports_desktop_backend_ownership: Option<bool>,
    desktop_auth_stale_reason: Option<String>,
    // A partial install answers `-h` but its backend dies on import, so a running CLI is not ready.
    studio_install_ok: Option<bool>,
    studio_install_reason: Option<String>,
    // Quarantine can remove runtime files. None when the CLI is too old or nothing is installed.
    llama_runtime_ok: Option<bool>,
    llama_runtime_reason: Option<String>,
    version: Option<String>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
struct ManagedCapabilityCache {
    schema: u16,
    bin_path: String,
    bin_size: u64,
    bin_mtime_ms: u64,
    studio_root_id: Option<String>,
    marker_path: Option<String>,
    marker_size: Option<u64>,
    marker_mtime_ms: Option<u64>,
    llama_runtime: Option<String>,
    desktop_protocol_version: u16,
    desktop_manageability_version: u16,
    capability: DesktopCapability,
}

#[derive(Debug, Clone)]
struct MarkerFingerprint {
    path: String,
    size: u64,
    mtime_ms: u64,
    content_hash: Option<u64>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct ManagedBinFingerprint {
    bin_path: String,
    bin_size: u64,
    bin_mtime_ms: u64,
    studio_root_id: Option<String>,
    marker_path: Option<String>,
    marker_size: Option<u64>,
    marker_mtime_ms: Option<u64>,
    llama_runtime: Option<String>,
}

fn modified_ms(metadata: &fs::Metadata) -> Option<u64> {
    metadata
        .modified()
        .ok()?
        .duration_since(UNIX_EPOCH)
        .ok()
        .and_then(|duration| u64::try_from(duration.as_millis()).ok())
}
fn hash_bytes(hash: u64, bytes: &[u8]) -> u64 {
    bytes.iter().fold(hash, |mut next, byte| {
        next ^= u64::from(*byte);
        next.wrapping_mul(FNV64_PRIME)
    })
}

fn marker_content_hash(path: &Path, metadata: &fs::Metadata) -> Option<u64> {
    if metadata.len() > HASHED_MARKER_MAX_BYTES {
        return None;
    }
    fs::read(path)
        .ok()
        .map(|bytes| hash_bytes(FNV64_OFFSET_BASIS, &bytes))
}

fn site_packages_dirs(venv_dir: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    #[cfg(unix)]
    {
        if let Ok(lib_dir) = fs::read_dir(venv_dir.join("lib")) {
            for entry in lib_dir.flatten() {
                out.push(entry.path().join("site-packages"));
            }
        }
    }
    out.push(venv_dir.join("Lib").join("site-packages"));
    // read_dir order is unspecified and the hashes below fold in order.
    out.sort();
    out
}

/// Hash of installed .dist-info/.egg-info names; pip uninstall changes nothing else fingerprinted.
fn installed_distributions_hash(site_packages: &Path) -> Option<u64> {
    let mut names: Vec<String> = fs::read_dir(site_packages)
        .ok()?
        .flatten()
        .filter_map(|entry| {
            let name = entry.file_name().to_string_lossy().into_owned();
            (name.ends_with(".dist-info") || name.ends_with(".egg-info")).then_some(name)
        })
        .collect();
    names.sort();
    Some(names.iter().fold(FNV64_OFFSET_BASIS, |hash, name| {
        hash_bytes(hash, name.as_bytes())
    }))
}

fn marker_candidates_for_bin(bin: &Path) -> Vec<PathBuf> {
    let Some(scripts_dir) = bin.parent() else {
        return Vec::new();
    };
    let Some(venv_dir) = scripts_dir.parent() else {
        return Vec::new();
    };
    let mut out = Vec::new();

    for site_packages in site_packages_dirs(venv_dir) {
        out.push(
            site_packages
                .join("unsloth_cli")
                .join("commands")
                .join("studio.py"),
        );
    }
    for marker_name in FALLBACK_MARKER_NAMES {
        out.push(venv_dir.join(marker_name));
        out.push(scripts_dir.join(marker_name));
    }
    out
}

/// The file standing for "this CLI": the launcher, or python.exe on Windows when quarantine removed it.
fn fingerprint_identity_file(bin: &Path) -> Option<PathBuf> {
    if bin.exists() {
        return Some(bin.to_path_buf());
    }
    #[cfg(windows)]
    {
        let interpreter = bin.parent()?.join("python.exe");
        if interpreter.exists() {
            return Some(interpreter);
        }
    }
    None
}

fn managed_bin_fingerprint(bin: &Path) -> Option<ManagedBinFingerprint> {
    // Metadata from whatever identifies this CLI, but the cache key below stays the
    // launcher path, so the two layouts of one install cannot collide.
    let bin_metadata = fs::metadata(fingerprint_identity_file(bin)?).ok()?;
    let bin_path = bin
        .canonicalize()
        .unwrap_or_else(|_| bin.to_path_buf())
        .to_string_lossy()
        .into_owned();

    let studio_root_id = crate::desktop_backend_owner::read_expected_studio_root_id();
    let mut marker_entries: Vec<MarkerFingerprint> = marker_candidates_for_bin(bin)
        .into_iter()
        .filter_map(|path| {
            let metadata = fs::metadata(&path).ok()?;
            Some(MarkerFingerprint {
                path: path
                    .canonicalize()
                    .unwrap_or(path.clone())
                    .to_string_lossy()
                    .into_owned(),
                size: metadata.len(),
                mtime_ms: modified_ms(&metadata)?,
                content_hash: marker_content_hash(&path, &metadata),
            })
        })
        .collect();
    marker_entries.sort_by(|left, right| left.path.cmp(&right.path));
    let mut marker_hash = marker_entries
        .iter()
        .fold(FNV64_OFFSET_BASIS, |hash, marker| {
            let next = hash_bytes(hash, marker.path.as_bytes());
            let next = hash_bytes(next, &marker.size.to_le_bytes());
            let next = hash_bytes(next, &marker.mtime_ms.to_le_bytes());
            if let Some(content_hash) = marker.content_hash {
                hash_bytes(next, &content_hash.to_le_bytes())
            } else {
                next
            }
        });
    let mut tracked = marker_entries.len();
    if let Some(venv_dir) = bin.parent().and_then(Path::parent) {
        for site_packages in site_packages_dirs(venv_dir) {
            let Some(dist_hash) = installed_distributions_hash(&site_packages) else {
                continue;
            };
            marker_hash = hash_bytes(marker_hash, site_packages.to_string_lossy().as_bytes());
            marker_hash = hash_bytes(marker_hash, &dist_hash.to_le_bytes());
            tracked += 1;
        }
    }
    let marker_path = (tracked > 0).then(|| "markers".to_string());
    let marker_size = (tracked > 0).then_some(tracked as u64);
    let marker_mtime_ms = (tracked > 0).then_some(marker_hash);

    Some(ManagedBinFingerprint {
        bin_path,
        bin_size: bin_metadata.len(),
        bin_mtime_ms: modified_ms(&bin_metadata)?,
        studio_root_id,
        marker_path,
        marker_size,
        marker_mtime_ms,
        llama_runtime: llama_runtime_fingerprint(bin),
    })
}

/// `~` resolved like the CLI child: ntpath uses USERPROFILE, not dirs::home_dir()'s known folder.
/// process.rs uses this too so pinning and fingerprinting agree.
pub(crate) fn tilde_home() -> Option<PathBuf> {
    if cfg!(windows) {
        if let Some(profile) = std::env::var_os("USERPROFILE") {
            if !profile.is_empty() {
                return Some(PathBuf::from(profile));
            }
        }
    }
    dirs::home_dir()
}

/// UNSLOTH_LLAMA_CPP_PATH as the CLI child sees it: trimmed, `~` expanded, relative anchored to cwd.
/// UNSLOTH_STUDIO_HOME is ignored: managed spawns scrub it.
#[cfg_attr(test, allow(dead_code))]
fn llama_runtime_override() -> Option<PathBuf> {
    llama_runtime_override_from(
        std::env::var("UNSLOTH_LLAMA_CPP_PATH").ok().as_deref(),
        tilde_home().as_deref(),
        std::env::current_dir().ok().as_deref(),
    )
}

/// Split out from the reads so tests can drive it without a process-wide variable.
pub(crate) fn llama_runtime_override_from(
    value: Option<&str>,
    home: Option<&Path>,
    cwd: Option<&Path>,
) -> Option<PathBuf> {
    let value = value?.trim();
    if value.is_empty() {
        return None;
    }
    if value == "~" {
        return home.map(Path::to_path_buf);
    }
    if let Some(rest) = value
        .strip_prefix("~/")
        .or_else(|| cfg!(windows).then(|| value.strip_prefix("~\\")).flatten())
    {
        return Some(home?.join(rest));
    }
    if let Some(named) = named_user_home(value, home) {
        return Some(named);
    }
    let path = PathBuf::from(value);
    if path.is_absolute() {
        return Some(path);
    }
    // Anchored, not dropped: the child joins it to this same directory.
    Some(cwd?.join(path))
}

/// `~alice/...` via the password database, as Path.expanduser() does; None for unknown names.
#[cfg(unix)]
pub(crate) fn named_user_home(value: &str, _home: Option<&Path>) -> Option<PathBuf> {
    use std::os::unix::ffi::OsStrExt;

    let rest = value.strip_prefix('~')?;
    if rest.is_empty() {
        return None;
    }
    let (name, tail) = match rest.find('/') {
        Some(at) => (&rest[..at], &rest[at + 1..]),
        None => (rest, ""),
    };
    if name.is_empty() {
        return None;
    }
    let c_name = std::ffi::CString::new(name).ok()?;
    // getpwnam_r, not getpwnam: getpwnam returns process-shared storage another thread can overwrite.
    let mut buffer = vec![0i8; 1024];
    let mut passwd: libc::passwd = unsafe { std::mem::zeroed() };
    let home = loop {
        let mut found: *mut libc::passwd = std::ptr::null_mut();
        let code = unsafe {
            libc::getpwnam_r(
                c_name.as_ptr(),
                &mut passwd,
                buffer.as_mut_ptr() as *mut libc::c_char,
                buffer.len(),
                &mut found,
            )
        };
        if code == libc::ERANGE && buffer.len() < 1 << 20 {
            // Buffer too small; growth is capped so a broken passwd source cannot allocate without end.
            buffer.resize(buffer.len() * 2, 0);
            continue;
        }
        if code != 0 || found.is_null() {
            return None;
        }
        let dir = passwd.pw_dir;
        if dir.is_null() {
            return None;
        }
        break PathBuf::from(std::ffi::OsStr::from_bytes(unsafe {
            std::ffi::CStr::from_ptr(dir).to_bytes()
        }));
    };
    Some(if tail.is_empty() { home } else { home.join(tail) })
}

#[cfg(windows)]
pub(crate) fn named_user_home(value: &str, home: Option<&Path>) -> Option<PathBuf> {
    named_windows_user_home(value, home?, std::env::var("USERNAME").ok().as_deref())
}

#[cfg(not(any(unix, windows)))]
pub(crate) fn named_user_home(_value: &str, _home: Option<&Path>) -> Option<PathBuf> {
    None
}

/// `~name` on Windows as ntpath.expanduser resolves it (sibling profile), matching process.rs.
/// None where ntpath declines, e.g. a profile not named after the current user.
#[cfg_attr(not(windows), allow(dead_code))]
fn named_windows_user_home(value: &str, home: &Path, username: Option<&str>) -> Option<PathBuf> {
    let rest = value.strip_prefix('~')?;
    let end = rest.find(['\\', '/']).unwrap_or(rest.len());
    let (name, tail) = (&rest[..end], &rest[end..]);
    if name.is_empty() {
        return None;
    }
    let home = home.to_string_lossy();
    // Split on the string, not with Path::parent: these are Windows paths
    // whichever platform is reading them.
    let cut = home.rfind(['\\', '/'])?;
    let this_profile = &home[cut + 1..];
    let base = match username {
        Some(user) if user == name => home.clone().into_owned(),
        // C:\Users\alice.DOMAIN is not alice's sibling, so ntpath refuses unless
        // this profile is named after the current user.
        Some(user) if user == this_profile => format!("{}{}", &home[..cut + 1], name),
        _ => return None,
    };
    Some(PathBuf::from(format!("{base}{tail}")))
}

/// Markers and max size of install.ps1's unsloth.cmd shim; same pair as `_is_managed_cmd_shim`.
#[cfg(any(windows, test))]
const CMD_SHIM_MARKERS: [&[u8]; 2] = [b"unsloth-studio-managed-launcher", b"from unsloth_cli import app"];
#[cfg(any(windows, test))]
const CMD_SHIM_MAX_BYTES: u64 = 8192;

/// Mirrors `_looks_like_installer_managed_studio_home` in the CLI.
fn looks_like_installer_managed_studio_home(candidate: &Path) -> bool {
    if candidate.join("share").join("studio.conf").is_file() {
        return true;
    }
    #[cfg(not(windows))]
    {
        candidate.join("bin").join("unsloth").is_file()
    }
    #[cfg(windows)]
    {
        if candidate.join("bin").join("unsloth.exe").is_file() {
            return true;
        }
        is_managed_cmd_shim(&candidate.join("bin").join("unsloth.cmd"))
    }
}

/// Whether a path is the `.cmd` shim this installer generates.
#[cfg(any(windows, test))]
fn is_managed_cmd_shim(path: &Path) -> bool {
    let Ok(metadata) = fs::metadata(path) else {
        return false;
    };
    if !metadata.is_file() || metadata.len() > CMD_SHIM_MAX_BYTES {
        return false;
    }
    let Ok(body) = fs::read(path) else {
        return false;
    };
    CMD_SHIM_MARKERS
        .iter()
        .all(|marker| body.windows(marker.len()).any(|window| window == *marker))
}

/// The CLI re-infers the studio root from sys.prefix and repoints UNSLOTH_LLAMA_CPP_PATH there,
/// so the fingerprint must follow it. `bin`'s grandparent is `sys.prefix`.
fn inferred_studio_llama_root(bin: &Path) -> Option<PathBuf> {
    let prefix = bin.parent()?.parent()?;
    if prefix.file_name()? != "unsloth_studio" {
        return None;
    }
    let root = prefix.parent()?;
    // Python resolves both sides, so a symlinked legacy root is still the legacy root.
    let legacy = dirs::home_dir()?.join(".unsloth").join("studio");
    let same = match (root.canonicalize(), legacy.canonicalize()) {
        (Ok(left), Ok(right)) => left == right,
        _ => root == legacy,
    };
    if same {
        return None;
    }
    if !looks_like_installer_managed_studio_home(root) {
        return None;
    }
    // A master root puts runtimes beside studio/; the CLI grades <master>/llama.cpp.
    if let Some(master) = recorded_master_root(root) {
        return Some(master.join("llama.cpp"));
    }
    Some(root.join("llama.cpp"))
}

/// Same rule as `_recorded_master_root` in unsloth_cli/commands/studio.py: must exist and contain this tree.
fn recorded_master_root(studio_home: &Path) -> Option<PathBuf> {
    let note = studio_home.join("share").join(".unsloth-master-root");
    let recorded = std::fs::read_to_string(note).ok()?;
    let recorded = recorded.trim();
    if recorded.is_empty() {
        return None;
    }
    let master = PathBuf::from(recorded);
    if !master.is_dir() {
        return None;
    }
    let master = master.canonicalize().unwrap_or_else(|_| master.clone());
    let here = studio_home
        .canonicalize()
        .unwrap_or_else(|_| studio_home.to_path_buf());
    if here == master || here.ancestors().any(|ancestor| ancestor == master) {
        return Some(master);
    }
    None
}

/// Presence, not executability, matching `_scan_pinned`, which also stops at a non-executable server.
fn holds_a_llama_server(root: &Path) -> bool {
    let name = if cfg!(windows) {
        "llama-server.exe"
    } else {
        "llama-server"
    };
    let mut candidates = vec![root.join(name), root.join("build").join("bin").join(name)];
    if cfg!(windows) {
        candidates.push(root.join("build").join("bin").join("Release").join(name));
    }
    candidates.iter().any(|candidate| {
        let Ok(metadata) = fs::metadata(candidate) else {
            return false;
        };
        metadata.is_file()
    })
}

/// The managed llama.cpp root, as default_managed_llama_dir picks it in Python.
fn llama_runtime_root(bin: &Path) -> Option<PathBuf> {
    // Hermetic under test; unset means no runtime.
    #[cfg(test)]
    {
        let _ = bin;
        return std::env::var_os("UNSLOTH_TEST_LLAMA_RUNTIME_ROOT").map(PathBuf::from);
    }
    // The override's answer is final. Trimmed first: whitespace-only means no override, as in Python.
    #[cfg(not(test))]
    if std::env::var("UNSLOTH_LLAMA_CPP_PATH")
        .is_ok_and(|value| !value.trim().is_empty())
    {
        // A desktop-written override is taken as given; a user one only if it holds a server,
        // as in _scan_pinned.
        let desktop_wrote_it =
            std::env::var("UNSLOTH_STUDIO_MANAGED_LLAMA_CPP_PATH").as_deref() == Ok("1");
        let override_root = llama_runtime_override();
        if desktop_wrote_it {
            return override_root;
        }
        if let Some(root) = override_root {
            if holds_a_llama_server(&root) {
                return Some(root);
            }
        }
    }
    #[cfg(not(test))]
    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"));
}

/// File count and byte total of the runtime bin dir; None when no runtime is installed.
fn llama_runtime_fingerprint(bin: &Path) -> Option<String> {
    llama_runtime_fingerprint_at(&llama_runtime_root(bin)?)
}

fn llama_runtime_fingerprint_at(root: &Path) -> Option<String> {
    let mut bin = root.join("build").join("bin");
    if cfg!(windows) {
        bin = bin.join("Release");
    }
    let root_part = root_entrypoints(root);
    match fs::read_dir(&bin) {
        Ok(entries) => Some(format!("bin:{}|root:{root_part}", counted(entries))),
        // Missing build/bin is distinct from nothing installed, so fingerprint the root's entries.
        Err(_) => fs::read_dir(root)
            .ok()
            .map(|entries| format!("nobin:{}|root:{root_part}", counted(entries))),
    }
}

/// Root entrypoints, which `_find_llama_server_binary` checks before build/bin. Follows links like the CLI.
fn root_entrypoints(root: &Path) -> String {
    let ext = if cfg!(windows) { ".exe" } else { "" };
    let mut out = String::new();
    for name in ["llama-server", "llama-quantize"] {
        if !out.is_empty() {
            out.push(',');
        }
        match fs::metadata(root.join(format!("{name}{ext}"))) {
            Ok(meta) => {
                #[cfg(unix)]
                let mode = {
                    use std::os::unix::fs::PermissionsExt;
                    u64::from(meta.permissions().mode() & 0o7777)
                };
                #[cfg(not(unix))]
                let mode = 0u64;
                out.push_str(&format!("{}:{}:{mode}", u64::from(meta.is_file()), meta.len()));
            }
            Err(_) => out.push('-'),
        }
    }
    out
}

/// Files, bytes, links and summed mode bits; links and exec bits are tracked because
/// installed_runtime_health rejects their loss.
fn counted(entries: fs::ReadDir) -> String {
    let mut count: u64 = 0;
    let mut bytes: u64 = 0;
    let mut links: u64 = 0;
    let mut modes: u64 = 0;
    let mut names: u64 = 0;
    for entry in entries.flatten() {
        let Ok(meta) = entry.metadata() else {
            continue;
        };
        if meta.is_symlink() {
            links += 1;
            names = names.wrapping_add(name_hash(&entry.file_name()));
            continue;
        }
        if meta.is_file() {
            count += 1;
            names = names.wrapping_add(name_hash(&entry.file_name()));
            bytes += meta.len();
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                // Sum of full mode bits: the owner's bits alone decide os.access(X_OK). Zero on Windows.
                modes += u64::from(meta.permissions().mode() & 0o7777);
            }
        }
    }
    format!("{count}:{bytes}:{links}:{modes}:{names}")
}

/// FNV-1a (stable across Rust releases) of an entry name, summed since read_dir order is unspecified.
/// Names catch quarantine renames that leave every counter unchanged.
fn name_hash(name: &std::ffi::OsStr) -> u64 {
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for byte in name.to_string_lossy().as_bytes() {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(0x1000_0000_01b3);
    }
    hash
}

/// Only the pre-probe fingerprint, and only if the tree still matches, so a mid-probe quarantine
/// is not cached.
fn fingerprint_to_cache_under<'a>(
    before: Option<&'a ManagedBinFingerprint>,
    after: Option<ManagedBinFingerprint>,
) -> Option<&'a ManagedBinFingerprint> {
    let before = before?;
    (after.as_ref() == Some(before)).then_some(before)
}

fn capability_cache_path() -> Option<PathBuf> {
    #[cfg(test)]
    if let Some(home) = std::env::var_os("UNSLOTH_TEST_DESKTOP_CAPABILITY_CACHE_HOME") {
        return Some(
            PathBuf::from(home)
                .join(".unsloth")
                .join("studio")
                .join("desktop_capability_cache.json"),
        );
    }

    dirs::home_dir().map(|home| {
        crate::studio_home::studio_root_for_home(&home).join("desktop_capability_cache.json")
    })
}

fn cache_matches(cache: &ManagedCapabilityCache, fingerprint: &ManagedBinFingerprint) -> bool {
    cache.schema == MANAGED_CAPABILITY_CACHE_SCHEMA
        && cache.desktop_protocol_version == DESKTOP_PROTOCOL_VERSION
        && cache.desktop_manageability_version == DESKTOP_MANAGEABILITY_VERSION
        && cache.bin_path == fingerprint.bin_path
        && cache.bin_size == fingerprint.bin_size
        && cache.bin_mtime_ms == fingerprint.bin_mtime_ms
        && cache.studio_root_id == fingerprint.studio_root_id
        && cache.marker_path == fingerprint.marker_path
        && cache.marker_size == fingerprint.marker_size
        && cache.marker_mtime_ms == fingerprint.marker_mtime_ms
        && cache.llama_runtime == fingerprint.llama_runtime
        && managed_capability_ready(Path::new(&fingerprint.bin_path), &cache.capability)
}

fn read_cached_capability(fingerprint: &ManagedBinFingerprint) -> Option<DesktopCapability> {
    let path = capability_cache_path()?;
    let bytes = fs::read(path).ok()?;
    let cache = serde_json::from_slice::<ManagedCapabilityCache>(&bytes).ok()?;
    if cache_matches(&cache, fingerprint) {
        Some(cache.capability)
    } else {
        None
    }
}

/// The CLI's word for "another runtime is the active one, so the managed tree is
/// not mine to grade". Its null verdict is about a selection, not about the tree.
const LLAMA_RUNTIME_NOT_MANAGED: &str = "llama_runtime_not_managed";

/// And its word for "the probe itself raised", which is about one attempt.
const LLAMA_RUNTIME_PROBE_FAILED: &str = "llama_runtime_probe_failed";

/// Skipped verdicts are not cacheable: their cause is outside this fingerprint.
fn llama_runtime_verdict_was_skipped(capability: &DesktopCapability) -> bool {
    capability.llama_runtime_ok.is_none()
        && matches!(
            capability.llama_runtime_reason.as_deref(),
            Some(LLAMA_RUNTIME_NOT_MANAGED) | Some(LLAMA_RUNTIME_PROBE_FAILED)
        )
}

fn write_cached_capability(fingerprint: &ManagedBinFingerprint, capability: &DesktopCapability) {
    if llama_runtime_verdict_was_skipped(capability) {
        return;
    }
    let Some(path) = capability_cache_path() else {
        return;
    };
    let cache = ManagedCapabilityCache {
        schema: MANAGED_CAPABILITY_CACHE_SCHEMA,
        bin_path: fingerprint.bin_path.clone(),
        bin_size: fingerprint.bin_size,
        bin_mtime_ms: fingerprint.bin_mtime_ms,
        studio_root_id: fingerprint.studio_root_id.clone(),
        marker_path: fingerprint.marker_path.clone(),
        marker_size: fingerprint.marker_size,
        marker_mtime_ms: fingerprint.marker_mtime_ms,
        llama_runtime: fingerprint.llama_runtime.clone(),
        desktop_protocol_version: DESKTOP_PROTOCOL_VERSION,
        desktop_manageability_version: DESKTOP_MANAGEABILITY_VERSION,
        capability: capability.clone(),
    };
    if let Some(parent) = path.parent() {
        if fs::create_dir_all(parent).is_err() {
            return;
        }
    }
    let Ok(bytes) = serde_json::to_vec_pretty(&cache) else {
        return;
    };
    if let Err(error) = fs::write(&path, bytes) {
        warn!(
            "Managed preflight: could not write capability cache: {}",
            error
        );
    }
}

async fn run_cli_probe(bin: &Path, args: &[&str]) -> Result<bool, String> {
    let started = Instant::now();
    let Ok(mut cmd) = crate::process::build_managed_cli_command_tokio(bin, args) else {
        info!(
            "Managed preflight probe {:?} has no managed interpreter to run",
            args
        );
        // Ok, not Err: a venv with no interpreter is a result, not a failed setup.
        return Ok(false);
    };
    cmd.stdout(Stdio::null()).stderr(Stdio::null());

    // Reported, not `false`: the CLI never ran, so calling it broken would trigger a pointless repair.
    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);

    // 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)]
    {
        use std::os::windows::process::CommandExt;
        cmd.creation_flags(crate::process::CREATE_NO_WINDOW);
    }

    let spawned = crate::process::with_studio_runtime_launch_guard(|| {
        cmd.spawn().map_err(|error| error.to_string())
    })
    .map_err(probe_spawn_error);
    let mut child = match spawned {
        Ok(child) => child,
        Err(error) if error == MANAGED_ENVIRONMENT_BUSY => {
            info!(
                "Managed preflight probe {:?} skipped: managed environment is busy",
                args
            );
            return Err(error);
        }
        Err(_) => {
            info!(
                "Managed preflight probe {:?} failed to spawn in {}ms",
                args,
                started.elapsed().as_millis()
            );
            return Ok(false);
        }
    };

    let ok = match tokio::time::timeout(Duration::from_secs(10), child.wait()).await {
        Ok(Ok(status)) => status.success(),
        _ => {
            let _ = child.kill().await;
            let _ = child.wait().await;
            false
        }
    };
    info!(
        "Managed preflight probe {:?} finished ok={} in {}ms",
        args,
        ok,
        started.elapsed().as_millis()
    );
    Ok(ok)
}

async fn probe_cli_capability(bin: &Path) -> Result<Option<DesktopCapability>, String> {
    let started = Instant::now();
    let Ok(mut cmd) = crate::process::build_managed_cli_command_tokio(
        bin,
        &["studio", "desktop-capabilities", "--json"],
    ) else {
        info!("Managed desktop-capabilities probe has no managed interpreter to run");
        // As above: a missing interpreter is a verdict, not a failure to ask.
        return Ok(None);
    };
    cmd.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);

    // 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)]
    {
        use std::os::windows::process::CommandExt;
        cmd.creation_flags(crate::process::CREATE_NO_WINDOW);
    }

    let spawned = crate::process::with_studio_runtime_launch_guard(|| {
        cmd.spawn().map_err(|error| error.to_string())
    })
    .map_err(probe_spawn_error);
    let mut child = match spawned {
        Ok(child) => child,
        Err(error) if error == MANAGED_ENVIRONMENT_BUSY => {
            info!("Managed desktop-capabilities probe skipped: managed environment is busy");
            return Err(error);
        }
        Err(_) => {
            info!(
                "Managed desktop-capabilities probe failed to spawn in {}ms",
                started.elapsed().as_millis()
            );
            return Ok(None);
        }
    };
    let Some(mut stdout) = child.stdout.take() else {
        return Ok(None);
    };

    match tokio::time::timeout(Duration::from_secs(10), child.wait()).await {
        Ok(Ok(status)) if status.success() => {}
        Err(_) => {
            let _ = child.kill().await;
            let _ = child.wait().await;
            info!(
                "Managed desktop-capabilities probe timed out in {}ms",
                started.elapsed().as_millis()
            );
            return Ok(None);
        }
        _ => {
            info!(
                "Managed desktop-capabilities probe exited unsuccessfully in {}ms",
                started.elapsed().as_millis()
            );
            return Ok(None);
        }
    }

    let mut output = Vec::new();
    if stdout.read_to_end(&mut output).await.is_err() {
        return Ok(None);
    }

    let capability = serde_json::from_slice::<DesktopCapability>(&output).ok();
    info!(
        "Managed desktop-capabilities probe finished ok={} in {}ms",
        capability.is_some(),
        started.elapsed().as_millis()
    );
    Ok(capability)
}

fn desktop_capability_stale_reason(capability: &DesktopCapability) -> Option<String> {
    if capability.desktop_protocol_version != Some(DESKTOP_PROTOCOL_VERSION) {
        return Some("desktop_protocol_incompatible".to_string());
    }
    if capability.supports_api_only != Some(true) {
        return Some("desktop_api_only_unsupported".to_string());
    }
    if capability.supports_provision_desktop_auth != Some(true) {
        return capability
            .desktop_auth_stale_reason
            .clone()
            .or_else(|| Some("desktop_auth_unsupported".to_string()));
    }
    if capability.desktop_manageability_version.unwrap_or(0) < DESKTOP_MANAGEABILITY_VERSION {
        return Some("desktop_manageability_unsupported".to_string());
    }
    if capability.supports_desktop_backend_ownership != Some(true) {
        return Some("desktop_backend_ownership_unsupported".to_string());
    }
    // Half-installed is Stale, not Ready: starting the backend just crashes it.
    // A CLI too old to answer is already rejected above on manageability.
    if capability.studio_install_ok != Some(true) {
        return Some(
            capability
                .studio_install_reason
                .clone()
                .unwrap_or_else(|| "studio_install_incomplete".to_string()),
        );
    }
    // Only explicit false: None (old CLI or nothing installed) must not force a repair.
    if capability.llama_runtime_ok == Some(false) {
        return Some(
            capability
                .llama_runtime_reason
                .clone()
                .filter(|reason| !reason.is_empty())
                .unwrap_or_else(|| "llama_runtime_incomplete".to_string()),
        );
    }
    managed_backend_version_stale_reason(capability.version.as_deref())
}

#[cfg(test)]
fn desktop_capability_ready(capability: &DesktopCapability) -> bool {
    desktop_capability_stale_reason(capability).is_none()
}

/// Beside pyvenv.cfg, written by the installers when the package index lacked this
/// build's backend release (#14031): a repair would only reinstall the same one.
const FEED_CEILING_MARKER: &str = "unsloth_feed_ceiling.json";

#[derive(Deserialize)]
struct FeedCeiling {
    requested: String,
    available: String,
}

fn feed_ceiling_holds(bin: &Path, version: Option<&str>, expected: &str) -> bool {
    let (Some(venv_dir), Some(version)) = (bin.parent().and_then(Path::parent), version) else {
        return false;
    };
    let Ok(bytes) = fs::read(venv_dir.join(FEED_CEILING_MARKER)) else {
        return false;
    };
    let Ok(ceiling) = serde_json::from_slice::<FeedCeiling>(&bytes) else {
        return false;
    };
    // An update can keep an installed release above the ceiling; a newer app re-grades.
    let installed = parse_version(version);
    let available = parse_version(&ceiling.available);
    let (Some(installed), Some(available)) = (installed, available) else {
        return false;
    };
    ceiling.requested == expected && compare_versions(&installed, &available).is_ge()
}

fn managed_capability_stale_reason(bin: &Path, capability: &DesktopCapability) -> Option<String> {
    let reason = desktop_capability_stale_reason(capability)?;
    let version = capability.version.as_deref();
    if reason == "desktop_backend_version_outdated"
        && feed_ceiling_holds(bin, version, expected_backend_version())
    {
        info!("Managed preflight: backend {version:?} is the newest the package index has; not repairing");
        return None;
    }
    Some(reason)
}

fn managed_capability_ready(bin: &Path, capability: &DesktopCapability) -> bool {
    managed_capability_stale_reason(bin, 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> {
    let error = crate::process::managed_cli_context_error()?;
    info!("Managed preflight: managed context unavailable: {error}");
    Some(context_reason(&error))
}

pub(super) struct LaunchCliProbe {
    bin: PathBuf,
    started: Instant,
    handle: tauri::async_runtime::JoinHandle<Result<bool, String>>,
    capability: Option<LaunchCapabilityProbe>,
}

type CapabilityProbeResult = Result<Option<DesktopCapability>, String>;

/// The capability answer a launch probe took on a cache miss, with the tree it was asked against.
struct LaunchCapabilityProbe {
    fingerprint: ManagedBinFingerprint,
    answer: tokio::sync::oneshot::Receiver<CapabilityProbeResult>,
}

type PendingLaunchCliProbe = tokio::sync::oneshot::Receiver<Option<LaunchCliProbe>>;

/// Filled before the setup thread runs, so an early preflight still waits for its spawn.
static LAUNCH_CLI_PROBE: std::sync::Mutex<Option<PendingLaunchCliProbe>> =
    std::sync::Mutex::new(None);

const LAUNCH_CLI_PROBE_MAX_AGE: Duration = Duration::from_secs(30);

/// The first preflight for the same CLI reuses a passing `-h` from here. Off the main thread:
/// finding the CLI touches the disk and the runtime's first use builds it.
pub(crate) fn start_launch_cli_probe() {
    let pending = begin_launch_cli_probe();
    let spawned = std::thread::Builder::new()
        .name("launch-cli-probe".to_string())
        .spawn(move || {
            let probe = crate::process::find_unsloth_binary()
                .filter(|_| crate::process::managed_cli_context_error().is_none())
                .map(|bin| {
                    let miss = capability_cache_miss(&bin);
                    spawn_launch_cli_probe(bin, miss)
                });
            let _ = pending.send(probe);
        });
    if let Err(error) = spawned {
        warn!("Could not start the launch CLI probe: {error}");
    }
}

pub(super) fn begin_launch_cli_probe() -> tokio::sync::oneshot::Sender<Option<LaunchCliProbe>> {
    let (sender, receiver) = tokio::sync::oneshot::channel();
    if let Ok(mut slot) = LAUNCH_CLI_PROBE.lock() {
        *slot = Some(receiver);
    }
    sender
}

/// The fingerprint to ask capabilities against, when the cache has no answer for it.
fn capability_cache_miss(bin: &Path) -> Option<ManagedBinFingerprint> {
    managed_bin_fingerprint(bin).filter(|fingerprint| read_cached_capability(fingerprint).is_none())
}

fn spawn_launch_cli_probe(
    bin: PathBuf,
    capability_miss: Option<ManagedBinFingerprint>,
) -> LaunchCliProbe {
    let probe_bin = bin.clone();
    let Some(fingerprint) = capability_miss else {
        let handle =
            tauri::async_runtime::spawn(async move { run_cli_probe(&probe_bin, &["-h"]).await });
        return launch_cli_probe_task(bin, handle);
    };
    // One task, as in the preflight's own miss, so the two spawns take the launch guard in turn.
    let (sender, answer) = tokio::sync::oneshot::channel();
    let handle = tauri::async_runtime::spawn(async move {
        let (help, capability) = tokio::join!(
            run_cli_probe(&probe_bin, &["-h"]),
            probe_cli_capability(&probe_bin)
        );
        let _ = sender.send(capability);
        help
    });
    let mut probe = launch_cli_probe_task(bin, handle);
    probe.capability = Some(LaunchCapabilityProbe {
        fingerprint,
        answer,
    });
    probe
}

pub(super) fn launch_cli_probe_task(
    bin: PathBuf,
    handle: tauri::async_runtime::JoinHandle<Result<bool, String>>,
) -> LaunchCliProbe {
    LaunchCliProbe {
        bin,
        started: Instant::now(),
        handle,
        capability: None,
    }
}

#[cfg(test)]
pub(super) fn install_launch_cli_probe(bin: PathBuf) {
    let _ = begin_launch_cli_probe().send(Some(spawn_launch_cli_probe(bin, None)));
}

/// What `start_launch_cli_probe` hands over for `bin`, including its cache-miss decision.
#[cfg(test)]
pub(super) fn install_launch_cli_probe_like_setup(bin: PathBuf) {
    let miss = capability_cache_miss(&bin);
    let _ = begin_launch_cli_probe().send(Some(spawn_launch_cli_probe(bin, miss)));
}

#[cfg(test)]
pub(super) fn install_launch_cli_probe_task(
    bin: PathBuf,
    handle: tauri::async_runtime::JoinHandle<Result<bool, String>>,
) {
    let _ = begin_launch_cli_probe().send(Some(launch_cli_probe_task(bin, handle)));
}

#[derive(Default)]
struct LaunchProbeReuse {
    help_passed: bool,
    /// Only when asked against the tree the preflight sees.
    capability: Option<DesktopCapability>,
}

/// The launch probe's reusable answers for `bin`, taken once. Any CLI's probe is awaited:
/// its spawns hold the runtime launch guard, which a spawn beside them reads as busy.
async fn take_launch_cli_probe(
    bin: &Path,
    fingerprint: Option<&ManagedBinFingerprint>,
) -> LaunchProbeReuse {
    let pending = match LAUNCH_CLI_PROBE.lock() {
        Ok(mut slot) => slot.take(),
        Err(_) => None,
    };
    let Some(pending) = pending else {
        return LaunchProbeReuse::default();
    };
    let Ok(Some(probe)) = pending.await else {
        return LaunchProbeReuse::default();
    };
    let passed = matches!(probe.handle.await, Ok(Ok(true)));
    if probe.bin != bin {
        info!(
            "Managed preflight: launch -h probe was for {:?}, not {:?}; not reused",
            probe.bin, bin
        );
        return LaunchProbeReuse::default();
    }
    let age = probe.started.elapsed();
    let fresh = age <= LAUNCH_CLI_PROBE_MAX_AGE;
    info!(
        "Managed preflight: launch -h probe passed={} age={}ms reused={}",
        passed,
        age.as_millis(),
        passed && fresh
    );
    if !(passed && fresh) {
        return LaunchProbeReuse::default();
    }
    let mut capability = None;
    if let Some(launch) = probe.capability {
        let same_tree = fingerprint == Some(&launch.fingerprint);
        // Only an answer: a failed or unasked probe is asked again, as on a miss without one.
        if let Ok(Ok(Some(answer))) = launch.answer.await {
            capability = same_tree.then_some(answer);
        }
        info!(
            "Managed preflight: launch desktop-capabilities probe reused={}",
            capability.is_some()
        );
    }
    LaunchProbeReuse {
        help_passed: true,
        capability,
    }
}

pub(super) async fn probe_managed_bin(bin: PathBuf) -> ManagedProbe {
    let started = Instant::now();

    // An unmounted profile is not a broken install; repair would need 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),
        };
    }

    // Fingerprint taken before any probe, so an answer is cached against the tree the CLI read.
    let fingerprint_before = managed_bin_fingerprint(&bin);
    let cache_hit = fingerprint_before
        .as_ref()
        .is_some_and(|fingerprint| read_cached_capability(fingerprint).is_some());

    // `-h` decides first: a fingerprint does not prove the CLI launches, and a failing `-h` wins over
    // a capability answer. Awaited before any spawn below, which would find its guard held.
    let launch = take_launch_cli_probe(&bin, fingerprint_before.as_ref()).await;
    let launch_help_passed = launch.help_passed;
    let help_probe = async {
        if launch_help_passed {
            Ok(true)
        } else {
            run_cli_probe(&bin, &["-h"]).await
        }
    };

    // A cache miss overlaps both Python starts; one task, so the spawns take the guard in turn.
    let (cli_probe, capability_probe) = if cache_hit {
        let help = help_probe.await;
        // The tree can change while `-h` runs; the cached answer holds only for the tree it was read under.
        if matches!(help, Ok(true)) && managed_bin_fingerprint(&bin) != fingerprint_before {
            (help, Some(probe_cli_capability(&bin).await))
        } else {
            (help, None)
        }
    } else if let Some(capability) = launch.capability {
        drop(help_probe);
        (Ok(true), Some(Ok(Some(capability))))
    } else {
        let (help, capability) = tokio::join!(help_probe, probe_cli_capability(&bin));
        (help, Some(capability))
    };

    match cli_probe {
        // The CLI was never asked, so do not report a broken install.
        Err(error) => {
            info!(
                "Managed preflight: cli not asked for {:?} in {}ms",
                bin,
                started.elapsed().as_millis()
            );
            return ManagedProbe::Stale {
                bin,
                reason: unasked_reason(&error),
            };
        }
        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) => {}
    }

    let Some(capability_probe) = capability_probe else {
        info!(
            "Managed preflight: using cached desktop capability for {:?} in {}ms",
            bin,
            started.elapsed().as_millis()
        );
        return ManagedProbe::Ready { bin };
    };

    let capability = match capability_probe {
        Ok(capability) => capability,
        Err(error) => {
            info!(
                "Managed preflight: cli not asked for {:?} in {}ms",
                bin,
                started.elapsed().as_millis()
            );
            return ManagedProbe::Stale {
                bin,
                reason: unasked_reason(&error),
            };
        }
    };
    if let Some(capability) = capability {
        if let Some(fingerprint) = fingerprint_to_cache_under(
            fingerprint_before.as_ref(),
            managed_bin_fingerprint(&bin),
        ) {
            write_cached_capability(fingerprint, &capability);
        }
        if managed_capability_ready(&bin, &capability) {
            info!(
                "Managed preflight: cli ready for {:?} in {}ms",
                bin,
                started.elapsed().as_millis()
            );
            return ManagedProbe::Ready { bin };
        }
        info!(
            "Managed preflight: cli stale for {:?} in {}ms",
            bin,
            started.elapsed().as_millis()
        );
        let reason = managed_capability_stale_reason(&bin, &capability)
            .unwrap_or_else(|| "desktop_capability_incompatible".to_string());
        return ManagedProbe::Stale { bin, reason };
    }

    info!(
        "Managed preflight: desktop capability probe failed for {:?} in {}ms",
        bin,
        started.elapsed().as_millis()
    );
    ManagedProbe::Stale {
        bin,
        reason: working_directory_reason()
            .unwrap_or_else(|| "desktop_capability_probe_failed".to_string()),
    }
}

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,
        // An unreachable profile looks like no install; say which.
        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",
        result,
        started.elapsed().as_millis()
    );
    result
}

pub async fn managed_install_ready() -> bool {
    matches!(probe_managed_install().await, ManagedProbe::Ready { .. })
}

#[cfg(test)]
mod tests {
    use super::super::version::MIN_DESKTOP_BACKEND_VERSION;
    use super::*;

    fn healthy_capability() -> DesktopCapability {
        DesktopCapability {
            desktop_protocol_version: Some(DESKTOP_PROTOCOL_VERSION),
            desktop_manageability_version: Some(DESKTOP_MANAGEABILITY_VERSION),
            supports_api_only: Some(true),
            supports_provision_desktop_auth: Some(true),
            supports_desktop_backend_ownership: Some(true),
            desktop_auth_stale_reason: None,
            studio_install_ok: Some(true),
            studio_install_reason: None,
            llama_runtime_ok: Some(true),
            llama_runtime_reason: None,
            version: Some(MIN_DESKTOP_BACKEND_VERSION.to_string()),
        }
    }

    #[test]
    fn a_feed_ceiling_marker_covers_only_the_release_it_names() {
        let venv = std::env::temp_dir().join(format!(
            "unsloth-feed-ceiling-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let bin = venv.join("bin").join("unsloth");
        fs::create_dir_all(bin.parent().unwrap()).unwrap();
        assert!(!feed_ceiling_holds(&bin, Some("2026.10.3"), "2026.10.6"));

        fs::write(
            venv.join(FEED_CEILING_MARKER),
            r#"{"requested": "2026.10.6", "available": "2026.10.3"}"#,
        )
        .unwrap();
        assert!(feed_ceiling_holds(&bin, Some("2026.10.3"), "2026.10.6"));
        // A newer app wants a newer backend; a backend the update kept above the ceiling is fine.
        assert!(!feed_ceiling_holds(&bin, Some("2026.10.3"), "2026.10.8"));
        assert!(feed_ceiling_holds(&bin, Some("2026.10.4"), "2026.10.6"));
        assert!(!feed_ceiling_holds(&bin, Some("2026.10.2"), "2026.10.6"));
        assert!(!feed_ceiling_holds(&bin, None, "2026.10.6"));

        // It only ever answers "outdated": a backend below the floor is still repaired.
        let mut capability = healthy_capability();
        capability.version = Some("2026.5.2".to_string());
        fs::write(
            venv.join(FEED_CEILING_MARKER),
            r#"{"requested": "2026.8.4", "available": "2026.5.2"}"#,
        )
        .unwrap();
        assert_eq!(
            managed_capability_stale_reason(&bin, &capability).as_deref(),
            Some("desktop_backend_version_too_old")
        );
        assert!(managed_capability_ready(&bin, &healthy_capability()));

        fs::write(venv.join(FEED_CEILING_MARKER), "not json").unwrap();
        assert!(!feed_ceiling_holds(&bin, Some("2026.10.3"), "2026.10.6"));
        let _ = fs::remove_dir_all(&venv);
    }

    #[test]
    fn complete_install_is_ready() {
        assert_eq!(desktop_capability_stale_reason(&healthy_capability()), None);
        assert!(desktop_capability_ready(&healthy_capability()));
    }

    #[test]
    fn a_venv_behind_the_desktop_backend_version_is_stale() {
        let mut capability = healthy_capability();
        capability.version = Some("2026.5.2".to_string());
        assert_eq!(
            desktop_capability_stale_reason(&capability).as_deref(),
            Some("desktop_backend_version_too_old")
        );
        assert!(!desktop_capability_ready(&capability));
    }

    #[test]
    fn incomplete_install_is_stale_with_the_cli_reason() {
        let mut capability = healthy_capability();
        capability.studio_install_ok = Some(false);
        capability.studio_install_reason = Some("studio_install_incomplete".to_string());
        assert_eq!(
            desktop_capability_stale_reason(&capability).as_deref(),
            Some("studio_install_incomplete")
        );
        assert!(!desktop_capability_ready(&capability));
    }

    #[test]
    fn deps_removed_after_install_is_stale() {
        let mut capability = healthy_capability();
        capability.studio_install_ok = Some(false);
        capability.studio_install_reason = Some("studio_deps_missing".to_string());
        assert_eq!(
            desktop_capability_stale_reason(&capability).as_deref(),
            Some("studio_deps_missing")
        );
    }

    #[test]
    fn missing_install_field_falls_back_to_a_generic_reason() {
        let mut capability = healthy_capability();
        capability.studio_install_ok = None;
        capability.studio_install_reason = None;
        assert_eq!(
            desktop_capability_stale_reason(&capability).as_deref(),
            Some("studio_install_incomplete")
        );
    }

    #[test]
    fn a_quarantined_llama_runtime_is_stale() {
        let mut capability = healthy_capability();
        capability.llama_runtime_ok = Some(false);
        capability.llama_runtime_reason = Some("llama_runtime_payload_incomplete".to_string());
        assert_eq!(
            desktop_capability_stale_reason(&capability).as_deref(),
            Some("llama_runtime_payload_incomplete")
        );
        assert!(!desktop_capability_ready(&capability));
    }

    #[test]
    fn a_broken_runtime_without_a_reason_falls_back_to_a_generic_one() {
        let mut capability = healthy_capability();
        capability.llama_runtime_ok = Some(false);
        capability.llama_runtime_reason = Some(String::new());
        assert_eq!(
            desktop_capability_stale_reason(&capability).as_deref(),
            Some("llama_runtime_incomplete")
        );
    }

    #[test]
    fn an_unknown_llama_runtime_is_not_stale() {
        let mut capability = healthy_capability();
        capability.llama_runtime_ok = None;
        capability.llama_runtime_reason = None;
        assert_eq!(desktop_capability_stale_reason(&capability), None);
        assert!(desktop_capability_ready(&capability));
    }

    /// JSON, not a struct literal, to show a missing key deserializes.
    fn pre_pr_capability_json() -> String {
        format!(
            r#"{{
              "desktop_protocol_version": {protocol},
              "desktop_manageability_version": {manageability},
              "supports_api_only": true,
              "supports_provision_desktop_auth": true,
              "supports_desktop_backend_ownership": true,
              "desktop_auth_stale_reason": null,
              "studio_install_ok": true,
              "studio_install_reason": null,
              "version": "{version}"
            }}"#,
            protocol = DESKTOP_PROTOCOL_VERSION,
            manageability = DESKTOP_MANAGEABILITY_VERSION,
            version = MIN_DESKTOP_BACKEND_VERSION,
        )
    }

    #[test]
    fn a_capability_payload_without_the_new_keys_still_parses_and_is_ready() {
        // Old CLIs print neither key; failing here would send every user into repair.
        let capability: DesktopCapability =
            serde_json::from_str(&pre_pr_capability_json()).expect("pre-PR payload must parse");
        assert_eq!(capability.llama_runtime_ok, None);
        assert_eq!(capability.llama_runtime_reason, None);
        assert_eq!(desktop_capability_stale_reason(&capability), None);
        assert!(desktop_capability_ready(&capability));
    }

    #[test]
    fn a_payload_from_a_newer_cli_ignores_keys_this_desktop_does_not_know() {
        // The CLI and shell update separately: unknown keys must be ignored.
        let json = pre_pr_capability_json().replace(
            "\"studio_install_ok\": true,",
            "\"studio_install_ok\": true, \"a_field_from_the_future\": {\"nested\": [1]},",
        );
        let capability: DesktopCapability =
            serde_json::from_str(&json).expect("an unknown key must not be fatal");
        assert!(desktop_capability_ready(&capability));
    }

    #[test]
    fn a_null_llama_runtime_ok_is_not_a_broken_runtime() {
        // Explicit nulls, since the CLI seeds both before trying.
        let json = pre_pr_capability_json().replace(
            "\"studio_install_ok\": true,",
            "\"llama_runtime_ok\": null, \"llama_runtime_reason\": \"\", \"studio_install_ok\": true,",
        );
        let capability: DesktopCapability = serde_json::from_str(&json).unwrap();
        assert_eq!(desktop_capability_stale_reason(&capability), None);
    }

    #[test]
    fn a_broken_runtime_survives_the_json_round_trip() {
        // The frontend switches its message on this exact string.
        let json = pre_pr_capability_json().replace(
            "\"studio_install_ok\": true,",
            "\"llama_runtime_ok\": false, \"llama_runtime_reason\": \"llama_runtime_binaries_missing\", \"studio_install_ok\": true,",
        );
        let capability: DesktopCapability = serde_json::from_str(&json).unwrap();
        assert_eq!(
            desktop_capability_stale_reason(&capability).as_deref(),
            Some("llama_runtime_binaries_missing")
        );
    }

    #[test]
    fn a_cache_file_written_before_this_field_is_ignored_rather_than_fatal() {
        let old = format!(
            r#"{{
              "schema": 3,
              "bin_path": "/managed/unsloth",
              "bin_size": 1,
              "bin_mtime_ms": 1,
              "studio_root_id": null,
              "marker_path": null,
              "marker_size": null,
              "marker_mtime_ms": null,
              "desktop_protocol_version": {protocol},
              "desktop_manageability_version": {manageability},
              "capability": {capability}
            }}"#,
            protocol = DESKTOP_PROTOCOL_VERSION,
            manageability = DESKTOP_MANAGEABILITY_VERSION,
            capability = pre_pr_capability_json(),
        );
        let cache: ManagedCapabilityCache =
            serde_json::from_str(&old).expect("an old cache file must still parse");
        assert_eq!(cache.llama_runtime, None);
        assert_ne!(cache.schema, MANAGED_CAPABILITY_CACHE_SCHEMA);

        let fingerprint = ManagedBinFingerprint {
            bin_path: "/managed/unsloth".to_string(),
            bin_size: 1,
            bin_mtime_ms: 1,
            studio_root_id: None,
            marker_path: None,
            marker_size: None,
            marker_mtime_ms: None,
            llama_runtime: Some("12:345".to_string()),
        };
        assert!(
            !cache_matches(&cache, &fingerprint),
            "a cache from before the runtime was fingerprinted must not be served"
        );
    }

    #[test]
    fn a_quarantined_runtime_file_changes_the_fingerprint() {
        let root = std::env::temp_dir().join(format!(
            "unsloth-llama-fingerprint-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = fs::remove_dir_all(&root);
        let mut bin = root.join("build").join("bin");
        if cfg!(windows) {
            bin = bin.join("Release");
        }
        fs::create_dir_all(&bin).unwrap();
        fs::write(bin.join("llama.dll"), vec![0u8; 1024]).unwrap();
        fs::write(bin.join("ggml-base.dll"), vec![0u8; 2048]).unwrap();

        let intact =
            llama_runtime_fingerprint_at(&root).expect("an installed runtime must fingerprint");
        assert_eq!(
            intact,
            llama_runtime_fingerprint_at(&root).unwrap(),
            "the same tree must fingerprint the same twice, or every launch misses its own cache"
        );

        fs::remove_file(bin.join("ggml-base.dll")).unwrap();
        let quarantined = llama_runtime_fingerprint_at(&root).unwrap();
        assert_ne!(intact, quarantined);

        fs::create_dir(bin.join("some-subdir")).unwrap();
        assert_eq!(quarantined, llama_runtime_fingerprint_at(&root).unwrap());

        fs::write(bin.join("llama.dll"), vec![0u8; 4096]).unwrap();
        assert_ne!(quarantined, llama_runtime_fingerprint_at(&root).unwrap());

        fs::remove_dir_all(&root).unwrap();
        assert_eq!(llama_runtime_fingerprint_at(&root), None);
        fs::create_dir_all(&bin).unwrap();
        assert_eq!(
            llama_runtime_fingerprint_at(&root).as_deref(),
            Some("bin:0:0:0:0:0|root:-,-")
        );

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn a_marker_left_over_a_missing_build_dir_changes_the_fingerprint() {
        let root = std::env::temp_dir().join(format!(
            "unsloth-llama-nobin-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = fs::remove_dir_all(&root);

        assert_eq!(
            llama_runtime_fingerprint_at(&root),
            None,
            "no tree at all is the NotInstalled case, and stays None"
        );

        fs::create_dir_all(&root).unwrap();
        let empty_tree = llama_runtime_fingerprint_at(&root);
        assert!(
            empty_tree.is_some(),
            "a runtime root with no build/bin is a broken install, not an absent one"
        );

        fs::write(root.join("unsloth_llama_prebuilt.json"), b"{}").unwrap();
        assert_ne!(
            empty_tree,
            llama_runtime_fingerprint_at(&root),
            "a marker arriving over a missing build/bin must invalidate the cached Ready"
        );

        let mut bin = root.join("build").join("bin");
        if cfg!(windows) {
            bin = bin.join("Release");
        }
        fs::create_dir_all(&bin).unwrap();
        assert_ne!(
            llama_runtime_fingerprint_at(&root),
            empty_tree,
            "an empty binary directory is not the same state as a missing one"
        );

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn the_runtime_override_is_resolved_the_way_python_resolves_it() {
        let home = PathBuf::from(if cfg!(windows) {
            "C:\\Users\\me"
        } else {
            "/home/me"
        });
        let cwd = PathBuf::from(if cfg!(windows) { "C:\\work" } else { "/work" });
        let absolute = if cfg!(windows) {
            "C:\\opt\\llama.cpp"
        } else {
            "/opt/llama.cpp"
        };
        let cases: Vec<(Option<&str>, Option<PathBuf>)> = vec![
            (None, None),
            (Some(""), None),
            (Some("   "), None),
            (Some("~"), Some(home.clone())),
            (Some("~/llama.cpp"), Some(home.join("llama.cpp"))),
            (Some("  ~/llama.cpp  "), Some(home.join("llama.cpp"))),
            (Some(absolute), Some(PathBuf::from(absolute))),
            (
                Some("~someone/llama.cpp"),
                Some(cwd.join("~someone/llama.cpp")),
            ),
            (Some("llama.cpp"), Some(cwd.join("llama.cpp"))),
            (Some("./llama.cpp"), Some(cwd.join("./llama.cpp"))),
            (Some("../llama.cpp"), Some(cwd.join("../llama.cpp"))),
        ];
        for (value, expected) in cases {
            assert_eq!(
                llama_runtime_override_from(value, Some(&home), Some(&cwd)),
                expected,
                "value {value:?}"
            );
        }
    }

    #[test]
    fn an_override_that_cannot_be_anchored_is_dropped_rather_than_guessed() {
        assert_eq!(llama_runtime_override_from(Some("~/x"), None, None), None);
        assert_eq!(llama_runtime_override_from(Some("x"), None, None), None);
        let absolute = if cfg!(windows) {
            "C:\\opt\\llama.cpp"
        } else {
            "/opt/llama.cpp"
        };
        assert_eq!(
            llama_runtime_override_from(Some(absolute), None, None),
            Some(PathBuf::from(absolute))
        );
    }

    #[cfg(windows)]
    #[test]
    fn the_windows_tilde_resolves_through_the_same_profile_the_child_uses() {
        let _guard = crate::native_path_policy::PROCESS_ENV_LOCK.lock();
        let previous = std::env::var_os("USERPROFILE");
        std::env::set_var("USERPROFILE", "C:\\Portable\\Profile");
        let resolved = tilde_home();
        match previous {
            Some(value) => std::env::set_var("USERPROFILE", value),
            None => std::env::remove_var("USERPROFILE"),
        }
        assert_eq!(resolved, Some(PathBuf::from("C:\\Portable\\Profile")));
    }

    #[test]
    fn older_cli_is_rejected_on_manageability_before_the_install_check() {
        let mut capability = healthy_capability();
        capability.desktop_manageability_version = Some(1);
        capability.studio_install_ok = None;
        assert_eq!(
            desktop_capability_stale_reason(&capability).as_deref(),
            Some("desktop_manageability_unsupported")
        );
    }

    #[test]
    fn a_stale_capability_is_never_served_from_cache() {
        // write_cached_capability runs before the ready check, so incomplete installs do get cached.
        let mut capability = healthy_capability();
        capability.studio_install_ok = Some(false);
        let cache = ManagedCapabilityCache {
            schema: MANAGED_CAPABILITY_CACHE_SCHEMA,
            bin_path: "/managed/unsloth".to_string(),
            bin_size: 1,
            bin_mtime_ms: 1,
            studio_root_id: None,
            marker_path: None,
            marker_size: None,
            marker_mtime_ms: None,
            llama_runtime: None,
            desktop_protocol_version: DESKTOP_PROTOCOL_VERSION,
            desktop_manageability_version: DESKTOP_MANAGEABILITY_VERSION,
            capability,
        };
        let fingerprint = ManagedBinFingerprint {
            bin_path: "/managed/unsloth".to_string(),
            bin_size: 1,
            bin_mtime_ms: 1,
            studio_root_id: None,
            marker_path: None,
            marker_size: None,
            marker_mtime_ms: None,
            llama_runtime: None,
        };
        assert!(!cache_matches(&cache, &fingerprint));
    }

    #[cfg(windows)]
    #[test]
    fn a_quarantined_launcher_is_fingerprinted_through_its_interpreter() {
        let venv = std::env::temp_dir().join(format!(
            "unsloth-fingerprint-quarantined-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let scripts = venv.join("Scripts");
        fs::create_dir_all(&scripts).unwrap();
        let bin = scripts.join("unsloth.exe");
        let interpreter = scripts.join("python.exe");
        fs::write(&interpreter, "python").unwrap();
        assert!(!bin.exists(), "this case is about the launcher being gone");

        let fingerprint = managed_bin_fingerprint(&bin)
            .expect("a stubless venv must still fingerprint, through python.exe");
        assert!(fingerprint.bin_path.ends_with("unsloth.exe"));
        fs::write(&interpreter, "python-after-an-update").unwrap();
        let after = managed_bin_fingerprint(&bin).unwrap();
        assert_ne!(fingerprint.bin_size, after.bin_size);

        fs::remove_file(&interpreter).unwrap();
        assert!(managed_bin_fingerprint(&bin).is_none());

        let _ = fs::remove_dir_all(&venv);
    }

    #[test]
    fn dropping_the_manifest_changes_the_fingerprint() {
        let venv = std::env::temp_dir().join(format!(
            "unsloth-fingerprint-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let scripts = venv.join("bin");
        fs::create_dir_all(&scripts).unwrap();
        let bin = scripts.join("unsloth");
        fs::write(&bin, "#!/bin/sh\nexit 0\n").unwrap();
        let manifest = venv.join("unsloth_install_manifest.json");
        fs::write(&manifest, "{}").unwrap();

        let with_manifest = managed_bin_fingerprint(&bin).unwrap();
        fs::remove_file(&manifest).unwrap();
        let without_manifest = managed_bin_fingerprint(&bin).unwrap();

        assert_ne!(with_manifest, without_manifest);
        let _ = fs::remove_dir_all(&venv);
    }

    fn cache_for(fingerprint: &ManagedBinFingerprint) -> ManagedCapabilityCache {
        ManagedCapabilityCache {
            schema: MANAGED_CAPABILITY_CACHE_SCHEMA,
            bin_path: fingerprint.bin_path.clone(),
            bin_size: fingerprint.bin_size,
            bin_mtime_ms: fingerprint.bin_mtime_ms,
            studio_root_id: fingerprint.studio_root_id.clone(),
            marker_path: fingerprint.marker_path.clone(),
            marker_size: fingerprint.marker_size,
            marker_mtime_ms: fingerprint.marker_mtime_ms,
            llama_runtime: fingerprint.llama_runtime.clone(),
            desktop_protocol_version: DESKTOP_PROTOCOL_VERSION,
            desktop_manageability_version: DESKTOP_MANAGEABILITY_VERSION,
            capability: healthy_capability(),
        }
    }

    #[test]
    fn losing_a_studio_package_changes_the_fingerprint() {
        let venv = std::env::temp_dir().join(format!(
            "unsloth-fingerprint-deps-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = fs::remove_dir_all(&venv);
        let scripts = venv.join("bin");
        fs::create_dir_all(&scripts).unwrap();
        let bin = scripts.join("unsloth");
        fs::write(&bin, "#!/bin/sh\nexit 0\n").unwrap();
        fs::write(venv.join("pyvenv.cfg"), "home = /usr/bin\n").unwrap();
        fs::write(venv.join("unsloth_install_manifest.json"), "{}").unwrap();

        // site_packages_dirs() uses Lib/site-packages on Windows.
        let site_packages = if cfg!(windows) {
            venv.join("Lib").join("site-packages")
        } else {
            venv.join("lib").join("python3.11").join("site-packages")
        };
        fs::create_dir_all(site_packages.join("unsloth_cli").join("commands")).unwrap();
        fs::write(
            site_packages
                .join("unsloth_cli")
                .join("commands")
                .join("studio.py"),
            "# cli\n",
        )
        .unwrap();
        let dist_info = site_packages.join("fastmcp-3.0.2.dist-info");
        fs::create_dir_all(&dist_info).unwrap();
        fs::write(dist_info.join("METADATA"), "Name: fastmcp\n").unwrap();

        let with_dep = managed_bin_fingerprint(&bin).unwrap();
        let healthy_cache = cache_for(&with_dep);
        assert_eq!(with_dep, managed_bin_fingerprint(&bin).unwrap());
        assert!(cache_matches(&healthy_cache, &with_dep));

        fs::remove_dir_all(&dist_info).unwrap();
        let without_dep = managed_bin_fingerprint(&bin).unwrap();

        assert_ne!(with_dep, without_dep);
        assert!(
            !cache_matches(&healthy_cache, &without_dep),
            "a removed studio package must not keep serving the cached Ready answer"
        );
        let _ = fs::remove_dir_all(&venv);
    }

    #[test]
    fn a_busy_runtime_gate_is_not_a_broken_install() {
        let busy = probe_spawn_error(crate::process::STUDIO_RUNTIME_GATE_BUSY.to_string());
        assert_eq!(busy, MANAGED_ENVIRONMENT_BUSY);
        assert_eq!(unasked_reason(&busy), MANAGED_ENVIRONMENT_BUSY);
        assert!(blocks_auto_repair(&busy));
        assert!(!is_context_reason(&busy));

        let spawn_failure = probe_spawn_error("No such file or directory".to_string());
        assert_eq!(spawn_failure, "No such file or directory");
        assert!(!blocks_auto_repair("cli_unusable"));
        assert!(blocks_auto_repair(WORKING_DIRECTORY_UNAVAILABLE));
    }

    #[test]
    fn a_context_reason_names_the_setting_it_could_not_preserve() {
        use crate::process::ManagedContextError;
        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));
        assert!(!reason.contains("cannot resolve"));
        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"));
    }

    /// Per process+thread: tests walk real files in parallel and would delete each other's trees.
    fn scratch_dir(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "unsloth-managed-{name}-{}-{:?}",
            std::process::id(),
            std::thread::current().id()
        ));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// The one directory llama_runtime_fingerprint_at walks, kept in one place so
    /// the tests and the walk cannot drift apart on the Windows-only Release level.
    fn runtime_bin_dir(root: &Path) -> PathBuf {
        let bin = root.join("build").join("bin");
        if cfg!(windows) {
            bin.join("Release")
        } else {
            bin
        }
    }

    /// The names half of an expected fingerprint.
    fn names_sum(names: &[&str]) -> u64 {
        names.iter().fold(0u64, |acc, name| {
            acc.wrapping_add(name_hash(std::ffi::OsStr::new(name)))
        })
    }

    fn server_file_name() -> &'static str {
        if cfg!(windows) {
            "llama-server.exe"
        } else {
            "llama-server"
        }
    }

    fn install_fake_runtime(root: &Path) -> PathBuf {
        let bin = runtime_bin_dir(root);
        fs::create_dir_all(&bin).unwrap();
        let server = bin.join("llama-server");
        fs::write(&server, vec![0u8; 4096]).unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut mode = fs::metadata(&server).unwrap().permissions();
            mode.set_mode(0o755);
            fs::set_permissions(&server, mode).unwrap();
        }
        let library = bin.join("libggml-base.so");
        fs::write(&library, vec![0u8; 2048]).unwrap();
        // Explicit mode: permission bits are fingerprinted, so umask must not matter.
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut mode = fs::metadata(&library).unwrap().permissions();
            mode.set_mode(0o644);
            fs::set_permissions(&library, mode).unwrap();
        }
        bin
    }

    /// Built directly to keep UNSLOTH_TEST_LLAMA_RUNTIME_ROOT out of parallel tests.
    fn fingerprint_for_runtime(runtime_root: &Path) -> ManagedBinFingerprint {
        ManagedBinFingerprint {
            bin_path: "/managed/unsloth".to_string(),
            bin_size: 42,
            bin_mtime_ms: 1_700_000_000_000,
            studio_root_id: None,
            marker_path: None,
            marker_size: None,
            marker_mtime_ms: None,
            llama_runtime: llama_runtime_fingerprint_at(runtime_root),
        }
    }

    /// Points capability_cache_path() at a per-test dir; holds PROCESS_ENV_LOCK since the hook is
    /// process-wide.
    struct CapabilityCacheHome {
        home: PathBuf,
        previous: Option<std::ffi::OsString>,
        /// Declared last so it is released after the restore below has run.
        _env: std::sync::MutexGuard<'static, ()>,
    }

    impl CapabilityCacheHome {
        fn new(test_name: &str) -> Self {
            let _env = crate::native_path_policy::PROCESS_ENV_LOCK
                .lock()
                .unwrap_or_else(|poisoned| poisoned.into_inner());
            let home = std::env::temp_dir().join(format!(
                "unsloth-managed-cache-{test_name}-{}-{:?}",
                std::process::id(),
                std::thread::current().id()
            ));
            let _ = fs::remove_dir_all(&home);
            fs::create_dir_all(&home).unwrap();
            let previous = std::env::var_os("UNSLOTH_TEST_DESKTOP_CAPABILITY_CACHE_HOME");
            std::env::set_var("UNSLOTH_TEST_DESKTOP_CAPABILITY_CACHE_HOME", &home);
            Self {
                home,
                previous,
                _env,
            }
        }

        fn cache_file(&self) -> PathBuf {
            let path = capability_cache_path().expect("the test hook must resolve a cache path");
            assert!(
                path.starts_with(&self.home),
                "the hook must resolve inside this test's home, not the real one: {path:?}"
            );
            path
        }
    }

    impl Drop for CapabilityCacheHome {
        fn drop(&mut self) {
            match &self.previous {
                Some(previous) => {
                    std::env::set_var("UNSLOTH_TEST_DESKTOP_CAPABILITY_CACHE_HOME", previous)
                }
                None => std::env::remove_var("UNSLOTH_TEST_DESKTOP_CAPABILITY_CACHE_HOME"),
            }
            let _ = fs::remove_dir_all(&self.home);
        }
    }

    #[test]
    fn an_unchanged_runtime_serves_the_cached_capability_back_from_disk() {
        let home = CapabilityCacheHome::new("hit");
        let root = scratch_dir("runtime-hit");
        install_fake_runtime(&root);

        let fingerprint = fingerprint_for_runtime(&root);
        assert!(
            read_cached_capability(&fingerprint).is_none(),
            "nothing is cached yet, so the first launch must miss"
        );
        write_cached_capability(&fingerprint, &healthy_capability());
        assert!(
            home.cache_file().exists(),
            "the cache must reach disk, not just the struct"
        );

        let relaunch = fingerprint_for_runtime(&root);
        let cached = read_cached_capability(&relaunch)
            .expect("an install nothing touched must hit its own cache");
        assert_eq!(cached.llama_runtime_ok, Some(true));
        assert!(desktop_capability_ready(&cached));

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn a_file_quarantined_out_of_the_runtime_misses_the_cache() {
        let home = CapabilityCacheHome::new("quarantine");
        let root = scratch_dir("runtime-quarantine");
        let bin = install_fake_runtime(&root);

        let healthy = fingerprint_for_runtime(&root);
        write_cached_capability(&healthy, &healthy_capability());
        assert!(read_cached_capability(&healthy).is_some());

        fs::remove_file(bin.join("libggml-base.so")).unwrap();
        let quarantined = fingerprint_for_runtime(&root);
        assert_ne!(healthy.llama_runtime, quarantined.llama_runtime);
        assert!(
            read_cached_capability(&quarantined).is_none(),
            "a quarantined runtime file must not keep serving a cached Ready"
        );
        assert!(home.cache_file().exists());

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn a_file_added_to_the_runtime_misses_the_cache() {
        let _home = CapabilityCacheHome::new("added");
        let root = scratch_dir("runtime-added");
        let bin = install_fake_runtime(&root);

        let before = fingerprint_for_runtime(&root);
        write_cached_capability(&before, &healthy_capability());

        fs::write(bin.join("llama-quantize"), vec![0u8; 512]).unwrap();
        let after = fingerprint_for_runtime(&root);
        assert!(
            read_cached_capability(&after).is_none(),
            "a runtime that gained a file must be asked about again"
        );

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn a_runtime_directory_that_is_gone_entirely_misses_the_cache() {
        let _home = CapabilityCacheHome::new("removed");
        let root = scratch_dir("runtime-removed");
        install_fake_runtime(&root);

        let installed = fingerprint_for_runtime(&root);
        write_cached_capability(&installed, &healthy_capability());

        fs::remove_dir_all(&root).unwrap();
        let gone = fingerprint_for_runtime(&root);
        assert_eq!(gone.llama_runtime, None);
        assert!(
            read_cached_capability(&gone).is_none(),
            "a runtime that was removed must not be served the entry it had while installed"
        );
    }

    #[test]
    fn an_install_with_no_runtime_at_all_still_hits_its_cache() {
        let _home = CapabilityCacheHome::new("no-runtime");
        let parent = scratch_dir("runtime-absent");
        let root = parent.join("never-installed");

        let without = fingerprint_for_runtime(&root);
        assert_eq!(without.llama_runtime, None);
        write_cached_capability(&without, &healthy_capability());
        assert!(
            read_cached_capability(&fingerprint_for_runtime(&root)).is_some(),
            "an install with no runtime must not miss its own cache every launch"
        );

        install_fake_runtime(&root);
        let with = fingerprint_for_runtime(&root);
        assert!(with.llama_runtime.is_some());
        assert!(
            read_cached_capability(&with).is_none(),
            "a runtime installed after the cache was written must be probed"
        );

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn a_cached_capability_that_is_itself_broken_is_never_served() {
        let home = CapabilityCacheHome::new("broken");
        let root = scratch_dir("runtime-broken");
        install_fake_runtime(&root);

        let fingerprint = fingerprint_for_runtime(&root);
        let mut capability = healthy_capability();
        capability.llama_runtime_ok = Some(false);
        capability.llama_runtime_reason = Some("llama_runtime_payload_incomplete".to_string());
        write_cached_capability(&fingerprint, &capability);

        let raw =
            fs::read(home.cache_file()).expect("the broken verdict is written like any other");
        assert!(String::from_utf8_lossy(&raw).contains("llama_runtime_payload_incomplete"));
        assert!(
            read_cached_capability(&fingerprint).is_none(),
            "a broken runtime must be re-probed even when nothing on disk moved"
        );

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn a_runtime_verdict_the_cli_skipped_is_never_cached() {
        let home = CapabilityCacheHome::new("skipped-verdict");
        let root = scratch_dir("runtime-skipped-verdict");
        install_fake_runtime(&root);
        let fingerprint = fingerprint_for_runtime(&root);

        let mut skipped = healthy_capability();
        skipped.llama_runtime_ok = None;
        skipped.llama_runtime_reason = Some(LLAMA_RUNTIME_NOT_MANAGED.to_string());
        assert!(desktop_capability_ready(&skipped));
        write_cached_capability(&fingerprint, &skipped);
        assert!(
            !home.cache_file().exists(),
            "a verdict that was never reached must not reach the cache"
        );
        assert!(read_cached_capability(&fingerprint).is_none());

        let mut not_installed = healthy_capability();
        not_installed.llama_runtime_ok = None;
        not_installed.llama_runtime_reason = Some(String::new());
        write_cached_capability(&fingerprint, &not_installed);
        assert!(
            read_cached_capability(&fingerprint).is_some(),
            "only the skipped verdict is uncacheable, or every launch pays a probe"
        );

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn a_verdict_is_only_cached_against_the_tree_the_probe_read() {
        let parent = scratch_dir("verdict-snapshot");
        let root = parent.join("llama.cpp");
        install_fake_runtime(&root);
        let before = fingerprint_for_runtime(&root);

        assert_eq!(
            fingerprint_to_cache_under(Some(&before), Some(fingerprint_for_runtime(&root))),
            Some(&before),
            "an unchanged tree is what the answer describes, so it is cacheable"
        );

        fs::remove_file(runtime_bin_dir(&root).join("libggml-base.so")).unwrap();
        assert_eq!(
            fingerprint_to_cache_under(Some(&before), Some(fingerprint_for_runtime(&root))),
            None,
            "a verdict about a tree that no longer exists must not be kept"
        );
        assert_eq!(fingerprint_to_cache_under(Some(&before), None), None);
        assert_eq!(fingerprint_to_cache_under(None, Some(before)), None);

        let _ = fs::remove_dir_all(&parent);
    }

    #[test]
    fn a_runtime_probe_that_raised_is_never_cached_either() {
        let home = CapabilityCacheHome::new("probe-failed-verdict");
        let root = scratch_dir("runtime-probe-failed");
        install_fake_runtime(&root);
        let fingerprint = fingerprint_for_runtime(&root);

        let mut failed = healthy_capability();
        failed.llama_runtime_ok = None;
        failed.llama_runtime_reason = Some(LLAMA_RUNTIME_PROBE_FAILED.to_string());
        assert!(desktop_capability_ready(&failed), "still Ready: this is about the cache");
        write_cached_capability(&fingerprint, &failed);
        assert!(
            !home.cache_file().exists(),
            "an attempt that raised must not freeze a Ready over a damaged tree"
        );
        assert!(read_cached_capability(&fingerprint).is_none());

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn a_named_windows_profile_resolves_where_the_child_will_look() {
        // Same cases as process.rs's own test, so the two readers cannot drift.
        let home = Path::new("C:\\Users\\me");
        assert_eq!(
            named_windows_user_home("~other\\llama.cpp", home, Some("me")),
            Some(PathBuf::from("C:\\Users\\other\\llama.cpp")),
        );
        assert_eq!(
            named_windows_user_home("~other/llama.cpp", home, Some("me")),
            Some(PathBuf::from("C:\\Users\\other/llama.cpp")),
        );
        assert_eq!(
            named_windows_user_home("~me\\llama.cpp", home, Some("me")),
            Some(PathBuf::from("C:\\Users\\me\\llama.cpp")),
        );
        assert_eq!(
            named_windows_user_home("~other", home, Some("me")),
            Some(PathBuf::from("C:\\Users\\other")),
        );
        assert_eq!(
            named_windows_user_home("~other\\llama.cpp", Path::new("C:\\Users\\me.DOMAIN"), Some("me")),
            None,
        );
        assert_eq!(named_windows_user_home("~other\\llama.cpp", home, None), None);
        assert_eq!(named_windows_user_home("~", home, Some("me")), None);
        assert_eq!(named_windows_user_home("~\\llama.cpp", home, Some("me")), None);
    }

    #[test]
    fn a_schema_three_cache_file_on_disk_misses_and_is_rewritten_as_schema_four() {
        let home = CapabilityCacheHome::new("schema-three");
        let root = scratch_dir("runtime-schema-three");
        install_fake_runtime(&root);
        let fingerprint = fingerprint_for_runtime(&root);

        let path = home.cache_file();
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        let previous_release = format!(
            r#"{{
  "schema": 3,
  "bin_path": "{bin_path}",
  "bin_size": {bin_size},
  "bin_mtime_ms": {bin_mtime_ms},
  "studio_root_id": null,
  "marker_path": null,
  "marker_size": null,
  "marker_mtime_ms": null,
  "desktop_protocol_version": {protocol},
  "desktop_manageability_version": {manageability},
  "capability": {capability}
}}"#,
            bin_path = fingerprint.bin_path,
            bin_size = fingerprint.bin_size,
            bin_mtime_ms = fingerprint.bin_mtime_ms,
            protocol = DESKTOP_PROTOCOL_VERSION,
            manageability = DESKTOP_MANAGEABILITY_VERSION,
            capability = pre_pr_capability_json(),
        );
        fs::write(&path, previous_release).unwrap();
        assert!(
            read_cached_capability(&fingerprint).is_none(),
            "a schema 3 entry reached Ready without ever looking at the runtime"
        );

        write_cached_capability(&fingerprint, &healthy_capability());
        let rewritten: serde_json::Value =
            serde_json::from_slice(&fs::read(&path).unwrap()).expect("the rewrite must be JSON");
        assert_eq!(
            rewritten["schema"].as_u64(),
            Some(u64::from(MANAGED_CAPABILITY_CACHE_SCHEMA))
        );
        assert_eq!(
            rewritten["llama_runtime"].as_str(),
            fingerprint.llama_runtime.as_deref(),
            "the rewritten entry must carry the runtime the old one had no room for"
        );
        assert!(
            read_cached_capability(&fingerprint).is_some(),
            "the replacement entry must then hit, or the upgrade never stops re-probing"
        );

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn files_below_the_binary_directory_are_not_walked() {
        let root = scratch_dir("runtime-nested");
        let bin = install_fake_runtime(&root);
        let flat = llama_runtime_fingerprint_at(&root).unwrap();

        let nested = bin.join("vendor").join("deep");
        fs::create_dir_all(&nested).unwrap();
        fs::write(nested.join("payload.bin"), vec![0u8; 8192]).unwrap();
        assert_eq!(
            flat,
            llama_runtime_fingerprint_at(&root).unwrap(),
            "a subdirectory and its contents are not part of the runtime fingerprint"
        );

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn a_replacement_of_the_same_size_is_a_collision_this_fingerprint_does_not_catch() {
        // Count and byte total only: an in-place same-length rewrite is invisible, accepted.
        let root = scratch_dir("runtime-collision");
        let bin = install_fake_runtime(&root);
        let original = llama_runtime_fingerprint_at(&root).unwrap();

        fs::write(bin.join("llama-server"), vec![0xABu8; 4096]).unwrap();
        assert_eq!(
            original,
            llama_runtime_fingerprint_at(&root).unwrap(),
            "same count and same bytes is a collision, and this asserts it honestly"
        );

        fs::write(bin.join("llama-server"), vec![0u8; 4097]).unwrap();
        assert_ne!(
            original,
            llama_runtime_fingerprint_at(&root).unwrap(),
            "one byte of size difference must still invalidate"
        );

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn a_root_entrypoint_is_part_of_the_fingerprint() {
        let root = scratch_dir("runtime-root-entrypoint");
        install_fake_runtime(&root);
        let without = llama_runtime_fingerprint_at(&root).unwrap();

        let wrapper = root.join(if cfg!(windows) {
            "llama-server.exe"
        } else {
            "llama-server"
        });
        fs::write(&wrapper, b"#!/bin/sh\n").unwrap();
        let with_wrapper = llama_runtime_fingerprint_at(&root).unwrap();
        assert_ne!(without, with_wrapper, "a root entrypoint appearing must invalidate");

        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut mode = fs::metadata(&wrapper).unwrap().permissions();
            mode.set_mode(0o755);
            fs::set_permissions(&wrapper, mode).unwrap();
            let executable = llama_runtime_fingerprint_at(&root).unwrap();
            assert_ne!(with_wrapper, executable, "the wrapper's mode is graded, so watch it");

            mode = fs::metadata(&wrapper).unwrap().permissions();
            mode.set_mode(0o644);
            fs::set_permissions(&wrapper, mode).unwrap();
            assert_eq!(
                with_wrapper,
                llama_runtime_fingerprint_at(&root).unwrap(),
                "and the same tree must fingerprint the same both times"
            );
        }

        fs::remove_file(&wrapper).unwrap();
        assert_eq!(
            without,
            llama_runtime_fingerprint_at(&root).unwrap(),
            "an absent root entrypoint is the state a plain build/bin install is in"
        );

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn renaming_a_runtime_file_in_place_moves_the_fingerprint() {
        let root = scratch_dir("runtime-renamed-in-place");
        let bin = install_fake_runtime(&root);

        let intact = llama_runtime_fingerprint_at(&root).unwrap();
        fs::rename(
            bin.join("libggml-base.so"),
            bin.join("libggml-base.so.quarantine"),
        )
        .unwrap();
        let renamed = llama_runtime_fingerprint_at(&root).unwrap();
        assert_ne!(
            intact, renamed,
            "a required library renamed in place must not fingerprint as the healthy tree"
        );
        // The root segment is dropped first: it carries its own colons.
        let counters = |value: &str| {
            value.split_once('|').unwrap().0.rsplit_once(':').unwrap().0.to_string()
        };
        assert_eq!(counters(&intact), counters(&renamed));

        fs::rename(
            bin.join("libggml-base.so.quarantine"),
            bin.join("libggml-base.so"),
        )
        .unwrap();
        assert_eq!(intact, llama_runtime_fingerprint_at(&root).unwrap());

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn a_runtime_root_that_is_a_file_fingerprints_as_no_runtime() {
        let parent = scratch_dir("runtime-is-a-file");
        let root = parent.join("llama.cpp");
        fs::write(&root, "not a directory").unwrap();
        assert_eq!(llama_runtime_fingerprint_at(&root), None);
        let _ = fs::remove_dir_all(&parent);
    }

    #[test]
    fn a_runtime_path_with_spaces_and_non_ascii_fingerprints_normally() {
        let parent = scratch_dir("runtime-unicode");
        let root = parent.join("Мой каталог ünïcode llama.cpp");
        install_fake_runtime(&root);
        assert_eq!(
            llama_runtime_fingerprint_at(&root).as_deref(),
            Some(
                format!(
                    "bin:2:6144:0:{}:{}|root:-,-",
                    if cfg!(unix) { 913 } else { 0 },
                    names_sum(&["llama-server", "libggml-base.so"])
                )
                .as_str()
            )
        );
        let _ = fs::remove_dir_all(&parent);
    }

    #[test]
    fn the_runtime_fingerprint_does_not_depend_on_directory_order() {
        let parent = scratch_dir("runtime-order");
        let names = ["llama-server", "libggml.so", "llama-cli", "libmtmd.so"];

        let forwards = parent.join("forwards");
        let forwards_bin = runtime_bin_dir(&forwards);
        fs::create_dir_all(&forwards_bin).unwrap();
        for (index, name) in names.iter().enumerate() {
            fs::write(forwards_bin.join(name), vec![0u8; 100 + index]).unwrap();
        }

        let backwards = parent.join("backwards");
        let backwards_bin = runtime_bin_dir(&backwards);
        fs::create_dir_all(&backwards_bin).unwrap();
        for (index, name) in names.iter().enumerate().rev() {
            fs::write(backwards_bin.join(name), vec![0u8; 100 + index]).unwrap();
        }

        assert_eq!(
            llama_runtime_fingerprint_at(&forwards),
            llama_runtime_fingerprint_at(&backwards)
        );
        let _ = fs::remove_dir_all(&parent);
    }

    #[test]
    fn a_large_runtime_directory_fingerprints_fast_enough_for_the_launch_path() {
        // Loose bound: catches a walk that reads contents or recurses, without flaking.
        let root = scratch_dir("runtime-large");
        let bin = runtime_bin_dir(&root);
        fs::create_dir_all(&bin).unwrap();
        for index in 0..5000 {
            let artifact = bin.join(format!("artifact-{index:05}.o"));
            fs::write(&artifact, [0u8; 1]).unwrap();
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mut mode = fs::metadata(&artifact).unwrap().permissions();
                mode.set_mode(0o644);
                fs::set_permissions(&artifact, mode).unwrap();
            }
        }

        let started = Instant::now();
        let fingerprint = llama_runtime_fingerprint_at(&root);
        let elapsed = started.elapsed();
        assert_eq!(
            fingerprint.as_deref(),
            Some(
                format!(
                    "bin:5000:5000:0:{}:{}|root:-,-",
                    if cfg!(unix) { 2100000 } else { 0 },
                    names_sum(
                        &(0..5000)
                            .map(|index| format!("artifact-{index:05}.o"))
                            .collect::<Vec<_>>()
                            .iter()
                            .map(String::as_str)
                            .collect::<Vec<_>>()
                    )
                )
                .as_str()
            )
        );
        assert!(
            elapsed < Duration::from_secs(2),
            "5000 files took {elapsed:?}, which is too much to spend before the window opens"
        );

        let _ = fs::remove_dir_all(&root);
    }

    #[cfg(unix)]
    #[test]
    fn a_symlinked_runtime_root_fingerprints_the_tree_it_points_at() {
        let parent = scratch_dir("runtime-symlinked-root");
        let real = parent.join("real");
        let bin = install_fake_runtime(&real);
        let linked = parent.join("linked");
        std::os::unix::fs::symlink(&real, &linked).unwrap();

        assert_eq!(
            llama_runtime_fingerprint_at(&real),
            llama_runtime_fingerprint_at(&linked),
            "a symlinked root must see the same tree, or an override written that way is not covered"
        );
        fs::remove_file(bin.join("libggml-base.so")).unwrap();
        assert_eq!(
            llama_runtime_fingerprint_at(&linked).as_deref(),
            Some(
                format!(
                    "bin:1:4096:0:{}:{}|root:-,-",
                    if cfg!(unix) { 493 } else { 0 },
                    names_sum(&["llama-server"])
                )
                .as_str()
            )
        );

        let _ = fs::remove_dir_all(&parent);
    }

    #[cfg(unix)]
    #[test]
    fn a_symlinked_file_inside_the_runtime_is_counted_and_its_loss_is_seen() {
        let parent = scratch_dir("runtime-symlinked-file");
        let root = parent.join("llama.cpp");
        let bin = install_fake_runtime(&root);
        let before = llama_runtime_fingerprint_at(&root).unwrap();

        std::os::unix::fs::symlink(bin.join("llama-server"), bin.join("llama-cli")).unwrap();
        let with_link = llama_runtime_fingerprint_at(&root).unwrap();
        assert_ne!(
            before, with_link,
            "a link beside the binaries has to move the fingerprint"
        );
        fs::remove_file(bin.join("llama-cli")).unwrap();
        assert_eq!(before, llama_runtime_fingerprint_at(&root).unwrap());

        let _ = fs::remove_dir_all(&parent);
    }

    #[test]
    fn an_installer_managed_venv_names_its_own_runtime() {
        let root = scratch_dir("inferred-studio-home");
        let bin = root.join("unsloth_studio").join("bin").join("unsloth");
        fs::create_dir_all(bin.parent().unwrap()).unwrap();
        fs::write(&bin, b"launcher").unwrap();

        assert_eq!(inferred_studio_llama_root(&bin), None);

        fs::create_dir_all(root.join("share")).unwrap();
        fs::write(root.join("share").join("studio.conf"), b"managed").unwrap();
        assert_eq!(
            inferred_studio_llama_root(&bin),
            Some(root.join("llama.cpp")),
            "an installer-managed root names the runtime beside it"
        );

        let loose = root.join("some_venv").join("bin").join("unsloth");
        fs::create_dir_all(loose.parent().unwrap()).unwrap();
        fs::write(&loose, b"launcher").unwrap();
        assert_eq!(inferred_studio_llama_root(&loose), None);

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn a_recorded_master_root_names_the_runtime_beside_studio() {
        let master = scratch_dir("master-root-runtime");
        let studio = master.join("studio");
        let bin = studio.join("unsloth_studio").join("bin").join("unsloth");
        fs::create_dir_all(bin.parent().unwrap()).unwrap();
        fs::write(&bin, b"launcher").unwrap();
        fs::create_dir_all(studio.join("share")).unwrap();
        fs::write(studio.join("share").join("studio.conf"), b"managed").unwrap();

        assert_eq!(
            inferred_studio_llama_root(&bin),
            Some(studio.join("llama.cpp"))
        );

        fs::write(
            studio.join("share").join(".unsloth-master-root"),
            master.to_string_lossy().as_bytes(),
        )
        .unwrap();
        let expected = master.canonicalize().unwrap_or_else(|_| master.clone());
        assert_eq!(
            inferred_studio_llama_root(&bin),
            Some(expected.join("llama.cpp")),
            "the recorded master root names the runtime beside studio/"
        );

        let elsewhere = scratch_dir("master-root-elsewhere");
        fs::write(
            studio.join("share").join(".unsloth-master-root"),
            elsewhere.to_string_lossy().as_bytes(),
        )
        .unwrap();
        assert_eq!(
            inferred_studio_llama_root(&bin),
            Some(studio.join("llama.cpp"))
        );

        for body in ["", "/nonexistent-master-root-9d3f"] {
            fs::write(studio.join("share").join(".unsloth-master-root"), body).unwrap();
            assert_eq!(
                inferred_studio_llama_root(&bin),
                Some(studio.join("llama.cpp")),
                "note body {body:?}"
            );
        }

        let _ = fs::remove_dir_all(&elsewhere);
        let _ = fs::remove_dir_all(&master);
    }

    #[cfg(not(windows))]
    #[test]
    fn the_unix_sentinel_is_the_launcher_the_installer_writes() {
        let root = scratch_dir("studio-sentinel");
        fs::create_dir_all(root.join("bin")).unwrap();
        assert!(!looks_like_installer_managed_studio_home(&root));
        fs::write(root.join("bin").join("unsloth"), b"launcher").unwrap();
        assert!(looks_like_installer_managed_studio_home(&root));
        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn the_cmd_shim_has_to_be_the_one_the_installer_generated() {
        let root = scratch_dir("cmd-shim");
        let shim = root.join("unsloth.cmd");
        fs::create_dir_all(&root).unwrap();
        assert!(!is_managed_cmd_shim(&shim));

        fs::write(&shim, b"@echo off\r\npython -m unsloth_cli %*\r\n").unwrap();
        assert!(
            !is_managed_cmd_shim(&shim),
            "a hand rolled wrapper that calls the CLI is not this shim"
        );

        fs::write(
            &shim,
            b"@rem unsloth-studio-managed-launcher\r\n@python -c \"from unsloth_cli import app; app()\" %*\r\n",
        )
        .unwrap();
        assert!(is_managed_cmd_shim(&shim));

        let mut oversized = b"unsloth-studio-managed-launcher from unsloth_cli import app".to_vec();
        oversized.resize((CMD_SHIM_MAX_BYTES + 1) as usize, b' ');
        fs::write(&shim, &oversized).unwrap();
        assert!(!is_managed_cmd_shim(&shim));

        let _ = fs::remove_dir_all(&root);
    }

    #[test]
    fn an_override_with_no_server_in_it_does_not_stop_the_search() {
        let root = scratch_dir("override-empty");
        fs::create_dir_all(&root).unwrap();
        assert!(!holds_a_llama_server(&root));
        assert!(!holds_a_llama_server(&root.join("not-there")));

        let bin = install_fake_runtime(&root);
        // On Windows the entrypoint carries .exe; the counting fixture's name is not the finder's.
        fs::write(bin.join(server_file_name()), b"binary").unwrap();
        assert!(
            holds_a_llama_server(&root),
            "build/bin/llama-server is one of the layouts the backend accepts"
        );

        let flat = scratch_dir("override-flat");
        fs::create_dir_all(&flat).unwrap();
        let server = flat.join(server_file_name());
        fs::write(&server, b"binary").unwrap();
        assert!(holds_a_llama_server(&flat));

        let decoy = scratch_dir("override-decoy");
        fs::create_dir_all(decoy.join(server_file_name())).unwrap();
        assert!(!holds_a_llama_server(&decoy));
        let _ = fs::remove_dir_all(&decoy);

        let _ = bin;
        let _ = fs::remove_dir_all(&root);
        let _ = fs::remove_dir_all(&flat);
    }

    #[cfg(unix)]
    #[test]
    fn a_named_user_resolves_through_the_reentrant_lookup() {
        // root exists on every unix box, so this is checkable anywhere.
        let home = Path::new("/home/whoever");
        let resolved = named_user_home("~root/llama.cpp", Some(home));
        assert!(
            resolved.is_some(),
            "root must resolve, or the reentrant lookup is not answering at all"
        );
        assert!(resolved.unwrap().ends_with("llama.cpp"));
        assert_eq!(
            named_user_home("~no-such-account-anywhere/x", Some(home)),
            None,
            "an unknown name leaves the value to be anchored like any relative path"
        );
    }

    #[cfg(unix)]
    #[test]
    fn clearing_the_execute_bit_moves_the_fingerprint() {
        use std::os::unix::fs::PermissionsExt;

        let parent = scratch_dir("runtime-exec-bit");
        let root = parent.join("llama.cpp");
        let bin = install_fake_runtime(&root);
        let before = llama_runtime_fingerprint_at(&root).unwrap();

        let server = bin.join("llama-server");
        let mut mode = fs::metadata(&server).unwrap().permissions();
        mode.set_mode(0o644);
        fs::set_permissions(&server, mode).unwrap();
        assert_ne!(
            before,
            llama_runtime_fingerprint_at(&root).unwrap(),
            "a binary that can no longer be executed is a different tree"
        );

        let mut restored = fs::metadata(&server).unwrap().permissions();
        restored.set_mode(0o755);
        fs::set_permissions(&server, restored).unwrap();
        assert_eq!(before, llama_runtime_fingerprint_at(&root).unwrap());

        let _ = fs::remove_dir_all(&parent);
    }

    #[cfg(unix)]
    #[test]
    fn losing_only_the_owners_execute_bit_moves_the_fingerprint() {
        use std::os::unix::fs::PermissionsExt;

        let parent = scratch_dir("runtime-owner-bit");
        let root = parent.join("llama.cpp");
        let bin = install_fake_runtime(&root);
        let server = bin.join("llama-server");
        let mut executable = fs::metadata(&server).unwrap().permissions();
        executable.set_mode(0o755);
        fs::set_permissions(&server, executable).unwrap();
        let before = llama_runtime_fingerprint_at(&root).unwrap();

        let mut owner_only = fs::metadata(&server).unwrap().permissions();
        owner_only.set_mode(0o655);
        fs::set_permissions(&server, owner_only).unwrap();
        assert_eq!(fs::metadata(&server).unwrap().permissions().mode() & 0o111, 0o011);
        assert_ne!(
            before,
            llama_runtime_fingerprint_at(&root).unwrap(),
            "a binary this user can no longer run is a different tree"
        );

        let _ = fs::remove_dir_all(&parent);
    }

    #[cfg(unix)]
    #[test]
    fn a_dangling_symlink_does_not_break_the_walk() {
        let parent = scratch_dir("runtime-dangling");
        let root = parent.join("llama.cpp");
        let bin = install_fake_runtime(&root);
        let before = llama_runtime_fingerprint_at(&root).unwrap();

        std::os::unix::fs::symlink(bin.join("gone.so"), bin.join("libggml.so")).unwrap();
        let dangling = llama_runtime_fingerprint_at(&root);
        assert!(
            dangling.is_some(),
            "a broken link must not make the walk fail or report the runtime missing"
        );
        assert_ne!(before, dangling.clone().unwrap());
        fs::remove_file(bin.join("libggml.so")).unwrap();
        assert_eq!(before, llama_runtime_fingerprint_at(&root).unwrap());

        let _ = fs::remove_dir_all(&parent);
    }

    #[cfg(unix)]
    #[test]
    fn a_runtime_directory_that_cannot_be_read_is_a_broken_install_not_an_absent_one() {
        use std::os::unix::fs::PermissionsExt;

        let root = scratch_dir("runtime-denied");
        let bin = install_fake_runtime(&root);
        let mut denied = fs::metadata(&bin).unwrap().permissions();
        denied.set_mode(0o000);
        fs::set_permissions(&bin, denied).unwrap();

        // Mode bits do not apply to root (some CI runs as root).
        if fs::read_dir(&bin).is_err() {
            let denied_fingerprint = llama_runtime_fingerprint_at(&root);
            assert!(
                denied_fingerprint.is_some(),
                "a root that is present but unreadable is a broken install, not an absent one"
            );
            assert_ne!(denied_fingerprint, None);
        }

        let mut restored = fs::metadata(&bin).unwrap().permissions();
        restored.set_mode(0o755);
        fs::set_permissions(&bin, restored).unwrap();
        let _ = fs::remove_dir_all(&root);
    }
}