Files
capri-core-rust/crates/capri/src/doctor.rs
T
nocodeandClaude Opus 5.5 49349d6ecd
CI / test (push) Has been cancelled
Linux port: first run, packaging, single instance, privacy and wiring
First run and backend
- The companion opens without Ollama or a model (OFFLINE / SETUP REQUIRED),
  opens Settings > Language model and picks the model up once downloaded.
- Model, provider and GPU changes apply without restarting (Ollama is
  restarted when launch settings change); no silent fallback from API mode.
- Fatal startup errors are shown in a window; the fallback avatar loads
  again; the shipped Capri artwork is used when nothing was imported.

Packaging and tooling
- packaging/arch/PKGBUILD, capri.desktop (KWin ScreenShot2 key), icons,
  artwork under /usr/share/capri/assets, Gitea Actions CI.
- xtask: `icons` and `release-check` (no private data or credentials).

Runtime
- One instance per data folder (flock + control socket): second launch
  shows the window; capri stop / restart / toggle / status (JSON, starts
  nothing) / doctor / setup / diagnostics export / purge.
- A foreign program on the Ollama port is refused; an Ollama left behind
  by Capri is replaced.

Privacy and security
- No raw Ollama log on disk; API keys are never saved in plaintext (old
  ones move to the keyring); refused credential notes are stored as
  [Credentials omitted]; launched apps get an allow-listed environment.

Fixes
- Stop/Escape silence the voice; saved voice effects apply to replies;
  settings_control glitch settings apply; distinct KWin cursor scripts;
  KDE window capture authorized for source builds; Linux wording.
- Voice pack references zipped with Windows separators are found.

Wired features
- Initiatives, request router, resource monitor, "clip that", questions
  about a snapshot, sleep mode, tap reactions, stopwatch, attachments,
  Internet mode button, voice-synced subtitles, wake visuals, dictation
  draft, tray switches, Spotify seek/shuffle/repeat; computer-control
  planner and classifier follow model switches and API mode.
- Approval cards: one shown, 8 queued, deduplicated, cancelled on stop,
  failure, lock or pause; one Application access switch.

Desktop
- Compositor detection (no black overlay on i3 without picom), i3lock
  detection, unsupported desktops reported at startup, screenshot-only
  control without AT-SPI, fontconfig fallbacks, translatable feature
  pages with French translations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 20:21:40 +01:00

161 lines
9.2 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! `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<String>, hint: impl Into<String>) -> Check {
Check { area, level, detail: detail.into(), hint: hint.into() }
}
fn run(program: &str, args: &[&str]) -> Option<String> {
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<screen>`.
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<Check> {
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<String> = 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(())
}