Skip to main content

oomtop_cli/
profile.rs

1//! Machine profile (UX §6): hardware facts, detected roles and the adaptations they imply. Built from a
2//! snapshot (pure) plus a bounded scan of the configured model folders (headers are never read), stored in
3//! `oomtop-state` and refreshed at most daily. Roles are sticky for [`ROLE_TTL_MS`] so a model server that
4//! isn't running right now doesn't erase the "local LLM" role.
5
6use oomtop_core::{GroupKind, ModelServerKind, Snapshot};
7use serde::{Deserialize, Serialize};
8use std::collections::BTreeMap;
9use std::path::Path;
10
11/// A role not observed for this long is dropped.
12pub const ROLE_TTL_MS: u64 = 30 * 86_400_000;
13/// Bounded model-folder scan: entries visited at most.
14pub const SCAN_MAX_ENTRIES: usize = 4000;
15const SCAN_MAX_DEPTH: usize = 3;
16/// Wall-time budget for the scan (it runs at most once a day, but must not delay the first frame much).
17pub const SCAN_BUDGET: std::time::Duration = std::time::Duration::from_millis(150);
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize, Hash)]
20#[serde(rename_all = "snake_case")]
21pub enum Role {
22    /// Model servers (Ollama, llama.cpp, LM Studio, vLLM, MLX) or gguf/safetensors files.
23    LocalLlm,
24    /// Diffusion servers (sd.cpp, ComfyUI-style).
25    Diffusion,
26    /// Agent CLIs (Claude Code, Codex, …).
27    AgentHeavy,
28    /// Gradle / Kotlin / JVM daemons.
29    JvmAndroid,
30    /// node / tsserver / browsers.
31    WebDev,
32    /// Docker / OrbStack / Podman / VMs.
33    ContainerUser,
34}
35
36impl Role {
37    pub fn describe(self) -> &'static str {
38        match self {
39            Role::LocalLlm => "local LLM (model servers / model files)",
40            Role::Diffusion => "image diffusion",
41            Role::AgentHeavy => "agent-heavy (agent CLIs)",
42            Role::JvmAndroid => "JVM / Android dev (Gradle, Kotlin daemons)",
43            Role::WebDev => "web dev (node, tsserver, browsers)",
44            Role::ContainerUser => "containers / VMs",
45        }
46    }
47}
48
49#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
50#[serde(default)]
51pub struct GpuInfo {
52    pub vendor: String,
53    pub name: String,
54    pub unified: bool,
55    pub vram: Option<u64>,
56}
57
58#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
59#[serde(default)]
60pub struct Hardware {
61    pub model: Option<String>,
62    pub cpu: Option<String>,
63    pub arch: String,
64    pub os: String,
65    pub cores_logical: u32,
66    pub cores_performance: Option<u32>,
67    pub cores_efficiency: Option<u32>,
68    pub ram: u64,
69    pub unified_memory: bool,
70    pub fanless: Option<bool>,
71    pub has_battery: bool,
72    pub gpus: Vec<GpuInfo>,
73}
74
75#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
76#[serde(default)]
77pub struct Adaptations {
78    /// Show a GPU column (a usable GPU with memory or utilization data).
79    pub gpu_column: bool,
80    /// Thermal-prone (fanless or unified-memory laptop): throttle insights enabled, larger margin advised.
81    pub thermal_prone: bool,
82    /// Suggested extra safety margin over the default, in percent of RAM (applied only if the user opts in).
83    pub suggested_margin_pct: f64,
84    /// Insight generators worth enabling for this machine.
85    pub insights: Vec<String>,
86}
87
88#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
89#[serde(default)]
90pub struct MachineProfile {
91    pub version: u32,
92    pub hardware: Hardware,
93    /// Role → last observed (ms).
94    pub roles: BTreeMap<Role, u64>,
95    pub adaptations: Adaptations,
96    /// Model files found in the configured folders (count only; names are not stored).
97    pub model_files: u64,
98    pub updated_ms: u64,
99}
100
101fn name_has(s: &Snapshot, needles: &[&str]) -> bool {
102    s.processes.iter().any(|p| {
103        let n = p.name.to_ascii_lowercase();
104        needles.iter().any(|x| n == *x || n.starts_with(x))
105    })
106}
107
108/// Roles visible in this snapshot.
109pub fn roles_in(s: &Snapshot, model_files: u64) -> Vec<Role> {
110    let mut r = Vec::new();
111    let llm = s.model_servers.iter().any(|m| m.kind != ModelServerKind::SdCpp) || model_files > 0;
112    if llm {
113        r.push(Role::LocalLlm);
114    }
115    if s.model_servers.iter().any(|m| m.kind == ModelServerKind::SdCpp)
116        || name_has(s, &["sd-server", "comfyui"])
117    {
118        r.push(Role::Diffusion);
119    }
120    if s.groups.iter().any(|g| g.kind == GroupKind::AgentSession) {
121        r.push(Role::AgentHeavy);
122    }
123    let jvm = s.groups.iter().any(|g| {
124        g.kind == GroupKind::BuildDaemon && {
125            let l = g.label.to_ascii_lowercase();
126            l.contains("gradle") || l.contains("kotlin") || l.contains("java")
127        }
128    });
129    if jvm {
130        r.push(Role::JvmAndroid);
131    }
132    if name_has(s, &["node", "tsserver", "bun", "deno", "vite"]) {
133        r.push(Role::WebDev);
134    }
135    if !s.sandboxes.is_empty() || name_has(s, &["dockerd", "com.docker", "orbstack", "podman", "containerd"])
136    {
137        r.push(Role::ContainerUser);
138    }
139    r
140}
141
142/// Hardware facts from a snapshot.
143pub fn hardware(s: &Snapshot) -> Hardware {
144    let h = &s.host;
145    Hardware {
146        model: h.model.clone(),
147        cpu: h.cpu_brand.clone(),
148        arch: h.arch.clone(),
149        os: h.os_version.clone(),
150        cores_logical: h.cores_logical,
151        cores_performance: h.cores_performance,
152        cores_efficiency: h.cores_efficiency,
153        ram: h.mem_total,
154        unified_memory: h.unified_memory,
155        fanless: h.fanless,
156        has_battery: s.thermal.battery_pct.is_available(),
157        gpus: s
158            .accelerators
159            .iter()
160            .map(|a| GpuInfo {
161                vendor: format!("{:?}", a.vendor).to_ascii_lowercase(),
162                name: a.name.clone(),
163                unified: a.unified,
164                vram: if a.unified { None } else { a.mem_total.value },
165            })
166            .collect(),
167    }
168}
169
170/// Builds (or refreshes) the profile. `prev` roles are kept until they expire.
171pub fn build(s: &Snapshot, model_files: u64, prev: Option<&MachineProfile>, now_ms: u64) -> MachineProfile {
172    let hw = hardware(s);
173    let mut roles: BTreeMap<Role, u64> = prev
174        .map(|p| {
175            p.roles
176                .iter()
177                .filter(|(_, t)| now_ms.saturating_sub(**t) < ROLE_TTL_MS)
178                .map(|(r, t)| (*r, *t))
179                .collect()
180        })
181        .unwrap_or_default();
182    for r in roles_in(s, model_files) {
183        roles.insert(r, now_ms);
184    }
185    let gpu_column = s
186        .accelerators
187        .iter()
188        .any(|a| a.mem_used.is_available() || a.util_pct.is_available());
189    let thermal_prone = hw.fanless == Some(true) || (hw.unified_memory && hw.has_battery);
190    let mut insights = vec!["headroom".to_string(), "reclaim".to_string()];
191    if thermal_prone {
192        insights.push("throttle".into());
193    }
194    if roles.contains_key(&Role::LocalLlm) || roles.contains_key(&Role::Diffusion) {
195        insights.push("model_fit".into());
196    }
197    if roles.contains_key(&Role::AgentHeavy) {
198        insights.push("agent_sessions".into());
199    }
200    if roles.contains_key(&Role::JvmAndroid) {
201        insights.push("idle_build_daemons".into());
202    }
203    MachineProfile {
204        version: 1,
205        adaptations: Adaptations {
206            gpu_column,
207            thermal_prone,
208            suggested_margin_pct: if thermal_prone && hw.unified_memory {
209                4.0
210            } else {
211                0.0
212            },
213            insights,
214        },
215        hardware: hw,
216        roles,
217        model_files,
218        updated_ms: now_ms,
219    }
220}
221
222/// Counts `.gguf` / `.safetensors` files under the folders (depth ≤ 3, ≤ [`SCAN_MAX_ENTRIES`] entries, at most
223/// [`SCAN_BUDGET`] of wall time; symlinks not followed; unreadable dirs skipped). Only the count is kept.
224pub fn count_model_files(folders: &[std::path::PathBuf]) -> u64 {
225    struct Walk {
226        seen: usize,
227        count: u64,
228        deadline: std::time::Instant,
229    }
230    impl Walk {
231        fn exhausted(&self) -> bool {
232            self.seen >= SCAN_MAX_ENTRIES || std::time::Instant::now() >= self.deadline
233        }
234        fn dir(&mut self, dir: &Path, depth: usize) {
235            if depth > SCAN_MAX_DEPTH || self.exhausted() {
236                return;
237            }
238            let Ok(rd) = std::fs::read_dir(dir) else { return };
239            for e in rd.flatten() {
240                self.seen += 1;
241                if self.exhausted() {
242                    return;
243                }
244                let Ok(ft) = e.file_type() else { continue };
245                let p = e.path();
246                if ft.is_dir() {
247                    self.dir(&p, depth + 1);
248                } else if ft.is_file()
249                    && p.extension().is_some_and(|x| {
250                        let x = x.to_ascii_lowercase();
251                        x == "gguf" || x == "safetensors"
252                    })
253                {
254                    self.count += 1;
255                }
256            }
257        }
258    }
259    let mut w = Walk {
260        seen: 0,
261        count: 0,
262        deadline: std::time::Instant::now() + SCAN_BUDGET,
263    };
264    for f in folders {
265        w.dir(f, 0);
266    }
267    w.count
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273    use oomtop_core::{Group, ModelServer, Process};
274
275    fn snap() -> Snapshot {
276        let mut s = Snapshot::default();
277        s.host.mem_total = 24 << 30;
278        s.host.unified_memory = true;
279        s.host.fanless = Some(true);
280        s.groups.push(Group {
281            id: "daemon:gradle".into(),
282            kind: GroupKind::BuildDaemon,
283            label: "GradleDaemon".into(),
284            ..Default::default()
285        });
286        s.groups.push(Group {
287            id: "agent:1".into(),
288            kind: GroupKind::AgentSession,
289            label: "Claude Code".into(),
290            ..Default::default()
291        });
292        s.model_servers.push(ModelServer {
293            id: "sd".into(),
294            kind: ModelServerKind::SdCpp,
295            ..Default::default()
296        });
297        s.processes.push(Process {
298            name: "node".into(),
299            ..Default::default()
300        });
301        s
302    }
303
304    #[test]
305    fn roles_and_adaptations() {
306        let p = build(&snap(), 0, None, 1000);
307        let roles: Vec<Role> = p.roles.keys().copied().collect();
308        assert_eq!(
309            roles,
310            vec![Role::Diffusion, Role::AgentHeavy, Role::JvmAndroid, Role::WebDev]
311        );
312        assert!(p.adaptations.thermal_prone);
313        assert!(!p.adaptations.gpu_column);
314        assert!(p.adaptations.insights.contains(&"throttle".to_string()));
315        assert!(p.adaptations.insights.contains(&"model_fit".to_string()));
316    }
317
318    #[test]
319    fn roles_are_sticky_until_they_expire() {
320        let first = build(&snap(), 3, None, 1000);
321        assert!(first.roles.contains_key(&Role::LocalLlm));
322        let later = build(&Snapshot::default(), 0, Some(&first), 1000 + 86_400_000);
323        assert!(later.roles.contains_key(&Role::LocalLlm), "kept for a day");
324        let much_later = build(&Snapshot::default(), 0, Some(&first), 1000 + ROLE_TTL_MS);
325        assert!(much_later.roles.is_empty());
326    }
327
328    #[test]
329    fn model_file_scan_is_bounded_and_counts() {
330        let d = tempfile::tempdir().unwrap();
331        std::fs::create_dir_all(d.path().join("a/b")).unwrap();
332        std::fs::write(d.path().join("a/m.gguf"), b"x").unwrap();
333        std::fs::write(d.path().join("a/b/w.safetensors"), b"x").unwrap();
334        std::fs::write(d.path().join("a/b/readme.md"), b"x").unwrap();
335        assert_eq!(count_model_files(&[d.path().to_path_buf()]), 2);
336        assert_eq!(count_model_files(&[d.path().join("missing")]), 0);
337    }
338
339    #[test]
340    fn serde_round_trip() {
341        let p = build(&snap(), 1, None, 5);
342        let v = serde_json::to_value(&p).unwrap();
343        assert_eq!(v["roles"]["agent_heavy"], 5);
344        let back: MachineProfile = serde_json::from_value(v).unwrap();
345        assert_eq!(back, p);
346    }
347}