Skip to main content

agentmux_srv_core/backend/
blockstats_detail.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a terminal's stats badge tooltip shows beyond the badge's own CPU and
5//! memory (`blockstats.detail`), and the badge's peak memory.
6//!
7//! The badge (`sysinfo::run_sysinfo_loop`, through `sampler::panes`) counts
8//! the pane's processes as Tower groups them: its Job Object or cgroup, else
9//! its shell's tree. The tooltip reads the same Tower task ([`from_task`]), so
10//! it lists the processes the badge counts: their names, when the shell
11//! started, and two more memory figures, private and committed. It shares
12//! Tower's process snapshot, which is reused within 900 ms, so an open
13//! tooltip adds no second read of the process table.
14//!
15//! A remote pane (SSH, WSL) is measured on the machine it is connected to,
16//! by AgentMux's helper there (`PaneProcs`); [`remote`] turns its answer
17//! into the badge's figures, with a peak kept here.
18//! SPEC_TERMINAL_STATS_BADGE_REMOTE_PANES_2026_10_12.md.
19
20use std::collections::HashMap;
21use std::sync::{Mutex, OnceLock};
22use std::time::{Duration, Instant};
23
24use agentmux_remote::fsproto::{PaneFound, PaneFrame};
25
26use crate::backend::rpc_types::{
27    BlockStatsFigures, BlockStatsHost, BlockStatsName, BlockStatsRemote, TowerProcess, TowerProcessRole, TowerTask,
28};
29
30/// The tooltip's numbers for a pane's Tower task. `memory_metric` is the
31/// snapshot's: what each process's private memory measures.
32pub fn from_task(task: &TowerTask, memory_metric: &str) -> BlockStatsFigures {
33    let procs = &task.processes;
34    let main = procs.iter().position(|p| p.role == Some(TowerProcessRole::Main));
35    // The shell first, then the rest in the task's order.
36    let ordered = main.into_iter().chain((0..procs.len()).filter(|&i| Some(i) != main));
37    let mut names: Vec<BlockStatsName> = Vec::new();
38    for i in ordered {
39        let name = display_name(&procs[i].name);
40        match names.iter_mut().find(|n| n.name == name) {
41            Some(n) => n.count += 1,
42            None => names.push(BlockStatsName { name: name.to_string(), count: 1 }),
43        }
44    }
45    // The shell stays first; the rest, most numerous first (stable: ties keep
46    // the task's order).
47    names[usize::from(main.is_some())..].sort_by(|a, b| b.count.cmp(&a.count));
48
49    // A figure no process reports is absent, not zero.
50    let sum = |f: fn(&TowerProcess) -> Option<u64>| procs.iter().filter_map(f).reduce(|a, b| a + b);
51    BlockStatsFigures {
52        processes: procs.len() as u32,
53        names,
54        started_at_ms: main.and_then(|i| procs[i].started_at_ms),
55        cpu: None,
56        mem_resident: None,
57        mem_private: sum(|p| p.mem),
58        mem_commit: sum(|p| p.mem_commit),
59        unmeasured: None,
60        memory_metric: memory_metric.to_string(),
61    }
62}
63
64/// A remote pane's helper answer as the badge's figures, with its peak.
65pub fn remote(block_id: &str, f: PaneFrame) -> BlockStatsRemote {
66    let percent = |milli: u64| milli as f64 / 10.0;
67    let host = BlockStatsHost {
68        cpu_count: f.cpu_count,
69        cpu: f.host_cpu_milli.map(percent),
70        mem: f.host_mem,
71        processes: f.host_processes,
72        unmeasured: f.host_unmeasured,
73        memory_metric: f.memory_metric.clone(),
74    };
75    let found = match f.found {
76        PaneFound::Session => "session",
77        PaneFound::Marker => "marker",
78        PaneFound::None => "none",
79    };
80    let figures = (f.found != PaneFound::None).then(|| BlockStatsFigures {
81        processes: f.processes,
82        names: f.names.into_iter().map(|(name, count)| BlockStatsName { name, count }).collect(),
83        started_at_ms: f.started_at_ms,
84        cpu: f.cpu_milli.map(percent),
85        mem_resident: f.mem_resident,
86        mem_private: f.mem,
87        mem_commit: None,
88        unmeasured: Some(f.unmeasured),
89        memory_metric: f.memory_metric,
90    });
91    let peak = figures.as_ref().and_then(|fig| {
92        let mem = fig.mem_resident?;
93        Some(remote_peaks().lock().unwrap().observe(block_id, (0, fig.started_at_ms.unwrap_or(0)), mem))
94    });
95    BlockStatsRemote { found: found.to_string(), figures, host: Some(host), peak, reason: None }
96}
97
98/// A remote pane whose machine couldn't be asked, and why.
99pub fn remote_unavailable(reason: String) -> BlockStatsRemote {
100    BlockStatsRemote { found: "unavailable".to_string(), figures: None, host: None, peak: None, reason: Some(reason) }
101}
102
103/// Remote panes' peaks, by pane and shell (its start: the PID is the other
104/// machine's). A pane not asked about for [`REMOTE_PEAK_IDLE`] is forgotten.
105fn remote_peaks() -> &'static Mutex<RemotePeaks> {
106    static PEAKS: OnceLock<Mutex<RemotePeaks>> = OnceLock::new();
107    PEAKS.get_or_init(Default::default)
108}
109
110const REMOTE_PEAK_IDLE: Duration = Duration::from_secs(600);
111
112#[derive(Default)]
113struct RemotePeaks {
114    peaks: Peaks,
115    seen: HashMap<String, Instant>,
116}
117
118impl RemotePeaks {
119    fn observe(&mut self, block_id: &str, shell: Shell, mem: u64) -> u64 {
120        let now = Instant::now();
121        self.seen.insert(block_id.to_string(), now);
122        self.seen.retain(|_, at| now.duration_since(*at) < REMOTE_PEAK_IDLE);
123        let seen = &self.seen;
124        self.peaks.retain(|id| seen.contains_key(id));
125        self.peaks.observe(block_id, shell, mem)
126    }
127}
128
129/// An executable's name as a person calls it: `pwsh`, not `pwsh.exe`.
130fn display_name(name: &str) -> &str {
131    let n = name.len();
132    if n > 4 && name.is_char_boundary(n - 4) && name[n - 4..].eq_ignore_ascii_case(".exe") {
133        &name[..n - 4]
134    } else {
135        name
136    }
137}
138
139/// The highest memory each pane's badge has shown since AgentMux started
140/// watching its shell. A new shell in the same pane (a restart) starts over.
141#[derive(Debug, Default)]
142pub struct Peaks {
143    by_block: HashMap<String, (Shell, u64)>,
144}
145
146/// Which shell a peak is for: its PID and start time, so a restarted shell
147/// that got the old one's PID back is still a new shell.
148pub type Shell = (u32, u64);
149
150impl Peaks {
151    /// Record the badge's `mem` for `block_id`, whose shell is `shell`; its
152    /// peak so far.
153    pub fn observe(&mut self, block_id: &str, shell: Shell, mem: u64) -> u64 {
154        let entry = self.by_block.entry(block_id.to_string()).or_insert((shell, mem));
155        if entry.0 != shell {
156            *entry = (shell, mem);
157        }
158        entry.1 = entry.1.max(mem);
159        entry.1
160    }
161
162    /// Forget every pane `keep` says no longer has stats.
163    pub fn retain(&mut self, keep: impl Fn(&str) -> bool) {
164        self.by_block.retain(|id, _| keep(id));
165    }
166}
167
168#[cfg(test)]
169mod tests {
170    use super::*;
171
172    fn proc(pid: u32, role: TowerProcessRole, started: u64, name: &str, private: u64, commit: Option<u64>) -> TowerProcess {
173        TowerProcess {
174            pid,
175            role: Some(role),
176            started_at_ms: Some(started),
177            name: name.to_string(),
178            mem: Some(private),
179            mem_resident: Some(private * 2),
180            mem_commit: commit,
181            ..Default::default()
182        }
183    }
184
185    fn task(processes: Vec<TowerProcess>) -> TowerTask {
186        TowerTask {
187            id: "term-1".to_string(),
188            kind: crate::backend::rpc_types::TowerTaskKind::Terminal,
189            label: "Terminal".to_string(),
190            tracking: "high".to_string(),
191            cpu: None,
192            cpu_account: false,
193            mem: 0,
194            processes,
195            exited: None,
196        }
197    }
198
199    /// A tracked pane: its shell isn't first in the tracker's list.
200    fn tracked() -> TowerTask {
201        use TowerProcessRole::{Main, Started, Support};
202        task(vec![
203            proc(13, Started, 2_500, "git.exe", 1, Some(2)),
204            proc(11, Started, 2_000, "node.exe", 20, Some(40)),
205            proc(10, Main, 1_000, "pwsh.exe", 10, Some(90)),
206            proc(15, Support, 900, "conhost.exe", 3, Some(6)),
207            proc(12, Started, 3_000, "node.exe", 5, Some(8)),
208        ])
209    }
210
211    #[test]
212    fn sums_every_process_of_the_task() {
213        let d = from_task(&tracked(), "private working set");
214        assert_eq!(d.processes, 5);
215        assert_eq!(d.started_at_ms, Some(1_000), "the shell's start");
216        assert_eq!(d.mem_private, Some(1 + 20 + 10 + 3 + 5));
217        assert_eq!(d.mem_commit, Some(2 + 40 + 90 + 6 + 8));
218        assert_eq!((d.cpu, d.mem_resident, d.unmeasured), (None, None, None));
219        assert_eq!(d.memory_metric, "private working set");
220    }
221
222    #[test]
223    fn names_the_shell_first_then_the_most_numerous() {
224        let d = from_task(&tracked(), "");
225        let names: Vec<(&str, u32)> = d.names.iter().map(|n| (n.name.as_str(), n.count)).collect();
226        // Ties keep the task's order: git before conhost.
227        assert_eq!(names, [("pwsh", 1), ("node", 2), ("git", 1), ("conhost", 1)]);
228    }
229
230    #[test]
231    fn a_figure_no_process_reports_is_absent_not_zero() {
232        let d = from_task(&task(vec![proc(20, TowerProcessRole::Main, 1_500, "bash", 7, None)]), "");
233        assert_eq!(d.processes, 1);
234        assert_eq!(d.mem_private, Some(7));
235        assert_eq!(d.mem_commit, None, "committed memory is Windows-only");
236        let empty = from_task(&task(vec![]), "");
237        assert_eq!((empty.processes, empty.mem_private, empty.names.len()), (0, None, 0));
238    }
239
240    #[test]
241    fn a_task_without_its_shell_has_no_start_and_sorts_every_name() {
242        use TowerProcessRole::Support;
243        let d = from_task(
244            &task(vec![
245                proc(30, Support, 5, "git", 1, None),
246                proc(31, Support, 6, "node", 1, None),
247                proc(32, Support, 7, "node", 1, None),
248            ]),
249            "",
250        );
251        assert_eq!(d.started_at_ms, None);
252        assert_eq!(d.names[0].name, "node");
253    }
254
255    #[test]
256    fn display_name_drops_only_a_trailing_exe() {
257        assert_eq!(display_name("pwsh.exe"), "pwsh");
258        assert_eq!(display_name("Code.EXE"), "Code");
259        assert_eq!(display_name("bash"), "bash");
260        assert_eq!(display_name(".exe"), ".exe");
261        assert_eq!(display_name("exe"), "exe");
262    }
263
264    fn frame(found: PaneFound, started: u64, resident: u64) -> PaneFrame {
265        PaneFrame {
266            found,
267            processes: 3,
268            names: vec![("bash".into(), 1), ("node".into(), 2)],
269            started_at_ms: Some(started),
270            cpu_milli: Some(1_250),
271            mem: Some(40 << 20),
272            mem_resident: Some(resident),
273            unmeasured: 0,
274            memory_metric: "anonymous resident + swap".into(),
275            cpu_count: 8,
276            host_cpu_milli: Some(3_000),
277            host_mem: 6 << 30,
278            host_processes: 400,
279            host_unmeasured: 0,
280        }
281    }
282
283    #[test]
284    fn a_remote_answer_becomes_the_badges_figures_and_peak() {
285        let r = remote("rb-1", frame(PaneFound::Session, 1_000, 90));
286        assert_eq!(r.found, "session");
287        let fig = r.figures.unwrap();
288        assert_eq!((fig.cpu, fig.mem_resident, fig.processes), (Some(125.0), Some(90), 3));
289        assert_eq!(fig.names[0].name, "bash");
290        let host = r.host.unwrap();
291        assert_eq!((host.cpu, host.cpu_count, host.processes), (Some(300.0), 8, 400));
292        assert_eq!(r.peak, Some(90));
293        assert_eq!(remote("rb-1", frame(PaneFound::Session, 1_000, 60)).peak, Some(90), "the peak holds");
294        assert_eq!(remote("rb-1", frame(PaneFound::Marker, 2_000, 50)).peak, Some(50), "a new shell starts over");
295    }
296
297    #[test]
298    fn a_remote_pane_found_by_neither_way_has_only_the_hosts_figures() {
299        let r = remote("rb-2", frame(PaneFound::None, 0, 0));
300        assert_eq!((r.found.as_str(), r.figures, r.peak), ("none", None, None));
301        assert!(r.host.is_some());
302        let u = remote_unavailable("no helper".into());
303        assert_eq!((u.found.as_str(), u.reason.as_deref(), u.host), ("unavailable", Some("no helper"), None));
304    }
305
306    #[test]
307    fn a_peak_holds_until_the_shell_changes() {
308        let mut peaks = Peaks::default();
309        assert_eq!(peaks.observe("b", (10, 1_000), 100), 100);
310        assert_eq!(peaks.observe("b", (10, 1_000), 180), 180);
311        assert_eq!(peaks.observe("b", (10, 1_000), 90), 180, "a trim doesn't lower the peak");
312        assert_eq!(peaks.observe("b", (11, 2_000), 50), 50, "a restarted shell starts over");
313        assert_eq!(peaks.observe("b", (11, 3_000), 40), 40, "even with the old shell's PID");
314        peaks.retain(|id| id != "b");
315        assert_eq!(peaks.observe("b", (11, 3_000), 30), 30, "a forgotten pane starts over");
316    }
317}