//! `capri doctor`: checks what Capri needs on this Linux desktop and says how to fix what is //! missing (spec 09 RT-08). Read-only: it starts nothing and changes nothing. use std::path::Path; use std::process::{Command, Stdio}; use std::time::Duration; use capri_core::{Paths, Settings}; use serde_json::{json, Value}; #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum Level { Ok, Warn, Fail, } pub struct Check { pub area: &'static str, pub level: Level, pub detail: String, /// What to do about it (empty when fine). pub hint: String, } fn check(area: &'static str, level: Level, detail: impl Into, hint: impl Into) -> Check { Check { area, level, detail: detail.into(), hint: hint.into() } } fn run(program: &str, args: &[&str]) -> Option { let out = Command::new(program).args(args).stdin(Stdio::null()).stderr(Stdio::null()).output().ok()?; out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string()) } fn on_path(program: &str) -> bool { std::env::var_os("PATH").is_some_and(|p| std::env::split_paths(&p).any(|d| d.join(program).is_file())) } /// A D-Bus name is owned now or can be started on demand. async fn bus_name(conn: &zbus::Connection, name: &str) -> bool { let Ok(dbus) = zbus::fdo::DBusProxy::new(conn).await else { return false }; let Ok(bus) = zbus::names::BusName::try_from(name) else { return false }; if dbus.name_has_owner(bus).await.unwrap_or(false) { return true; } dbus.list_activatable_names().await.is_ok_and(|names| names.iter().any(|n| n.as_str() == name)) } /// A compositing manager owns `_NET_WM_CM_S`. fn x11_compositor() -> bool { use x11rb::connection::Connection as _; use x11rb::protocol::xproto::ConnectionExt as _; let Ok((conn, screen)) = x11rb::connect(None) else { return false }; let _ = conn.setup(); let atom = conn.intern_atom(false, format!("_NET_WM_CM_S{screen}").as_bytes()).ok().and_then(|c| c.reply().ok()).map(|r| r.atom); atom.and_then(|a| conn.get_selection_owner(a).ok()?.reply().ok()).is_some_and(|r| r.owner != x11rb::NONE) } pub async fn checks(paths: &Paths, settings: &Settings) -> Vec { let mut out = vec![]; // Ollama let exe = std::env::var_os("CAPRI_OLLAMA_PATH").map(|p| p.to_string_lossy().into_owned()).or_else(|| settings.ollama_path.as_ref().map(|p| p.display().to_string())).unwrap_or_else(|| "ollama".into()); let inference: capri_llm::sections::InferenceSection = settings.section(); match run(&exe, &["--version"]) { Some(text) => { let version = text.split_whitespace().last().unwrap_or_default().to_string(); let ok = capri_llm::server::version_at_least(&version, &inference.min_ollama_version); out.push(check("Ollama", if ok { Level::Ok } else { Level::Fail }, format!("{exe} {version}"), if ok { String::new() } else { format!("Capri needs Ollama {} or newer: sudo pacman -Syu ollama", inference.min_ollama_version) })); } None => out.push(check("Ollama", Level::Fail, format!("{exe} not found"), "sudo pacman -S ollama (or ollama-cuda / ollama-rocm / ollama-vulkan for your GPU)")), } // Language model in Capri's store (manifests are read from disk: nothing is started) let store = settings.models_dir(paths); let installed = [&settings.model, &settings.upstream_model].iter().find(|m| capri_models::manage::read_manifest(&store, m).is_ok()).map(|m| m.to_string()); match (installed, settings.ollama_url.is_some()) { (Some(model), _) => out.push(check("Language model", Level::Ok, format!("{model} in {}", store.display()), "")), (None, true) => out.push(check("Language model", Level::Warn, "external Ollama server: models are not checked", "")), (None, false) => out.push(check("Language model", Level::Fail, format!("{} is not downloaded", settings.upstream_model), "capri pull, or Settings › Language model › Download")), } // Hardware let hw = capri_models::hardware::probe().await; let gpus: Vec = hw.gpus.iter().map(|g| g.name.clone()).collect(); out.push(check("Hardware", Level::Ok, format!("{}, {} threads, {:.1} GiB RAM{}", hw.cpu, hw.cpu_threads, hw.ram_gib(), if gpus.is_empty() { String::new() } else { format!(", GPU: {}", gpus.join(", ")) }), "")); for warning in hw.warnings { out.push(check("Hardware", Level::Warn, warning, "")); } // Desktop match capri_perception::platform::Platform::detect() { Ok(platform) => { let i3 = platform == capri_perception::platform::Platform::X11; let ready = !i3 || capri_perception::i3::I3::connect().await.is_ok(); out.push(check("Desktop", if ready { Level::Ok } else { Level::Warn }, format!("{platform:?}{}", if i3 && !ready { " without i3" } else { "" }), if ready { "" } else { "Screen and computer control need KDE Plasma (Wayland) or i3 (X11)" })); if i3 && ready { let compositor = x11_compositor(); out.push(check("Compositor", if compositor { Level::Ok } else { Level::Warn }, if compositor { "running" } else { "none found" }, if compositor { "" } else { "Transparency and leaving the frame need one: picom -b (add it to your i3 config)" })); } } Err(e) => out.push(check("Desktop", Level::Warn, format!("{e:#}"), "")), } // Session services over D-Bus match zbus::Connection::session().await { Ok(session) => { let secrets = bus_name(&session, "org.freedesktop.secrets").await; out.push(check("Secret Service", if secrets { Level::Ok } else { Level::Warn }, if secrets { "available" } else { "missing" }, if secrets { "" } else { "API keys cannot be saved: start KWallet (KDE) or gnome-keyring / KeePassXC (i3)" })); let tray = bus_name(&session, "org.kde.StatusNotifierWatcher").await; out.push(check("Tray icon", if tray { Level::Ok } else { Level::Warn }, if tray { "StatusNotifier host found" } else { "no StatusNotifier host" }, if tray { "" } else { "On i3: snixembed --fork (bridges to i3bar)" })); let a11y = bus_name(&session, "org.a11y.Bus").await; out.push(check("Accessibility", if a11y { Level::Ok } else { Level::Warn }, if a11y { "AT-SPI bus available" } else { "AT-SPI bus missing" }, if a11y { "" } else { "Computer control works from screenshots only: sudo pacman -S at-spi2-core" })); let portal = bus_name(&session, "org.freedesktop.portal.Desktop").await; out.push(check("Desktop portal", if portal { Level::Ok } else { Level::Warn }, if portal { "available" } else { "missing" }, if portal { "" } else { "KDE computer control uses the Remote Desktop portal: xdg-desktop-portal-kde" })); } Err(e) => out.push(check("D-Bus session", Level::Fail, format!("{e}"), "Run Capri inside a desktop session")), } // Audio let pactl = run("pactl", &["info"]); let pipewire = pactl.as_deref().is_some_and(|i| i.contains("PipeWire")); out.push(match pactl { Some(_) => check("Audio server", Level::Ok, if pipewire { "PipeWire (pulse)" } else { "PulseAudio" }, ""), None => check("Audio server", Level::Warn, "pactl not answering", "Named microphones, music detection and call audio need pipewire-pulse (or PulseAudio)"), }); for tool in ["parec", "pacat"] { if !on_path(tool) { out.push(check("Audio tools", Level::Warn, format!("{tool} missing"), "sudo pacman -S libpulse")); } } if pipewire && !Path::new("/usr/share/alsa/alsa.conf.d/50-pipewire.conf").exists() && !Path::new("/etc/alsa/conf.d/50-pipewire.conf").exists() { out.push(check("Audio (ALSA)", Level::Warn, "pipewire-alsa not detected", "Default microphone and speakers go through ALSA: sudo pacman -S pipewire-alsa")); } // Speech components let speech = paths.data.join("speech"); let any = |dir: &str| std::fs::read_dir(speech.join(dir)).is_ok_and(|mut d| d.next().is_some()); out.push(check("Speech", if any("asr") || any("tts") { Level::Ok } else { Level::Warn }, format!("recognition {}, voice {}", if any("asr") { "installed" } else { "not installed" }, if any("tts") { "installed" } else { "not installed" }), if any("asr") && any("tts") { "" } else { "Settings › Voice and microphone › Install" })); out } pub fn print(checks: &[Check]) { for c in checks { let mark = match c.level { Level::Ok => "ok ", Level::Warn => "warn", Level::Fail => "FAIL", }; println!("[{mark}] {:<16} {}", c.area, c.detail); if !c.hint.is_empty() { println!(" {:<16} → {}", "", c.hint); } } } /// Same checks as JSON (diagnostics export). pub fn to_json(checks: &[Check]) -> Value { Value::Array(checks.iter().map(|c| json!({"area": c.area, "level": format!("{:?}", c.level).to_lowercase(), "detail": c.detail, "hint": c.hint})).collect()) } pub async fn doctor(paths: &Paths, settings: &Settings) -> anyhow::Result<()> { let checks = tokio::time::timeout(Duration::from_secs(30), checks(paths, settings)).await?; print(&checks); let failures = checks.iter().filter(|c| c.level == Level::Fail).count(); anyhow::ensure!(failures == 0, "{failures} problem(s) must be fixed before Capri can answer."); Ok(()) }