agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
use super::{install, probe_version, Core};
use crate::core::tool_detection::{command_directories, executable};
use semver::Version;
use std::{
    collections::HashSet,
    ffi::OsString,
    path::{Path, PathBuf},
    sync::{Mutex, OnceLock},
    time::{Duration, Instant},
};

const DISCOVERY_TTL: Duration = Duration::from_secs(5);
static LAST_FOUND: OnceLock<Mutex<Option<Found>>> = OnceLock::new();

pub(super) fn invalidate() {
    if let Some(cache) = LAST_FOUND.get() {
        *cache.lock().unwrap_or_else(|error| error.into_inner()) = None;
    }
}

#[derive(PartialEq, Eq)]
struct Environment {
    path: Option<OsString>,
    install_dir: Option<PathBuf>,
    local_app_data: Option<PathBuf>,
}

struct Found {
    environment: Environment,
    expires: Instant,
    core: Core,
}

pub(super) fn discover() -> Option<Core> {
    let environment = Environment {
        path: std::env::var_os("PATH"),
        install_dir: std::env::var_os("HC_INSTALL_DIR").map(PathBuf::from),
        local_app_data: std::env::var_os("LOCALAPPDATA").map(PathBuf::from),
    };
    let mut cache = LAST_FOUND
        .get_or_init(|| Mutex::new(None))
        .lock()
        .unwrap_or_else(|error| error.into_inner());
    if let Some(found) = cache.as_ref().filter(|found| {
        found.environment == environment
            && found.expires > Instant::now()
            && executable(&found.core.executable)
    }) {
        return Some(found.core.clone());
    }

    let home = dirs::home_dir().unwrap_or_default();
    let platform = std::env::consts::OS;
    let roots = environment
        .install_dir
        .iter()
        .cloned()
        .chain(command_directories(&home))
        .chain(platform_roots(
            platform,
            &home,
            environment.local_app_data.as_deref(),
        ));
    let managed = install::installed_path();
    let core = select(
        roots,
        managed.as_deref(),
        std::env::consts::EXE_SUFFIX,
        |path| executable(path).then(|| probe_version(path).ok()).flatten(),
    );
    // Misses are deliberately uncached so a completed install is visible immediately.
    *cache = core.as_ref().map(|core| Found {
        environment,
        expires: Instant::now() + DISCOVERY_TTL,
        core: core.clone(),
    });
    core
}

fn platform_roots(platform: &str, home: &Path, local_app_data: Option<&Path>) -> Vec<PathBuf> {
    match platform {
        "windows" => vec![local_app_data
            .map(PathBuf::from)
            .unwrap_or_else(|| home.join("AppData/Local"))
            .join("Programs/herdr-core")],
        "macos" => vec![
            home.join(".local/share/herdr-core/current/Contents/MacOS"),
            home.join(".local/share/herdr-core/Herdr Core.app/Contents/MacOS"),
            home.join(".local/share/mise/shims"),
            home.join(".nix-profile/bin"),
        ],
        "linux" => vec![
            home.join(".local/share/mise/shims"),
            home.join(".nix-profile/bin"),
            PathBuf::from("/run/current-system/sw/bin"),
        ],
        _ => Vec::new(),
    }
}

fn select(
    roots: impl IntoIterator<Item = PathBuf>,
    managed: Option<&Path>,
    suffix: &str,
    mut version: impl FnMut(&Path) -> Option<Version>,
) -> Option<Core> {
    let mut seen = HashSet::new();
    let names = [format!("herdr-core{suffix}"), format!("hc{suffix}")];
    roots
        .into_iter()
        .filter(|root| root.is_absolute())
        .flat_map(|root| names.iter().map(move |name| root.join(name)))
        .chain(managed.map(PathBuf::from))
        .filter(|path| seen.insert(path.clone()))
        .find_map(|path| {
            let version = version(&path)?;
            let managed = managed.is_some_and(|installed| same_file_path(&path, installed));
            Some(Core {
                executable: path,
                version,
                managed,
                session: None,
            })
        })
}

fn same_file_path(path: &Path, installed: &Path) -> bool {
    path == installed
        || path
            .canonicalize()
            .ok()
            .is_some_and(|path| installed.canonicalize().ok().as_ref() == Some(&path))
}

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

    #[test]
    fn discovers_official_install_directories_without_path() {
        let temp = tempfile::tempdir().unwrap();
        let home = temp.path();
        let local = home.join("Local App Data");
        assert_eq!(
            platform_roots("windows", home, Some(&local)),
            [local.join("Programs/herdr-core")]
        );
        assert_eq!(
            platform_roots("windows", home, None),
            [home.join("AppData/Local/Programs/herdr-core")]
        );
        assert!(platform_roots("macos", home, None)
            .contains(&home.join(".local/share/herdr-core/current/Contents/MacOS")));
        assert!(platform_roots("linux", home, None).contains(&home.join(".nix-profile/bin")));
    }

    #[test]
    fn skips_unverified_aliases_and_falls_back_to_managed_native_binary() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path();
        let external = root.join("path");
        let managed = root.join("managed/herdr-core.exe");
        let mut attempted = Vec::new();
        let core = select(
            [PathBuf::from("relative"), external.clone()],
            Some(&managed),
            ".exe",
            |path| {
                attempted.push(path.to_path_buf());
                (path == managed).then(|| Version::new(0, 1, 22))
            },
        )
        .unwrap();
        assert_eq!(
            attempted,
            [
                external.join("herdr-core.exe"),
                external.join("hc.exe"),
                managed.clone(),
            ]
        );
        assert_eq!(core.executable, managed);
        assert!(core.managed);
    }

    #[test]
    fn prefers_verified_external_core_to_managed_installation() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path();
        let external = root.join("herdr-core");
        let managed = root.join("managed/herdr-core");
        let core = select([root.to_path_buf()], Some(&managed), "", |_| {
            Some(Version::new(0, 1, 22))
        })
        .unwrap();
        assert_eq!(core.executable, external);
        assert!(!core.managed);
    }

    #[cfg(unix)]
    #[test]
    fn recognizes_a_managed_installation_linked_on_path() {
        let temp = tempfile::tempdir().unwrap();
        let root = temp.path();
        let managed = root.join("installed-core");
        std::fs::write(&managed, b"fixture").unwrap();
        std::os::unix::fs::symlink(&managed, root.join("hc")).unwrap();
        let core = select([root.to_path_buf()], Some(&managed), "", |path| {
            path.is_file().then(|| Version::new(0, 1, 22))
        })
        .unwrap();
        assert_eq!(core.executable, root.join("hc"));
        assert!(core.managed);
    }

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

        let temp = tempfile::tempdir().unwrap();
        let other = temp.path().join("hc");
        let core = temp.path().join("herdr-core");
        for (path, version) in [(&other, "other-core 1.0.0"), (&core, "hc 0.1.22")] {
            std::fs::write(path, format!("#!/bin/sh\nprintf '%s\\n' '{version}'\n")).unwrap();
            std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).unwrap();
        }
        assert!(probe_version(&other).is_err());
        assert_eq!(probe_version(&core).unwrap(), Version::new(0, 1, 22));
    }
}