Skip to main content

agentmux_srv_core/backend/sampler/
panes.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Each pane's CPU and memory for its stats badge, taken from Tower's sample
5//! (`backend::tower::sampler`), so the badge and Tower count the same processes
6//! the same way: a pane's Job Object or cgroup, which nothing it starts can
7//! leave, else its shell's process tree. A Tower pane open at the same time
8//! shares the process snapshot (Tower reuses one taken within the last second).
9//! The badge's tooltip (`blockstats.detail`) reads the same task from
10//! [`tower_snapshot`], so it lists the processes the badge counts.
11//! docs/reports/REPORT_SYSINFO_REWRITE_AND_MODERN_MONITOR_2026_10_13.md section 5.5.
12
13use std::sync::Arc;
14
15use crate::backend::blockcontroller::pidregistry;
16use crate::backend::blockstats_detail::Shell;
17use crate::backend::rpc_types::{TowerProcessRole, TowerSnapshot, TowerTaskKind};
18use crate::backend::tower::sampler::{BlockLabel, Inputs, Tower};
19
20/// What one pane's badge shows.
21#[derive(Debug, Clone, PartialEq)]
22pub struct PaneStat {
23    pub block_id: String,
24    /// Percent of one core; `None` on the first sample, before there is a rate.
25    pub cpu_pct: Option<f64>,
26    /// Resident memory of its processes, bytes: what the badge calls Memory ("in
27    /// RAM now, including pages shared"). Its tooltip shows private memory
28    /// separately, from the detail.
29    pub mem: u64,
30    pub pids: u32,
31    /// Its main process, so a restarted shell starts a new peak.
32    pub shell: Shell,
33}
34
35/// Measures every pane's stats. Blocking: reads the process table.
36pub type PaneSampler = Arc<dyn Fn() -> std::io::Result<Vec<PaneStat>> + Send + Sync>;
37
38/// The panes' stats in a Tower snapshot: one per pane task, AgentMux's own
39/// task left out.
40pub fn from_snapshot(snap: &TowerSnapshot) -> Vec<PaneStat> {
41    snap.tasks
42        .iter()
43        .filter(|t| t.kind != TowerTaskKind::Agentmux)
44        .map(|t| {
45            let main = t.processes.iter().find(|p| p.role == Some(TowerProcessRole::Main));
46            PaneStat {
47                block_id: t.id.clone(),
48                cpu_pct: t.cpu.map(|c| c * 100.0),
49                mem: t.processes.iter().filter_map(|p| p.mem_resident).sum(),
50                pids: t.processes.len() as u32,
51                shell: main.map_or((0, 0), |p| (p.pid, p.started_at_ms.unwrap_or(0))),
52            }
53        })
54        .collect()
55}
56
57/// The live sampler: Tower's sample of this machine, with each pane named by
58/// `labels` (a pane `labels` doesn't know, such as one that was closed, is left out).
59pub fn tower_sampler(labels: impl Fn(&str) -> Option<BlockLabel> + Send + Sync + 'static) -> PaneSampler {
60    Arc::new(move || {
61        let tracked = crate::backend::process_tracker::registry::global().is_some_and(|r| r.has_tracked_blocks());
62        sample_if_panes(pidregistry::get_all().len(), tracked, || Ok(from_snapshot(&tower_snapshot(&labels)?)))
63    })
64}
65
66/// `sample`, unless there is no pane to measure: then no stats and no process-table
67/// read. The table would only hold the backend itself (left out of the stats), and
68/// reading it every pass is the whole cost of an idle srv.
69fn sample_if_panes(
70    registered_shells: usize,
71    tracked_blocks: bool,
72    sample: impl FnOnce() -> std::io::Result<Vec<PaneStat>>,
73) -> std::io::Result<Vec<PaneStat>> {
74    if registered_shells == 0 && !tracked_blocks {
75        return Ok(Vec::new());
76    }
77    sample()
78}
79
80/// Tower's sample of this machine's panes, each named by `labels`. Blocking:
81/// reads the process table, unless Tower read it within the last 900 ms.
82pub fn tower_snapshot(labels: impl Fn(&str) -> Option<BlockLabel>) -> std::io::Result<TowerSnapshot> {
83    let inputs = || Inputs {
84        blocks: crate::backend::process_tracker::registry::global()
85            .map(|t| t.members_by_block())
86            .unwrap_or_default(),
87        roots: pidregistry::get_all(),
88        own_pid: std::process::id(),
89    };
90    Tower::global().sample(false, "", inputs, labels, |_| None)
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96    use crate::backend::rpc_types::{TowerProcess, TowerTask};
97
98    #[test]
99    fn an_instance_with_no_pane_takes_no_process_snapshot() {
100        let taken = std::cell::Cell::new(0);
101        let sample = || {
102            taken.set(taken.get() + 1);
103            Ok(Vec::new())
104        };
105        assert!(sample_if_panes(0, false, sample).unwrap().is_empty());
106        assert_eq!(taken.get(), 0, "nothing registered and nothing tracked: nothing to measure");
107        sample_if_panes(1, false, sample).unwrap();
108        assert_eq!(taken.get(), 1, "a registered shell is measured");
109        sample_if_panes(0, true, sample).unwrap();
110        assert_eq!(taken.get(), 2, "a tracked agent pane is measured");
111    }
112
113    fn process(pid: u32, role: TowerProcessRole, started: u64) -> TowerProcess {
114        TowerProcess {
115            pid,
116            role: Some(role),
117            started_at_ms: Some(started),
118            mem: Some(1),
119            mem_resident: Some(1000 + u64::from(pid)),
120            ..Default::default()
121        }
122    }
123
124    fn snapshot(tasks: Vec<TowerTask>) -> TowerSnapshot {
125        TowerSnapshot {
126            ts_ms: 0,
127            hostname: String::new(),
128            panes: None,
129            memory: None,
130            os: String::new(),
131            cpu_count: 1,
132            memory_metric: String::new(),
133            interval_ms: 2000,
134            remote: false,
135            tasks,
136            machine: None,
137            host: None,
138        }
139    }
140
141    fn task(id: &str, kind: TowerTaskKind, cpu: Option<f64>, mem: u64, processes: Vec<TowerProcess>) -> TowerTask {
142        TowerTask {
143            id: id.to_string(),
144            kind,
145            label: id.to_string(),
146            tracking: "tree".to_string(),
147            cpu,
148            cpu_account: false,
149            mem,
150            processes,
151            exited: None,
152        }
153    }
154
155    #[test]
156    fn each_pane_task_becomes_a_badge_and_agentmux_itself_does_not() {
157        let snap = snapshot(vec![
158                task(
159                    "term-1",
160                    TowerTaskKind::Terminal,
161                    Some(0.25),
162                    4096,
163                    vec![process(10, TowerProcessRole::Main, 111), process(11, TowerProcessRole::Started, 112)],
164                ),
165                task("agent-1", TowerTaskKind::Agent, Some(1.5), 8192, vec![process(20, TowerProcessRole::Main, 222)]),
166                task(crate::backend::tower::sampler::AGENTMUX_TASK_ID, TowerTaskKind::Agentmux, Some(0.1), 1, vec![]),
167        ]);
168        let stats = from_snapshot(&snap);
169        assert_eq!(
170            stats,
171            vec![
172                // Resident memory summed over the processes, not the task's private total.
173                PaneStat { block_id: "term-1".into(), cpu_pct: Some(25.0), mem: 1010 + 1011, pids: 2, shell: (10, 111) },
174                PaneStat { block_id: "agent-1".into(), cpu_pct: Some(150.0), mem: 1020, pids: 1, shell: (20, 222) },
175            ]
176        );
177    }
178
179    #[test]
180    fn a_first_sample_has_no_rate_yet_and_a_task_without_a_main_process_has_no_shell() {
181        let snap = snapshot(vec![task("agent-2", TowerTaskKind::Agent, None, 10, vec![process(30, TowerProcessRole::Support, 5)])]);
182        let s = &from_snapshot(&snap)[0];
183        assert_eq!((s.cpu_pct, s.shell), (None, (0, 0)));
184    }
185}