Skip to main content

agentmux_srv_core/backend/tower/
sampler.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Tower: CPU and memory per task, for the read-only task manager pane
5//! (SPEC_TOWER_TASK_MANAGER_PANE_2026_10_08.md).
6//!
7//! A **task** is a pane and every process it started, plus one more for
8//! AgentMux itself. Each sample takes one process snapshot
9//! (`agentmux_procstats`) and groups it:
10//!
11//! 1. **The pane's tracker** (`process_tracker`): a Job Object or cgroup on
12//!    an agent, which nothing it starts can leave; a best-effort scan on
13//!    macOS.
14//! 2. **The pane's process tree** where there is no tracker membership (a
15//!    terminal on Linux or macOS): descendants of its shell.
16//! 3. **Sticky membership**: a process seen in a task stays in it until it
17//!    exits, even after it is reparented away from the tree.
18//! 4. **AgentMux**: the backend's own ancestry while it is AgentMux's
19//!    (launcher, window host) and everything under it no task claimed.
20//!
21//! Sampling is driven by the pane (`tower.sample`): nothing runs while no
22//! Tower is open, and two panes asking at once share a sample.
23
24use std::collections::{HashMap, HashSet, VecDeque};
25use std::sync::{Mutex, OnceLock};
26use std::time::{Duration, Instant};
27
28use agentmux_procstats::{ProcInfo, ProcKey, RateMeter};
29
30use crate::backend::process_tracker::registry::BlockMembers;
31use crate::backend::tower::agentmux::Describer;
32use crate::backend::process_tracker::{agent_started, TrackedProcess, TrackingConfidence};
33use crate::backend::rpc_types::{
34    TowerHost, TowerMachine, TowerProcess, TowerProcessKind, TowerProcessRole, TowerSnapshot, TowerTask, TowerTaskKind,
35};
36use crate::backend::tower::kind;
37
38/// `TowerTask::id` of AgentMux's own processes.
39pub const AGENTMUX_TASK_ID: &str = "agentmux";
40
41/// How often the pane asks while it is visible.
42pub const INTERVAL: Duration = Duration::from_secs(2);
43
44/// A request this soon after the last sample gets that sample: two Tower panes
45/// (or a re-render) don't double the cost or shrink the CPU window.
46const REUSE_WITHIN: Duration = Duration::from_millis(900);
47
48/// A gap longer than this since the last sample starts the CPU rates over, so
49/// a pane that was hidden for minutes doesn't show minutes-long averages.
50const STALE_AFTER: Duration = Duration::from_secs(10);
51
52/// Most processes one task's tree walk takes (a fork bomb shouldn't stall a
53/// sample).
54const MAX_TREE: usize = 2048;
55
56/// How long a task's exited process stays listed (dimmed, with what it
57/// used): long enough to see a build's compilers that a 2 s sample catches
58/// once or never. SPEC_TOWER_AGENT_CENTRIC_VIEWS_2026_10_08.md §5.4.
59const EXITED_LINGER: Duration = Duration::from_secs(60);
60
61/// At most this many exited processes are kept, the newest: a big build
62/// runs thousands of compilers a minute.
63const MAX_EXITED: usize = 500;
64
65/// A task's process that has exited: what it was when last seen.
66#[derive(Clone)]
67struct Exited {
68    info: ProcInfo,
69    task: String,
70    role: TowerProcessRole,
71    /// What its name or command line said it was when last seen: a `node`
72    /// that ran a build stays a build while it lingers.
73    named: TowerProcessKind,
74    peak: Option<u64>,
75    gone: Instant,
76    gone_ms: u64,
77}
78
79/// What the sampler is told about the panes.
80#[derive(Debug, Default)]
81pub struct Inputs {
82    /// Every block with a tracker.
83    pub blocks: Vec<BlockMembers>,
84    /// `(block id, its process)` for blocks registered for per-pane stats
85    /// (terminal shells), the tree walk's starting points.
86    pub roots: Vec<(String, u32)>,
87    /// This backend's PID: where the AgentMux task is found from.
88    pub own_pid: u32,
89}
90
91/// How a block is named and what kind of task it is.
92#[derive(Debug, Clone, Default)]
93pub struct BlockLabel {
94    pub label: String,
95    pub agent: bool,
96    /// An agent pane's provider (`agentProvider`), for its process's logo.
97    pub provider: Option<String>,
98}
99
100#[derive(Debug, Clone, PartialEq)]
101struct Group {
102    id: String,
103    tracking: &'static str,
104    cpu_time_ns: Option<u64>,
105    /// Indices into the snapshot, with each one's role.
106    members: Vec<(usize, TowerProcessRole)>,
107}
108
109#[derive(Debug, Default, PartialEq)]
110struct Grouping {
111    tasks: Vec<Group>,
112    agentmux: Vec<usize>,
113}
114
115fn is_agentmux_process(name: &str) -> bool {
116    name.to_ascii_lowercase().starts_with("agentmux")
117}
118
119fn tracking_label(c: TrackingConfidence) -> &'static str {
120    match c {
121        TrackingConfidence::High => "high",
122        TrackingConfidence::BestEffort => "best_effort",
123        TrackingConfidence::None => "tree",
124    }
125}
126
127/// Group a snapshot into tasks (module doc). Pure: everything it needs is in
128/// its arguments.
129fn group(snap: &[ProcInfo], inputs: &Inputs, sticky: &HashMap<ProcKey, String>) -> Grouping {
130    let by_pid: HashMap<u32, usize> = snap.iter().enumerate().map(|(i, p)| (p.pid, i)).collect();
131    // Parent → children, trusting a parent only if it really is one (a
132    // Windows parent PID can name a newer process that reused it).
133    let mut children: HashMap<usize, Vec<usize>> = HashMap::new();
134    for (i, p) in snap.iter().enumerate() {
135        if let Some(&parent) = p.ppid.and_then(|pp| by_pid.get(&pp)) {
136            if p.is_child_of(&snap[parent]) {
137                children.entry(parent).or_default().push(i);
138            }
139        }
140    }
141    let descendants = |root: usize, claimed: &HashMap<usize, usize>| -> Vec<usize> {
142        let mut out = vec![root];
143        let mut queue = VecDeque::from([root]);
144        while let Some(i) = queue.pop_front() {
145            for &c in children.get(&i).into_iter().flatten() {
146                if out.len() >= MAX_TREE {
147                    return out;
148                }
149                if !claimed.contains_key(&c) && !out.contains(&c) {
150                    out.push(c);
151                    queue.push_back(c);
152                }
153            }
154        }
155        out
156    };
157
158    let mut groups: Vec<Group> = Vec::new();
159    // Snapshot index → its group's index in `groups`.
160    let mut claimed: HashMap<usize, usize> = HashMap::new();
161
162    // 1. Trackers.
163    let mut blocks: Vec<&BlockMembers> = inputs.blocks.iter().collect();
164    blocks.sort_by(|a, b| a.block_id.cmp(&b.block_id));
165    for b in blocks {
166        let members: Vec<usize> = b
167            .pids
168            .iter()
169            .filter_map(|pid| by_pid.get(pid).copied())
170            .filter(|i| !claimed.contains_key(i))
171            .collect();
172        // A tree whose processes all came and went between two samples still
173        // has its CPU account: keep it, so that work is counted. It is shown
174        // only while that account moved (`render`).
175        if members.is_empty() && b.cpu_time_ns.is_none() {
176            continue;
177        }
178        let tracked: Vec<TrackedProcess> = members
179            .iter()
180            .map(|&i| TrackedProcess {
181                pid: snap[i].pid,
182                command: snap[i].name.clone(),
183                rss_bytes: 0,
184                started_at_ms: 0,
185                parent_pid: snap[i].ppid,
186                exe: String::new(),
187            })
188            .collect();
189        let started: HashSet<u32> = agent_started(tracked, &b.roots).into_iter().map(|p| p.pid).collect();
190        let gi = groups.len();
191        groups.push(Group {
192            id: b.block_id.clone(),
193            tracking: tracking_label(b.confidence),
194            cpu_time_ns: b.cpu_time_ns,
195            members: members
196                .iter()
197                .map(|&i| {
198                    let pid = snap[i].pid;
199                    let role = if b.roots.contains(&pid) {
200                        TowerProcessRole::Main
201                    } else if started.contains(&pid) {
202                        TowerProcessRole::Started
203                    } else {
204                        TowerProcessRole::Support
205                    };
206                    (i, role)
207                })
208                .collect(),
209        });
210        for &i in &members {
211            claimed.insert(i, gi);
212        }
213    }
214
215    // 2. Process trees, for blocks the trackers didn't cover.
216    let mut roots: Vec<&(String, u32)> = inputs.roots.iter().collect();
217    roots.sort();
218    for (block_id, pid) in roots {
219        if groups.iter().any(|g| &g.id == block_id) {
220            continue;
221        }
222        let Some(&root) = by_pid.get(pid) else { continue };
223        if claimed.contains_key(&root) {
224            continue;
225        }
226        let tree = descendants(root, &claimed);
227        let gi = groups.len();
228        groups.push(Group {
229            id: block_id.clone(),
230            tracking: tracking_label(TrackingConfidence::None),
231            cpu_time_ns: None,
232            members: tree
233                .iter()
234                .map(|&i| (i, if i == root { TowerProcessRole::Main } else { TowerProcessRole::Started }))
235                .collect(),
236        });
237        for i in tree {
238            claimed.insert(i, gi);
239        }
240    }
241
242    // 3. Sticky: still alive, not claimed this round, its task still here.
243    let by_key: HashMap<ProcKey, usize> = snap.iter().enumerate().map(|(i, p)| (p.key(), i)).collect();
244    let mut sticky: Vec<(&ProcKey, &String)> = sticky.iter().collect();
245    sticky.sort();
246    for (key, block_id) in sticky {
247        let Some(&i) = by_key.get(key) else { continue };
248        if claimed.contains_key(&i) {
249            continue;
250        }
251        let Some(gi) = groups.iter().position(|g| &g.id == block_id) else { continue };
252        groups[gi].members.push((i, TowerProcessRole::Started));
253        claimed.insert(i, gi);
254    }
255
256    // 4. AgentMux: up from this backend while the parent is AgentMux's, then
257    //    everything under that no task claimed.
258    let mut agentmux = Vec::new();
259    if let Some(&me) = by_pid.get(&inputs.own_pid) {
260        let mut top = me;
261        for _ in 0..16 {
262            let p = &snap[top];
263            let Some(&parent) = p.ppid.and_then(|pp| by_pid.get(&pp)) else { break };
264            if !p.is_child_of(&snap[parent]) || !is_agentmux_process(&snap[parent].name) {
265                break;
266            }
267            top = parent;
268        }
269        if !claimed.contains_key(&top) {
270            agentmux = descendants(top, &claimed);
271        }
272    }
273
274    Grouping { tasks: groups, agentmux }
275}
276
277/// Rows a snapshot sent to another machine carries per list (busiest,
278/// largest), as a remote frame does (`agentmux_remote::procs`).
279pub const SHARED_TOP: usize = 100;
280
281/// Make a snapshot fit to send to a paired device: drop the tasks `hidden`
282/// names (an agent hidden from paired devices) and their processes, keep the
283/// host rows matching every word of `filter`, then only the `top` busiest
284/// and `top` largest of those. Totals keep counting every process.
285pub fn share(snap: &mut TowerSnapshot, top: usize, filter: &str, hidden: &dyn Fn(&str) -> bool) {
286    snap.remote = true;
287    // Asked once per task (`hidden` reads the store), then used for every row.
288    let hidden: HashSet<String> = snap
289        .tasks
290        .iter()
291        .filter(|t| t.kind != TowerTaskKind::Agentmux && hidden(&t.id))
292        .map(|t| t.id.clone())
293        .collect();
294    snap.tasks.retain(|t| !hidden.contains(&t.id));
295    // A task's own list is capped like the host's, so one process-heavy agent
296    // can't make every frame megabytes (its totals still count every process).
297    for t in &mut snap.tasks {
298        keep_top(&mut t.processes, top);
299    }
300    let Some(host) = snap.host.as_mut() else { return };
301    host.processes.retain(|p| p.task.as_ref().is_none_or(|t| !hidden.contains(t)));
302    // Name, PID and the task's label, as the pane's own filter matches.
303    let labels: HashMap<&str, String> = snap.tasks.iter().map(|t| (t.id.as_str(), t.label.to_lowercase())).collect();
304    let words: Vec<String> = filter.to_lowercase().split_whitespace().map(str::to_string).collect();
305    host.processes.retain(|p| {
306        let task = p.task.as_deref().and_then(|t| labels.get(t)).map_or("", String::as_str);
307        let detail = p.detail.as_deref().unwrap_or("").to_lowercase();
308        let hay = format!("{} {} {task} {detail}", p.name.to_lowercase(), p.pid);
309        words.iter().all(|w| hay.contains(w.as_str()))
310    });
311    host.matched = host.processes.len() as u32;
312    keep_top(&mut host.processes, top);
313}
314
315/// Keep the `top` busiest by CPU and the `top` largest by memory (their
316/// union, in their original order).
317fn keep_top(processes: &mut Vec<TowerProcess>, top: usize) {
318    if processes.len() <= top {
319        return;
320    }
321    let mut by_cpu: Vec<usize> = (0..processes.len()).collect();
322    by_cpu.sort_by(|&a, &b| processes[b].cpu.unwrap_or(-1.0).total_cmp(&processes[a].cpu.unwrap_or(-1.0)));
323    let mut by_mem: Vec<usize> = (0..processes.len()).collect();
324    by_mem.sort_by_key(|&i| std::cmp::Reverse(processes[i].mem.map_or(-1, |m| m as i128)));
325    let keep: HashSet<usize> = by_cpu.into_iter().take(top).chain(by_mem.into_iter().take(top)).collect();
326    let mut i = 0;
327    processes.retain(|_| {
328        i += 1;
329        keep.contains(&(i - 1))
330    });
331}
332
333fn proc_id(p: &ProcInfo) -> String {
334    format!("{}:{}", p.pid, p.start_key)
335}
336
337
338struct State {
339    procs: RateMeter<ProcKey>,
340    tasks: RateMeter<String>,
341    sticky: HashMap<ProcKey, String>,
342    /// What each of AgentMux's own processes is (`tower::agentmux`).
343    describer: Describer,
344    /// The last measurement: what a request within [`REUSE_WITHIN`] renders
345    /// from, so it neither costs a second read nor shrinks the CPU window to
346    /// milliseconds (one coarse clock tick over that would read as a spike).
347    last: Option<Sampled>,
348    /// Each live process's most private memory seen.
349    peaks: HashMap<ProcKey, u64>,
350    /// Tasks' processes that exited within [`EXITED_LINGER`], oldest first.
351    exited: VecDeque<Exited>,
352    /// What a generic runtime's command line said (`kind::by_command_line`),
353    /// read once per process: `None` when it said nothing more.
354    refined: HashMap<ProcKey, Option<TowerProcessKind>>,
355}
356
357/// One measurement: the process table, every process's CPU rate, the grouping
358/// and each task's CPU account rate. [`render`] turns it into an answer.
359struct Sampled {
360    at: Instant,
361    /// When the process-table read began: a process started after this may
362    /// be missing from `procs` though it is running.
363    read_started: Instant,
364    ts_ms: u64,
365    procs: Vec<ProcInfo>,
366    rates: Vec<Option<f64>>,
367    grouping: Grouping,
368    account_rates: HashMap<String, Option<f64>>,
369    /// AgentMux's own processes: index → what it is (`TowerProcess::detail`).
370    details: HashMap<usize, String>,
371    /// Each process's peak private memory, by index.
372    peaks: Vec<Option<u64>>,
373    /// Tasks' processes that exited within [`EXITED_LINGER`].
374    exited: Vec<Exited>,
375    /// What each process's name, or a runtime's command line, says it is
376    /// (`tower::kind` rules 4–6), by index. Where it sits is applied in [`render`].
377    named: Vec<TowerProcessKind>,
378}
379
380/// The process-wide sampler. Its state is the previous sample (for CPU
381/// rates) and sticky membership.
382pub struct Tower {
383    state: Mutex<State>,
384}
385
386impl Default for Tower {
387    fn default() -> Self {
388        Self::new()
389    }
390}
391
392impl Tower {
393    pub fn new() -> Self {
394        Self {
395            state: Mutex::new(State {
396                procs: RateMeter::new(),
397                tasks: RateMeter::new(),
398                sticky: HashMap::new(),
399                describer: Describer::default(),
400                last: None,
401                peaks: HashMap::new(),
402                exited: VecDeque::new(),
403                refined: HashMap::new(),
404            }),
405        }
406    }
407
408    pub fn global() -> &'static Tower {
409        static GLOBAL: OnceLock<Tower> = OnceLock::new();
410        GLOBAL.get_or_init(Tower::new)
411    }
412
413    /// The PIDs in the process table of the last sample, if that sample's read
414    /// began at or after `since`: what is missing from it had exited by then.
415    /// `None` for an older sample (one reused within [`REUSE_WITHIN`], the last
416    /// good one before a failed read, or one whose read was already under way),
417    /// which can't speak for a process that started after it.
418    pub fn live_pids_since(&self, since: Instant) -> Option<HashSet<u32>> {
419        let st = self.state.lock().unwrap_or_else(|e| e.into_inner());
420        let last = st.last.as_ref().filter(|l| l.read_started >= since)?;
421        Some(last.procs.iter().map(|p| p.pid).collect())
422    }
423
424    /// A sample (module doc). BLOCKING: reads the process table, and `labels`
425    /// and `renderer` may read the store; call it off the async workers.
426    /// `renderer` says what a renderer PID serves ("window Main"), for the
427    /// AgentMux task's rows (`agentmux::renderer_serves`).
428    pub fn sample(
429        &self,
430        want_host: bool,
431        hostname: &str,
432        inputs: impl FnOnce() -> Inputs,
433        labels: impl Fn(&str) -> Option<BlockLabel>,
434        renderer: impl Fn(u32) -> Option<String>,
435    ) -> std::io::Result<TowerSnapshot> {
436        self.sample_from(agentmux_procstats::snapshot, want_host, hostname, inputs, labels, renderer)
437    }
438
439    /// [`sample`](Self::sample) with the process table read by `snapshot`.
440    fn sample_from(
441        &self,
442        snapshot: impl FnOnce() -> std::io::Result<Vec<ProcInfo>>,
443        want_host: bool,
444        hostname: &str,
445        inputs: impl FnOnce() -> Inputs,
446        labels: impl Fn(&str) -> Option<BlockLabel>,
447        renderer: impl Fn(u32) -> Option<String>,
448    ) -> std::io::Result<TowerSnapshot> {
449        let mut st = self.state.lock().unwrap_or_else(|e| e.into_inner());
450        let fresh = st.last.as_ref().is_some_and(|l| l.at.elapsed() < REUSE_WITHIN);
451        if !fresh {
452            let read_started = Instant::now();
453            let procs = snapshot()?;
454            let now = Instant::now();
455            if st.last.as_ref().is_some_and(|l| now.duration_since(l.at) > STALE_AFTER) {
456                st.procs = RateMeter::new();
457                st.tasks = RateMeter::new();
458            }
459            let mut sampled = advance(&mut st, procs, &inputs(), now, &agentmux_procstats::command_line_of);
460            sampled.read_started = read_started;
461            st.last = Some(sampled);
462        }
463        let last = st.last.as_ref().expect("measured above");
464        Ok(render(last, want_host, hostname, &labels, &renderer))
465    }
466}
467
468/// A pane's name in Tower and on its stats badge: the agent's name, else what
469/// the terminal runs. `None` for a block that no longer exists.
470pub fn block_label(mstore: &crate::backend::storage::store::Store, block_id: &str) -> Option<BlockLabel> {
471    use crate::backend::{blockcontroller, obj};
472    let block = mstore.get::<obj::Block>(block_id).ok().flatten()?;
473    let meta = |key: &str| obj::meta_get_string(&block.meta, key, "");
474    let agent_name = [meta("agentName"), meta("agentId")].into_iter().find(|s| !s.is_empty());
475    let agent = agent_name.is_some()
476        || blockcontroller::get_controller(block_id).is_some_and(|c| c.get_runtime_status().is_agent_pane);
477    let provider = agent.then(|| meta("agentProvider")).filter(|p| !p.is_empty());
478    let label = agent_name.unwrap_or_else(|| {
479        let title = meta("frame:title");
480        let connection = meta("connection");
481        if !title.is_empty() {
482            title
483        } else if !connection.is_empty() && connection != "local" {
484            format!("Terminal ({connection})")
485        } else if agent {
486            "Agent".to_string()
487        } else {
488            "Terminal".to_string()
489        }
490    });
491    Some(BlockLabel { label, agent, provider })
492}
493
494/// Measure: group the table, take every process's and task account's rate
495/// since the previous measurement, and remember sticky membership.
496/// `cmdline` reads a process's command line, for labelling AgentMux's own
497/// processes (`tower::agentmux`) and telling what a runtime in a pane's task
498/// runs (`tower::kind`). Neither command line leaves srv.
499fn advance(
500    st: &mut State,
501    procs: Vec<ProcInfo>,
502    inputs: &Inputs,
503    now: Instant,
504    cmdline: &dyn Fn(ProcKey) -> Option<String>,
505) -> Sampled {
506    let grouping = group(&procs, inputs, &st.sticky);
507    let details = st.describer.describe(&procs, &grouping.agentmux, inputs.own_pid, cmdline);
508    let (peaks, exited) = track_peaks_and_exits(st, &procs, now);
509    let named = name_kinds(st, &procs, &grouping, cmdline);
510    // Every process's rate, every round, so the Host view has rates the
511    // moment it is opened.
512    let rates: Vec<Option<f64>> = procs
513        .iter()
514        .map(|p| p.cpu_ns.and_then(|ns| st.procs.sample(p.key(), ns, now)))
515        .collect();
516    st.procs.finish();
517    let mut account_rates = HashMap::new();
518    let mut sticky = HashMap::new();
519    for g in &grouping.tasks {
520        if let Some(ns) = g.cpu_time_ns {
521            account_rates.insert(g.id.clone(), st.tasks.sample(g.id.clone(), ns, now));
522        }
523        for &(i, _) in &g.members {
524            sticky.insert(procs[i].key(), g.id.clone());
525        }
526    }
527    st.tasks.finish();
528    st.sticky = sticky;
529    Sampled {
530        at: now,
531        read_started: now,
532        ts_ms: agentmux_common::time::now_ms() as u64,
533        procs,
534        rates,
535        grouping,
536        account_rates,
537        details,
538        peaks,
539        exited,
540        named,
541    }
542}
543
544/// What each process's name says it is, and for a generic runtime inside a
545/// pane's task what its command line says: read once per process and
546/// remembered, so a `node` that runs a build is read once, not every 2 s.
547fn name_kinds(
548    st: &mut State,
549    procs: &[ProcInfo],
550    grouping: &Grouping,
551    cmdline: &dyn Fn(ProcKey) -> Option<String>,
552) -> Vec<TowerProcessKind> {
553    let in_task: HashSet<usize> = grouping.tasks.iter().flat_map(|g| g.members.iter().map(|m| m.0)).collect();
554    let mut refined = HashMap::new();
555    let kinds = procs
556        .iter()
557        .enumerate()
558        .map(|(i, p)| {
559            let by_name = kind::by_name(&p.name);
560            if !in_task.contains(&i) || !kind::is_generic_runtime(&p.name) {
561                return by_name;
562            }
563            let said = match st.refined.get(&p.key()) {
564                Some(said) => *said,
565                None => cmdline(p.key()).and_then(|c| kind::by_command_line(&c)),
566            };
567            refined.insert(p.key(), said);
568            said.unwrap_or(by_name)
569        })
570        .collect();
571    // Only live processes are remembered.
572    st.refined = refined;
573    kinds
574}
575
576/// The machine's installed memory, read once: it doesn't change while
577/// AgentMux runs.
578fn installed_memory() -> Option<u64> {
579    static TOTAL: OnceLock<Option<u64>> = OnceLock::new();
580    *TOTAL.get_or_init(|| {
581        let mut sys = sysinfo::System::new();
582        sys.refresh_memory();
583        Some(sys.total_memory()).filter(|&t| t > 0)
584    })
585}
586
587/// What a renderer row adds after its type: the window or pane it serves.
588fn renderer_suffix(detail: &str, pid: u32, renderer: &dyn Fn(u32) -> Option<String>) -> Option<String> {
589    (detail == "Renderer").then(|| renderer(pid)).flatten()
590}
591
592/// Update each process's peak memory, and note the tasks' members that were
593/// in the previous measurement and are gone from this one. Returns the
594/// peaks by index and the exited processes still within [`EXITED_LINGER`].
595fn track_peaks_and_exits(st: &mut State, procs: &[ProcInfo], now: Instant) -> (Vec<Option<u64>>, Vec<Exited>) {
596    let live: HashSet<ProcKey> = procs.iter().map(|p| p.key()).collect();
597    // Only a recent measurement says what exited just now. The sampler runs
598    // while a Tower pane is visible; after a gap (a hidden pane) what is gone
599    // went at any time in it, so nothing is listed as just exited.
600    let recent = st.last.as_ref().filter(|prev| now.duration_since(prev.at) <= STALE_AFTER);
601    if let Some(prev) = recent {
602        let gone_ms = agentmux_common::time::now_ms() as u64;
603        for g in &prev.grouping.tasks {
604            for &(i, role) in &g.members {
605                let p = &prev.procs[i];
606                if live.contains(&p.key()) {
607                    continue;
608                }
609                let peak = st.peaks.get(&p.key()).copied().or(p.mem_private);
610                let named = prev.named.get(i).copied().unwrap_or_else(|| kind::by_name(&p.name));
611                st.exited.push_back(Exited { info: p.clone(), task: g.id.clone(), role, named, peak, gone: now, gone_ms });
612            }
613        }
614    }
615    // Gone past the linger, or (a PID reused with the same key is impossible,
616    // but a process seen gone in one read can reappear in the next) back.
617    st.exited.retain(|e| now.duration_since(e.gone) < EXITED_LINGER && !live.contains(&e.info.key()));
618    while st.exited.len() > MAX_EXITED {
619        st.exited.pop_front();
620    }
621    let mut peaks = HashMap::with_capacity(procs.len());
622    for p in procs {
623        let peak = match (st.peaks.get(&p.key()).copied(), p.mem_private) {
624            (Some(a), Some(b)) => Some(a.max(b)),
625            (a, b) => a.or(b),
626        };
627        if let Some(v) = peak {
628            peaks.insert(p.key(), v);
629        }
630    }
631    st.peaks = peaks;
632    let by_index = procs.iter().map(|p| st.peaks.get(&p.key()).copied()).collect();
633    (by_index, st.exited.iter().cloned().collect())
634}
635
636/// A sum of rates, or `None` when none of them is known yet (a first
637/// sample), never a made-up 0.
638fn sum_known(rates: impl Iterator<Item = Option<f64>>) -> Option<f64> {
639    rates.flatten().fold(None, |acc, r| Some(acc.unwrap_or(0.0) + r))
640}
641
642/// The answer from a measurement. Pure apart from `labels` and `renderer`.
643fn render(
644    s: &Sampled,
645    want_host: bool,
646    hostname: &str,
647    labels: &dyn Fn(&str) -> Option<BlockLabel>,
648    renderer: &dyn Fn(u32) -> Option<String>,
649) -> TowerSnapshot {
650    let (procs, rates, grouping) = (&s.procs, &s.rates, &s.grouping);
651    // Each task's label, asked once, and where each process sits in a task:
652    // what `tower::kind` rules 1–3 need.
653    let task_labels: HashMap<&str, BlockLabel> =
654        grouping.tasks.iter().filter_map(|g| labels(&g.id).map(|l| (g.id.as_str(), l))).collect();
655    let task_kind = |label: &BlockLabel| if label.agent { TowerTaskKind::Agent } else { TowerTaskKind::Terminal };
656    let mut sits: HashMap<usize, (TowerProcessRole, &str)> = HashMap::new();
657    for g in &grouping.tasks {
658        for &(i, role) in &g.members {
659            sits.insert(i, (role, g.id.as_str()));
660        }
661    }
662    let agentmux_members: HashSet<usize> = grouping.agentmux.iter().copied().collect();
663    let kind_and_provider = |i: usize| -> (TowerProcessKind, Option<String>) {
664        let place = sits.get(&i).and_then(|&(role, id)| task_labels.get(id).map(|l| (role, l)));
665        let ctx = kind::Context {
666            task: place.map(|(role, l)| (role, task_kind(l))),
667            agentmux: agentmux_members.contains(&i) || s.details.contains_key(&i),
668        };
669        let kind = kind::classify(ctx, s.named[i]);
670        let provider = match place {
671            Some((TowerProcessRole::Main, l)) if l.agent => l.provider.clone(),
672            _ => None,
673        };
674        (kind, provider)
675    };
676    let row = |i: usize, role: Option<TowerProcessRole>, task: Option<String>| {
677        let p = &procs[i];
678        let (kind, provider) = kind_and_provider(i);
679        TowerProcess {
680            id: proc_id(p),
681            pid: p.pid,
682            ppid: p.ppid,
683            name: p.name.clone(),
684            started_at_ms: p.started_at_ms,
685            cpu: rates[i],
686            mem: p.mem_private,
687            mem_resident: p.mem_resident,
688            mem_commit: p.mem_commit,
689            role,
690            task,
691            detail: s.details.get(&i).map(|d| match renderer_suffix(d, p.pid, renderer) {
692                Some(serves) => format!("{d} · {serves}"),
693                None => d.clone(),
694            }),
695            cpu_time_ns: p.cpu_ns,
696            peak_mem: s.peaks.get(i).copied().flatten(),
697            exited_ms: None,
698            started_by: crate::backend::tool_calls::lookup(p.pid, p.started_at_ms).map(|c| c.description),
699            kind: Some(kind),
700            provider,
701        }
702    };
703    let exited_of = |task: &str| -> Vec<TowerProcess> {
704        s.exited
705            .iter()
706            .filter(|e| e.task == task)
707            .map(|e| TowerProcess {
708                id: proc_id(&e.info),
709                pid: e.info.pid,
710                ppid: e.info.ppid,
711                name: e.info.name.clone(),
712                started_at_ms: e.info.started_at_ms,
713                role: Some(e.role),
714                cpu_time_ns: e.info.cpu_ns,
715                peak_mem: e.peak,
716                exited_ms: Some(e.gone_ms),
717                started_by: crate::backend::tool_calls::lookup(e.info.pid, e.info.started_at_ms).map(|c| c.description),
718                kind: Some(kind::classify(
719                    kind::Context {
720                        task: task_labels.get(e.task.as_str()).map(|l| (e.role, task_kind(l))),
721                        agentmux: false,
722                    },
723                    e.named,
724                )),
725                ..Default::default()
726            })
727            .collect()
728    };
729
730    let mut tasks = Vec::new();
731    for g in &grouping.tasks {
732        let cpu = if g.cpu_time_ns.is_some() {
733            s.account_rates.get(&g.id).copied().flatten()
734        } else {
735            sum_known(g.members.iter().map(|m| rates[m.0]))
736        };
737        let exited = exited_of(&g.id);
738        // Nothing running, nothing used since the last sample and nothing
739        // that just exited: no row.
740        if g.members.is_empty() && cpu.unwrap_or(0.0) <= 0.0 && exited.is_empty() {
741            continue;
742        }
743        let Some(label) = task_labels.get(g.id.as_str()) else { continue };
744        tasks.push(TowerTask {
745            id: g.id.clone(),
746            kind: task_kind(label),
747            label: label.label.clone(),
748            tracking: g.tracking.to_string(),
749            cpu,
750            cpu_account: g.cpu_time_ns.is_some(),
751            mem: g.members.iter().filter_map(|&(i, _)| procs[i].mem_private).sum(),
752            processes: g.members.iter().map(|&(i, role)| row(i, Some(role), None)).collect(),
753            exited: (!exited.is_empty()).then_some(exited),
754        });
755    }
756
757    if !grouping.agentmux.is_empty() {
758        tasks.push(TowerTask {
759            id: AGENTMUX_TASK_ID.to_string(),
760            kind: TowerTaskKind::Agentmux,
761            label: "AgentMux".to_string(),
762            tracking: tracking_label(TrackingConfidence::None).to_string(),
763            cpu: sum_known(grouping.agentmux.iter().map(|&i| rates[i])),
764            cpu_account: false,
765            mem: grouping.agentmux.iter().filter_map(|&i| procs[i].mem_private).sum(),
766            processes: grouping
767                .agentmux
768                .iter()
769                .map(|&i| row(i, Some(TowerProcessRole::Main), None))
770                .collect(),
771            exited: None,
772        });
773    }
774
775    let host = want_host.then(|| {
776        let mut owner: HashMap<usize, String> = HashMap::new();
777        for t in &grouping.tasks {
778            for &(i, _) in &t.members {
779                owner.insert(i, t.id.clone());
780            }
781        }
782        for &i in &grouping.agentmux {
783            owner.insert(i, AGENTMUX_TASK_ID.to_string());
784        }
785        TowerHost {
786            processes: (0..procs.len()).map(|i| row(i, None, owner.get(&i).cloned())).collect(),
787            unmeasured: procs.iter().filter(|p| !p.measured()).count() as u32,
788            cpu: sum_known(rates.iter().copied()),
789            mem: procs.iter().filter_map(|p| p.mem_private).sum(),
790            total: procs.len() as u32,
791            matched: procs.len() as u32,
792        }
793    });
794
795    TowerSnapshot {
796        ts_ms: s.ts_ms,
797        hostname: hostname.to_string(),
798        panes: None,
799        os: std::env::consts::OS.to_string(),
800        cpu_count: agentmux_procstats::cpu_count() as u32,
801        memory_metric: agentmux_procstats::MEMORY_METRIC.to_string(),
802        interval_ms: INTERVAL.as_millis() as u32,
803        remote: false,
804        memory: None,
805        tasks,
806        // Already measured for every process each round (`advance`), so the
807        // totals cost nothing even when the full list isn't asked for.
808        machine: Some(TowerMachine {
809            cpu: sum_known(rates.iter().copied()),
810            mem: procs.iter().filter_map(|p| p.mem_private).sum(),
811            processes: procs.len() as u32,
812            mem_total: installed_memory(),
813            // AgentMux programs no task or group of ours holds: another
814            // instance's (a dev build beside the stable install).
815            agentmux_elsewhere: {
816                let ours: HashSet<usize> = sits.keys().copied().chain(agentmux_members.iter().copied()).collect();
817                let elsewhere: Vec<u64> = (0..procs.len())
818                    .filter(|i| !ours.contains(i) && is_agentmux_process(&procs[*i].name))
819                    .filter_map(|i| procs[i].mem_private)
820                    .collect();
821                (!elsewhere.is_empty()).then(|| elsewhere.iter().sum())
822            },
823        }),
824        host,
825    }
826}
827
828#[cfg(test)]
829mod tests {
830
831    /// A sample reused from before a moment, or none at all, can't say a
832    /// process that started after it has exited.
833    #[test]
834    fn live_pids_answer_only_for_a_sample_read_at_or_after_the_moment_asked() {
835        let tower = Tower::new();
836        let before = Instant::now();
837        assert_eq!(tower.live_pids_since(before), None, "no sample yet");
838        let one = || {
839            Ok(vec![p(42, 1, "sh")])
840        };
841        tower.sample_from(one, false, "", Inputs::default, |_| None, |_| None).unwrap();
842        assert_eq!(tower.live_pids_since(before), Some(HashSet::from([42])));
843        let later = Instant::now() + Duration::from_millis(1);
844        assert_eq!(tower.live_pids_since(later), None, "that sample was read before `later`");
845    }
846
847    /// A read already under way when a shell registered finishes after that
848    /// moment but can still miss the shell: it doesn't count either.
849    #[test]
850    fn a_read_that_began_before_the_moment_asked_does_not_count_though_it_ended_after() {
851        let tower = Tower::new();
852        let mid = std::cell::Cell::new(None);
853        let slow = || {
854            std::thread::sleep(Duration::from_millis(3));
855            mid.set(Some(Instant::now()));
856            std::thread::sleep(Duration::from_millis(3));
857            Ok(vec![p(42, 1, "sh")])
858        };
859        tower.sample_from(slow, false, "", Inputs::default, |_| None, |_| None).unwrap();
860        assert_eq!(tower.live_pids_since(mid.get().unwrap()), None);
861    }
862    use super::*;
863
864    fn build(
865        st: &mut State,
866        procs: &[ProcInfo],
867        inputs: &Inputs,
868        now: Instant,
869        want_host: bool,
870        hostname: &str,
871        labels: &dyn Fn(&str) -> Option<BlockLabel>,
872    ) -> TowerSnapshot {
873        let sampled = advance(st, procs.to_vec(), inputs, now, &|_| None);
874        let snap = render(&sampled, want_host, hostname, labels, &|_| None);
875        // As `Tower::sample_from` does: the next measurement compares to it.
876        st.last = Some(sampled);
877        snap
878    }
879
880    fn state() -> State {
881        State {
882            procs: RateMeter::new(),
883            tasks: RateMeter::new(),
884            sticky: HashMap::new(),
885            describer: Describer::default(),
886            last: None,
887            peaks: HashMap::new(),
888            exited: VecDeque::new(),
889            refined: HashMap::new(),
890        }
891    }
892
893    fn p(pid: u32, ppid: u32, name: &str) -> ProcInfo {
894        ProcInfo {
895            pid,
896            ppid: Some(ppid).filter(|&x| x != 0),
897            start_key: pid as u64 * 10,
898            started_at_ms: Some(pid as u64 * 10),
899            name: name.to_string(),
900            cpu_ns: Some(0),
901            mem_private: Some(1000),
902            mem_resident: Some(2000),
903            mem_commit: None,
904        }
905    }
906
907    fn tracked(block: &str, pids: &[u32], roots: &[u32]) -> BlockMembers {
908        BlockMembers {
909            block_id: block.to_string(),
910            pids: pids.to_vec(),
911            roots: roots.iter().copied().collect(),
912            confidence: TrackingConfidence::High,
913            cpu_time_ns: Some(0),
914        }
915    }
916
917    fn pids_of(snap: &[ProcInfo], idx: &[usize]) -> Vec<u32> {
918        let mut v: Vec<u32> = idx.iter().map(|&i| snap[i].pid).collect();
919        v.sort();
920        v
921    }
922
923    fn task<'a>(g: &'a Grouping, id: &str) -> &'a Group {
924        g.tasks.iter().find(|t| t.id == id).unwrap_or_else(|| panic!("no task {id}: {g:?}"))
925    }
926
927    /// launcher → srv → claude (job) → mcp, bash → node; launcher → cef host
928    /// → renderer. A terminal: srv → pwsh → vim (no tracker).
929    fn machine() -> Vec<ProcInfo> {
930        vec![
931            p(1, 0, "init"),
932            p(100, 1, "agentmux-launcher.exe"),
933            p(110, 100, "agentmux-srv.exe"),
934            p(120, 100, "agentmux-cef.exe"),
935            p(121, 120, "agentmux-cef.exe"),
936            p(200, 110, "claude.exe"),
937            p(201, 200, "agentmux-mcp.exe"),
938            p(202, 200, "bash.exe"),
939            p(203, 202, "node.exe"),
940            p(300, 110, "pwsh.exe"),
941            p(301, 300, "vim.exe"),
942            p(900, 1, "explorer.exe"),
943        ]
944    }
945
946    #[test]
947    fn tracker_members_tree_and_agentmux_are_grouped_with_roles() {
948        let snap = machine();
949        let inputs = Inputs {
950            blocks: vec![tracked("agent-a", &[200, 201, 202, 203], &[200])],
951            roots: vec![("term-b".into(), 300)],
952            own_pid: 110,
953        };
954        let g = group(&snap, &inputs, &HashMap::new());
955        let a = task(&g, "agent-a");
956        let role = |pid: u32| a.members.iter().find(|(i, _)| snap[*i].pid == pid).unwrap().1;
957        assert_eq!(role(200), TowerProcessRole::Main);
958        assert_eq!(role(201), TowerProcessRole::Support, "the MCP server is the agent's plumbing");
959        assert_eq!(role(202), TowerProcessRole::Started);
960        assert_eq!(role(203), TowerProcessRole::Started);
961        assert_eq!(a.tracking, "high");
962
963        let b = task(&g, "term-b");
964        assert_eq!(pids_of(&snap, &b.members.iter().map(|m| m.0).collect::<Vec<_>>()), vec![300, 301]);
965        assert_eq!(b.tracking, "tree");
966
967        // AgentMux: the launcher (srv's AgentMux parent) and everything under
968        // it that no task claimed; not init, not explorer.
969        assert_eq!(pids_of(&snap, &g.agentmux), vec![100, 110, 120, 121]);
970    }
971
972    #[test]
973    fn every_row_says_what_kind_of_process_it_is() {
974        let procs = machine();
975        let inputs = Inputs {
976            blocks: vec![tracked("agent-a", &[200, 201, 202, 203], &[200])],
977            roots: vec![("term-b".into(), 300)],
978            own_pid: 110,
979        };
980        let mut st = state();
981        // The node under the agent runs npm: its command line says so, and is
982        // read once for the process, not on every sample.
983        let reads = std::cell::Cell::new(0);
984        let cmdline = |k: ProcKey| -> Option<String> {
985            (k.pid == 203).then(|| {
986                reads.set(reads.get() + 1);
987                "node /x/node_modules/npm/bin/npm-cli.js ci".to_string()
988            })
989        };
990        let labels = |id: &str| -> Option<BlockLabel> {
991            let agent = id.starts_with("agent");
992            Some(BlockLabel { label: id.into(), agent, provider: agent.then(|| "claude".into()) })
993        };
994        let now = Instant::now();
995        let sampled = advance(&mut st, procs.clone(), &inputs, now, &cmdline);
996        let snap = render(&sampled, true, "h", &labels, &|_| None);
997        let host = snap.host.as_ref().unwrap();
998        let row = |pid: u32| host.processes.iter().find(|p| p.pid == pid).unwrap();
999        use TowerProcessKind as K;
1000        for (pid, want) in [
1001            (200, K::Agents),
1002            (201, K::Agentmux),
1003            (202, K::Shells),
1004            (203, K::Builds),
1005            (300, K::Shells),
1006            (301, K::Editors),
1007            (100, K::Agentmux),
1008            (110, K::Agentmux),
1009            (120, K::Agentmux),
1010            (121, K::Agentmux),
1011            (900, K::System),
1012            (1, K::System),
1013        ] {
1014            assert_eq!(row(pid).kind, Some(want), "pid {pid}");
1015        }
1016        assert_eq!(row(200).provider.as_deref(), Some("claude"), "the agent's own process carries its provider");
1017        assert_eq!(row(202).provider, None);
1018        let agent = snap.tasks.iter().find(|t| t.id == "agent-a").unwrap();
1019        assert!(agent.processes.iter().all(|p| p.kind.is_some()), "a task's rows carry kinds too");
1020        assert!(snap.machine.as_ref().unwrap().mem_total.is_some_and(|t| t > 0), "installed memory is sent");
1021
1022        st.last = Some(sampled);
1023        let second = advance(&mut st, procs.clone(), &inputs, now + Duration::from_secs(2), &cmdline);
1024        assert_eq!(reads.get(), 1, "the command line is remembered for the live process");
1025
1026        // The npm run exits: while it lingers it is still a build, not a bare runtime.
1027        st.last = Some(second);
1028        let gone: Vec<ProcInfo> = procs.into_iter().filter(|p| p.pid != 203).collect();
1029        let third = advance(&mut st, gone, &inputs, now + Duration::from_secs(4), &cmdline);
1030        let snap = render(&third, false, "h", &labels, &|_| None);
1031        let agent = snap.tasks.iter().find(|t| t.id == "agent-a").unwrap();
1032        let exited = agent.exited.as_ref().and_then(|e| e.iter().find(|p| p.pid == 203)).expect("node lingers");
1033        assert_eq!(exited.kind, Some(K::Builds));
1034    }
1035
1036    /// A dev build beside this instance: its programs are AgentMux's, but not
1037    /// this one's, so they are counted apart from the total
1038    /// (SPEC_TOWER_MEMORY_FIRST_AND_AGENTMUX_BREAKDOWN_2026_10_25.md §5.5).
1039    #[test]
1040    fn another_agentmux_instance_is_counted_beside_this_ones_tasks() {
1041        let inputs = Inputs { blocks: vec![], roots: vec![], own_pid: 110 };
1042        let mut procs = machine();
1043        let alone = build(&mut state(), &procs, &inputs, Instant::now(), false, "h", &|_| None);
1044        assert_eq!(alone.machine.as_ref().unwrap().agentmux_elsewhere, None);
1045
1046        procs.push(p(700, 1, "agentmux-launcher.exe"));
1047        procs.push(p(701, 700, "agentmux-cef.exe"));
1048        let snap = build(&mut state(), &procs, &inputs, Instant::now(), false, "h", &|_| None);
1049        assert_eq!(snap.machine.as_ref().unwrap().agentmux_elsewhere, Some(2000));
1050        assert!(
1051            snap.tasks.iter().all(|t| t.processes.iter().all(|p| p.pid != 700 && p.pid != 701)),
1052            "the other instance is not a task of this one"
1053        );
1054    }
1055
1056    #[test]
1057    fn a_tracker_covers_a_block_its_tree_would_have() {
1058        // The terminal has a Job Object too (Windows): its members win.
1059        let snap = machine();
1060        let inputs = Inputs {
1061            blocks: vec![tracked("term-b", &[300, 301], &[300])],
1062            roots: vec![("term-b".into(), 300)],
1063            own_pid: 110,
1064        };
1065        let g = group(&snap, &inputs, &HashMap::new());
1066        assert_eq!(g.tasks.len(), 1);
1067        assert_eq!(task(&g, "term-b").tracking, "high");
1068    }
1069
1070    #[test]
1071    fn a_reparented_process_stays_in_its_task() {
1072        // vim's shell exited; vim was reparented to init.
1073        let mut snap = machine();
1074        snap.retain(|x| x.pid != 300);
1075        snap.iter_mut().find(|x| x.pid == 301).unwrap().ppid = Some(1);
1076        let inputs = Inputs { blocks: vec![], roots: vec![("term-b".into(), 300)], own_pid: 110 };
1077        // No root, no task — unless the task is still around through another
1078        // member; here it isn't, so vim belongs to nobody.
1079        let g = group(&snap, &inputs, &HashMap::from([(snap.iter().find(|x| x.pid == 301).unwrap().key(), "term-b".to_string())]));
1080        assert!(g.tasks.is_empty());
1081
1082        // With the shell alive (a sibling of vim was reparented), sticky
1083        // membership keeps the reparented one in the task.
1084        let mut snap = machine();
1085        snap.push(p(302, 1, "server.exe"));
1086        let sticky = HashMap::from([(snap.last().unwrap().key(), "term-b".to_string())]);
1087        let inputs = Inputs { blocks: vec![], roots: vec![("term-b".into(), 300)], own_pid: 110 };
1088        let g = group(&snap, &inputs, &sticky);
1089        let members: Vec<usize> = task(&g, "term-b").members.iter().map(|m| m.0).collect();
1090        assert_eq!(pids_of(&snap, &members), vec![300, 301, 302]);
1091    }
1092
1093    #[test]
1094    fn a_reused_parent_pid_is_not_trusted() {
1095        // 301's recorded parent (300) exited and a NEWER process got PID 300.
1096        let mut snap = machine();
1097        let newer = snap.iter_mut().find(|x| x.pid == 300).unwrap();
1098        newer.started_at_ms = Some(999_999);
1099        newer.start_key = 999_999;
1100        let inputs = Inputs { blocks: vec![], roots: vec![("term-b".into(), 300)], own_pid: 110 };
1101        let g = group(&snap, &inputs, &HashMap::new());
1102        let members: Vec<usize> = task(&g, "term-b").members.iter().map(|m| m.0).collect();
1103        assert_eq!(pids_of(&snap, &members), vec![300], "vim is not the newer process's child");
1104    }
1105
1106    #[test]
1107    fn agentmux_stops_at_a_parent_that_is_not_agentmux() {
1108        // Run straight from a terminal (task dev): srv's parent is a shell.
1109        let snap = vec![p(1, 0, "init"), p(50, 1, "bash"), p(110, 50, "agentmux-srv"), p(111, 110, "agentmux-srv")];
1110        let g = group(&snap, &Inputs { own_pid: 110, ..Default::default() }, &HashMap::new());
1111        assert_eq!(pids_of(&snap, &g.agentmux), vec![110, 111]);
1112    }
1113
1114    fn label(id: &str) -> Option<BlockLabel> {
1115        Some(BlockLabel { label: format!("label {id}"), agent: id.starts_with("agent"), provider: id.starts_with("agent").then(|| "claude".to_string()) })
1116    }
1117
1118    /// A build's compiler that exits between samples stays in its task's
1119    /// `exited` list for a minute, with all the CPU it used and its peak
1120    /// memory, then goes; it never counts as running.
1121    #[test]
1122    fn a_task_process_that_exits_lingers_a_minute_with_what_it_used() {
1123        let mut st = state();
1124        let t0 = Instant::now();
1125        let mut snap = machine();
1126        let inputs = Inputs { blocks: vec![tracked("agent-a", &[200, 201, 202, 203], &[200])], roots: vec![], own_pid: 110 };
1127        let node = |snap: &mut Vec<ProcInfo>| snap.iter_mut().find(|x| x.pid == 203).unwrap().clone();
1128        let set = |snap: &mut Vec<ProcInfo>, mem: u64, cpu_ns: u64| {
1129            let n = snap.iter_mut().find(|x| x.pid == 203).unwrap();
1130            n.mem_private = Some(mem);
1131            n.cpu_ns = Some(cpu_ns);
1132        };
1133        set(&mut snap, 400, 1_000_000_000);
1134        build(&mut st, &snap, &inputs, t0, false, "host", &label);
1135        set(&mut snap, 100, 2_000_000_000);
1136        let second = build(&mut st, &snap, &inputs, t0 + Duration::from_secs(2), false, "host", &label);
1137        let task = |s: &TowerSnapshot| s.tasks.iter().find(|t| t.id == "agent-a").cloned().unwrap();
1138        let live = task(&second).processes.into_iter().find(|p| p.pid == 203).unwrap();
1139        assert_eq!((live.peak_mem, live.cpu_time_ns), (Some(400), Some(2_000_000_000)), "the peak, not the current");
1140        assert!(task(&second).exited.is_none());
1141
1142        let gone_key = node(&mut snap).key();
1143        snap.retain(|x| x.pid != 203);
1144        let third = build(&mut st, &snap, &inputs, t0 + Duration::from_secs(4), false, "host", &label);
1145        let t = task(&third);
1146        assert!(t.processes.iter().all(|p| p.pid != 203), "an exited process isn't running");
1147        let exited = t.exited.unwrap();
1148        assert_eq!(exited.len(), 1);
1149        let e = &exited[0];
1150        assert_eq!(e.id, format!("{}:{}", gone_key.pid, gone_key.start_key));
1151        assert_eq!((e.peak_mem, e.cpu_time_ns, e.cpu, e.mem), (Some(400), Some(2_000_000_000), None, None));
1152        assert_eq!(e.role, Some(TowerProcessRole::Started));
1153        assert!(e.exited_ms.is_some());
1154
1155        let later = build(&mut st, &snap, &inputs, t0 + Duration::from_secs(4) + EXITED_LINGER, false, "host", &label);
1156        assert!(task(&later).exited.is_none(), "gone after the linger");
1157    }
1158
1159    /// After a gap (no Tower pane visible), what went missing in it isn't
1160    /// listed as just exited.
1161    #[test]
1162    fn processes_gone_during_a_gap_are_not_listed_as_just_exited() {
1163        let mut st = state();
1164        let t0 = Instant::now();
1165        let mut snap = machine();
1166        let inputs = Inputs { blocks: vec![tracked("agent-a", &[200, 201, 202, 203], &[200])], roots: vec![], own_pid: 110 };
1167        build(&mut st, &snap, &inputs, t0, false, "host", &label);
1168        snap.retain(|x| x.pid != 203);
1169        let after_gap = build(&mut st, &snap, &inputs, t0 + STALE_AFTER + Duration::from_secs(1), false, "host", &label);
1170        let task = after_gap.tasks.iter().find(|t| t.id == "agent-a").unwrap();
1171        assert!(task.exited.is_none(), "nothing just exited after a gap");
1172    }
1173
1174    #[test]
1175    fn rates_come_from_the_job_account_and_the_process_deltas() {
1176        let mut st = state();
1177        let t0 = Instant::now();
1178        let mut snap = machine();
1179        let mut inputs = Inputs {
1180            blocks: vec![tracked("agent-a", &[200, 201, 202, 203], &[200])],
1181            roots: vec![("term-b".into(), 300)],
1182            own_pid: 110,
1183        };
1184        let first = build(&mut st, &snap, &inputs, t0, true, "host", &label);
1185        assert!(first.tasks.iter().all(|t| t.cpu.is_none()), "no rates on the first sample");
1186        assert_eq!(first.host.as_ref().unwrap().cpu, None, "nor a made-up 0% for the machine");
1187
1188        // One second later: node used 0.5 s; vim 0.25 s; the agent's job
1189        // account grew by 2 s (a build that already exited used most of it).
1190        snap.iter_mut().find(|x| x.pid == 203).unwrap().cpu_ns = Some(500_000_000);
1191        snap.iter_mut().find(|x| x.pid == 301).unwrap().cpu_ns = Some(250_000_000);
1192        inputs.blocks[0].cpu_time_ns = Some(2_000_000_000);
1193        let second = build(&mut st, &snap, &inputs, t0 + Duration::from_secs(1), true, "host", &label);
1194        let t = |id: &str| second.tasks.iter().find(|t| t.id == id).unwrap();
1195        assert!((t("agent-a").cpu.unwrap() - 2.0).abs() < 1e-9, "the job account, exited members included");
1196        assert!(t("agent-a").cpu_account);
1197        assert!((t("term-b").cpu.unwrap() - 0.25).abs() < 1e-9, "the tree's per-process sum");
1198        assert_eq!(t("agent-a").kind, TowerTaskKind::Agent);
1199        assert_eq!(t("term-b").kind, TowerTaskKind::Terminal);
1200        assert_eq!(t("agent-a").mem, 4000);
1201        assert_eq!(t(AGENTMUX_TASK_ID).kind, TowerTaskKind::Agentmux);
1202
1203        let host = second.host.unwrap();
1204        assert_eq!(host.processes.len(), snap.len());
1205        assert!((host.cpu.unwrap() - 0.75).abs() < 1e-9);
1206        let node = host.processes.iter().find(|x| x.pid == 203).unwrap();
1207        assert_eq!(node.task.as_deref(), Some("agent-a"));
1208        assert!(host.processes.iter().find(|x| x.pid == 900).unwrap().task.is_none());
1209        assert_eq!(node.id, "203:2030");
1210
1211        // The machine's totals come with every sample, the full list or not,
1212        // and are the host list's own.
1213        let machine = second.machine.clone().unwrap();
1214        assert_eq!(machine.cpu, host.cpu);
1215        assert_eq!(machine.mem, host.mem);
1216        assert_eq!(machine.processes as usize, snap.len());
1217        // (`build` measures again: a sample at the same instant has no CPU
1218        // interval, so only what doesn't depend on one is compared.)
1219        let without_list = build(&mut st, &snap, &inputs, t0 + Duration::from_secs(2), false, "host", &label);
1220        assert!(without_list.host.is_none());
1221        let again = without_list.machine.unwrap();
1222        assert_eq!((again.mem, again.processes), (machine.mem, machine.processes));
1223        assert_eq!(first.machine.unwrap().cpu, None, "no made-up 0% on the first sample");
1224    }
1225
1226    /// A build that started and finished between two samples: the tree has
1227    /// no live process, but its Job account grew, and that CPU is reported.
1228    #[test]
1229    fn a_tree_whose_processes_all_exited_still_reports_their_cpu() {
1230        let mut st = state();
1231        let t0 = Instant::now();
1232        let mut inputs = Inputs { blocks: vec![tracked("agent-a", &[], &[200])], roots: vec![], own_pid: 110 };
1233        inputs.blocks[0].cpu_time_ns = Some(1_000_000_000);
1234        let first = build(&mut st, &machine(), &inputs, t0, false, "h", &label);
1235        assert!(first.tasks.iter().all(|t| t.id != "agent-a"), "nothing measured yet, nothing running: no row");
1236        inputs.blocks[0].cpu_time_ns = Some(3_000_000_000);
1237        let second = build(&mut st, &machine(), &inputs, t0 + Duration::from_secs(1), false, "h", &label);
1238        let a = second.tasks.iter().find(|t| t.id == "agent-a").expect("its CPU is reported");
1239        assert!((a.cpu.unwrap() - 2.0).abs() < 1e-9);
1240        assert!(a.processes.is_empty());
1241        // Idle afterwards: the row goes away again.
1242        let third = build(&mut st, &machine(), &inputs, t0 + Duration::from_secs(2), false, "h", &label);
1243        assert!(third.tasks.iter().all(|t| t.id != "agent-a"));
1244    }
1245
1246    /// What a paired device gets: no hidden agent, no row of its processes,
1247    /// the filter applied, only the busiest and largest.
1248    #[test]
1249    fn a_shared_snapshot_hides_hidden_agents_and_keeps_the_top() {
1250        let mut st = state();
1251        let inputs = Inputs {
1252            blocks: vec![tracked("agent-a", &[200, 201, 202, 203], &[200]), tracked("agent-b", &[300, 301], &[300])],
1253            roots: vec![],
1254            own_pid: 110,
1255        };
1256        let mut snap = build(&mut st, &machine(), &inputs, Instant::now(), true, "h", &label);
1257        share(&mut snap, 2, "", &|id| id == "agent-b");
1258        assert!(snap.remote);
1259        assert!(snap.tasks.iter().all(|t| t.id != "agent-b"));
1260        let host = snap.host.as_ref().unwrap();
1261        assert!(host.processes.iter().all(|p| p.task.as_deref() != Some("agent-b")));
1262        assert!(host.processes.len() <= 4, "two lists of two");
1263        assert_eq!(host.total, machine().len() as u32, "totals still count everything");
1264        let a = snap.tasks.iter().find(|t| t.id == "agent-a").unwrap();
1265        assert!(a.processes.len() <= 4, "a task's own list is capped too");
1266        assert_eq!(a.mem, 4000, "but its totals count every process");
1267
1268        let mut snap = build(&mut st, &machine(), &inputs, Instant::now(), true, "h", &label);
1269        share(&mut snap, 100, "node", &|_| false);
1270        assert_eq!(snap.host.as_ref().unwrap().matched, 1);
1271        assert_eq!(snap.host.unwrap().processes[0].name, "node.exe");
1272
1273        // By the task's label, as the pane's filter matches.
1274        let mut snap = build(&mut st, &machine(), &inputs, Instant::now(), true, "h", &label);
1275        share(&mut snap, 100, "agent-b", &|_| false);
1276        let names: Vec<String> = snap.host.unwrap().processes.into_iter().map(|p| p.name).collect();
1277        assert_eq!(names.len(), 2, "{names:?}");
1278    }
1279
1280    #[test]
1281    fn a_block_without_a_label_is_left_out() {
1282        let mut st = state();
1283        let inputs = Inputs { blocks: vec![tracked("gone", &[200], &[200])], roots: vec![], own_pid: 110 };
1284        let s = build(&mut st, &machine(), &inputs, Instant::now(), false, "h", &|_| None);
1285        assert!(s.tasks.iter().all(|t| t.id != "gone"));
1286        assert!(s.host.is_none());
1287    }
1288
1289    /// Opening the Host view right after a Tasks sample renders the same
1290    /// measurement: no second read, so no CPU window of a few milliseconds.
1291    #[test]
1292    fn host_rows_added_within_the_reuse_window_come_from_the_same_measurement() {
1293        let tower = Tower::new();
1294        let reads = std::cell::Cell::new(0);
1295        let table = || {
1296            reads.set(reads.get() + 1);
1297            Ok(machine())
1298        };
1299        let inputs = || Inputs { own_pid: 110, ..Default::default() };
1300        let tasks_only = tower.sample_from(table, false, "h", inputs, label, |_| None).unwrap();
1301        assert!(tasks_only.host.is_none());
1302        let with_host = tower.sample_from(table, true, "h", inputs, label, |_| None).unwrap();
1303        assert_eq!(reads.get(), 1, "one read for both");
1304        assert_eq!(with_host.ts_ms, tasks_only.ts_ms);
1305        assert_eq!(with_host.host.unwrap().processes.len(), machine().len());
1306    }
1307
1308    /// The real sampler on this machine finds this test process as part of
1309    /// "AgentMux"-less grouping without error, and a second request within
1310    /// the reuse window is the same sample.
1311    #[test]
1312    fn a_real_sample_and_its_reuse() {
1313        let tower = Tower::new();
1314        let inputs = || Inputs { own_pid: std::process::id(), ..Default::default() };
1315        let a = tower.sample(true, "h", inputs, |_| None, |_| None).unwrap();
1316        let b = tower.sample(false, "h", inputs, |_| None, |_| None).unwrap();
1317        assert_eq!(a.ts_ms, b.ts_ms, "reused");
1318        assert!(a.host.as_ref().unwrap().processes.iter().any(|x| x.pid == std::process::id()));
1319        assert!(a.cpu_count >= 1);
1320    }
1321}