Skip to main content

agentmux_srv_core/backend/sampler/
own_processes.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4// How busy AgentMux's own processes are, beside the machine's CPU: this server (`srv`) and the
5// desktop host that started it (the CEF process). A stall the page sees is the page's, the host's
6// or a wait between them; with the machine's CPU alone a busy browser or build elsewhere reads the
7// same as a busy host. The page's flight recorder puts these on the same timeline as its frames.
8//
9// It runs in the machine sampler's own tick and adds no thread and no wake-up: two targeted process
10// reads (never the whole process table) per tick. Numbers only; the keys name the process kind, never
11// a path or a command line.
12
13use std::collections::HashMap;
14
15use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System};
16
17/// The key for this server's CPU, in percent of the whole machine (the scale of the machine's own `cpu`).
18pub const SRV_CPU_SERIES: &str = "proc:srv:cpu";
19/// The key for the desktop host's CPU, in the same scale.
20pub const CEF_CPU_SERIES: &str = "proc:cef:cpu";
21
22/// The parent of this server is the desktop host only when it is one of ours: a server started from a shell
23/// (a dev run, a test) has a shell for a parent, which is not reported as the host.
24pub fn is_host_name(name: &str) -> bool {
25    name.to_ascii_lowercase().contains("agentmux")
26}
27
28/// A process's CPU as sysinfo reports it (percent of one core, and over 100 for several) as a percent of
29/// the machine, so it reads on the machine's own scale.
30pub fn machine_percent(process_cpu: f32, cpus: usize) -> f64 {
31    if cpus == 0 {
32        return 0.0;
33    }
34    (f64::from(process_cpu) / cpus as f64).clamp(0.0, 100.0)
35}
36
37/// The two processes and the reader for them.
38pub struct OwnProcesses {
39    sys: System,
40    srv: Pid,
41    /// The desktop host's pid, once found; `None` when this server's parent is not one of ours.
42    host: Option<Pid>,
43    host_known: bool,
44}
45
46impl OwnProcesses {
47    pub fn new() -> Self {
48        Self { sys: System::new(), srv: Pid::from_u32(std::process::id()), host: None, host_known: false }
49    }
50
51    /// Adds this server's and the host's CPU to `values`; `cpus` is the machine's logical CPU count.
52    /// The first call has nothing to compare with and reports nothing.
53    pub fn sample(&mut self, cpus: usize, values: &mut HashMap<String, f64>) {
54        let kind = ProcessRefreshKind::nothing().with_cpu();
55        if !self.host_known {
56            // The parent link is always filled in: look for the host once.
57            self.sys.refresh_processes_specifics(ProcessesToUpdate::Some(&[self.srv]), true, ProcessRefreshKind::nothing());
58            self.host_known = true;
59            if let Some(parent) = self.sys.process(self.srv).and_then(|p| p.parent()) {
60                self.sys.refresh_processes_specifics(ProcessesToUpdate::Some(&[parent]), true, ProcessRefreshKind::nothing());
61                if self.sys.process(parent).is_some_and(|p| is_host_name(&p.name().to_string_lossy())) {
62                    self.host = Some(parent);
63                }
64            }
65        }
66        let mut pids = vec![self.srv];
67        pids.extend(self.host);
68        self.sys.refresh_processes_specifics(ProcessesToUpdate::Some(&pids), true, kind);
69        if let Some(p) = self.sys.process(self.srv) {
70            values.insert(SRV_CPU_SERIES.to_string(), machine_percent(p.cpu_usage(), cpus));
71        }
72        if let Some(p) = self.host.and_then(|h| self.sys.process(h)) {
73            values.insert(CEF_CPU_SERIES.to_string(), machine_percent(p.cpu_usage(), cpus));
74        }
75    }
76}
77
78thread_local! {
79    /// The machine sampler runs on one thread of its own (`sampler::thread`), so its reader lives there.
80    static OWN: std::cell::RefCell<OwnProcesses> = std::cell::RefCell::new(OwnProcesses::new());
81}
82
83/// `OwnProcesses::sample` on the sampler thread's own reader.
84pub fn sample_into(cpus: usize, values: &mut HashMap<String, f64>) {
85    OWN.with(|own| own.borrow_mut().sample(cpus, values));
86}
87
88impl Default for OwnProcesses {
89    fn default() -> Self {
90        Self::new()
91    }
92}
93
94#[cfg(test)]
95mod tests {
96    use super::*;
97
98    #[test]
99    fn only_a_process_of_ours_is_the_host() {
100        assert!(is_host_name("agentmux-cef.exe"));
101        assert!(is_host_name("AgentMux"));
102        assert!(!is_host_name("bash"));
103        assert!(!is_host_name("WindowsTerminal.exe"));
104    }
105
106    #[test]
107    fn a_process_is_a_share_of_the_whole_machine_and_never_over_a_hundred() {
108        assert!((machine_percent(100.0, 8) - 12.5).abs() < 1e-9);
109        assert_eq!(machine_percent(900.0, 8), 100.0);
110        assert_eq!(machine_percent(-1.0, 8), 0.0);
111        assert_eq!(machine_percent(50.0, 0), 0.0);
112    }
113
114    #[test]
115    fn this_process_is_reported_as_the_server_after_two_samples_and_the_values_are_on_the_machine_scale() {
116        let mut own = OwnProcesses::new();
117        let mut first = HashMap::new();
118        own.sample(4, &mut first);
119        // Burn a little CPU so the second reading has a delta to report.
120        let started = std::time::Instant::now();
121        while started.elapsed() < std::time::Duration::from_millis(250) {
122            std::hint::black_box(started.elapsed().as_nanos());
123        }
124        let mut second = HashMap::new();
125        own.sample(4, &mut second);
126        let srv = second.get(SRV_CPU_SERIES).copied().expect("the server's own CPU is reported");
127        assert!((0.0..=100.0).contains(&srv), "{srv}");
128        for key in second.keys() {
129            assert!(key.starts_with("proc:"), "{key}");
130        }
131    }
132}