Skip to main content

agentmux_srv_core/backend/tower/
agentmux.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Tower: what each of AgentMux's own processes is — "GPU", "Renderer",
5//! "Network service", "Server", "Launcher" — so the AgentMux task's rows say
6//! more than one executable name repeated a dozen times.
7//!
8//! Every CEF subprocess runs the host executable, so its name can't tell them
9//! apart (on Windows every one reads "AgentMux"); its command line can, with
10//! `--type=` and `--utility-sub-type=`. A command line can hold secrets, so it
11//! is read here only to pick a label and never leaves this module. On macOS the
12//! helper apps are already named per type ("AgentMux Helper (GPU)"), which is
13//! the fallback when a command line can't be read.
14//!
15//! The window host and the launcher carry no `--type`; they are told apart by
16//! the tree: the host is the parent of CEF subprocesses, the launcher an
17//! ancestor of this backend.
18//!
19//! A renderer also says what it serves — a window, a browser pane, an idle
20//! pool window ([`renderer_serves`]). Only the window host knows that: each
21//! renderer reports its PID to it (`crates/cef/src/renderer_map.rs`), and
22//! Tower asks it for the map while sampling.
23
24use std::collections::{HashMap, HashSet};
25
26use agentmux_procstats::{ProcInfo, ProcKey};
27use serde::Deserialize;
28
29/// What a process's own command line (or, failing that, its name) says.
30#[derive(Debug, Clone, PartialEq)]
31enum Kind {
32    /// A CEF subprocess: its type.
33    Cef(String),
34    /// srv itself in another role (it re-runs its own binary).
35    Srv(&'static str),
36    /// No `--type`: the window host or the launcher, or neither.
37    Plain,
38    /// The OS wouldn't give the command line, and the name says nothing:
39    /// read again on later samples, up to [`READ_ATTEMPTS`] in all, since a
40    /// read can fail on a process that is still starting.
41    Unreadable(u8),
42}
43
44/// How many times a command line that couldn't be read is tried. A process
45/// the OS never lets us read (another user's) is given up on after that.
46const READ_ATTEMPTS: u8 = 5;
47
48/// Remembers each process's [`Kind`], so a command line is read once per
49/// process rather than once per sample. Forgets processes that are gone.
50#[derive(Debug, Default)]
51pub struct Describer {
52    kinds: HashMap<ProcKey, Kind>,
53}
54
55impl Describer {
56    /// A label for each of `members` (indices into `snap`) that has one.
57    /// `cmdline` reads a process's command line (`agentmux_procstats::command_line_of`).
58    pub fn describe(
59        &mut self,
60        snap: &[ProcInfo],
61        members: &[usize],
62        own_pid: u32,
63        cmdline: &dyn Fn(ProcKey) -> Option<String>,
64    ) -> HashMap<usize, String> {
65        let present: HashSet<ProcKey> = members.iter().map(|&i| snap[i].key()).collect();
66        self.kinds.retain(|k, _| present.contains(k));
67        for &i in members {
68            let p = &snap[i];
69            if p.pid == own_pid {
70                continue;
71            }
72            let attempts = match self.kinds.get(&p.key()) {
73                None => 0,
74                Some(Kind::Unreadable(n)) if *n < READ_ATTEMPTS => *n,
75                Some(_) => continue,
76            };
77            let kind = match kind_of(p, cmdline(p.key()).as_deref()) {
78                Kind::Unreadable(_) => Kind::Unreadable(attempts + 1),
79                known => known,
80            };
81            self.kinds.insert(p.key(), kind);
82        }
83
84        let by_pid: HashMap<u32, usize> = members.iter().map(|&i| (snap[i].pid, i)).collect();
85        let parent_of = |i: usize| {
86            let p = &snap[i];
87            p.ppid.and_then(|pp| by_pid.get(&pp).copied()).filter(|&q| p.is_child_of(&snap[q]))
88        };
89        // The window host: whatever CEF subprocesses hang off.
90        let hosts: HashSet<usize> = members
91            .iter()
92            .filter(|&&i| matches!(self.kinds.get(&snap[i].key()), Some(Kind::Cef(_))))
93            .filter_map(|&i| parent_of(i))
94            .collect();
95        // The launcher: this backend's AgentMux ancestors.
96        let mut ancestors = HashSet::new();
97        let mut at = by_pid.get(&own_pid).copied();
98        for _ in 0..16 {
99            let Some(parent) = at.and_then(parent_of) else { break };
100            ancestors.insert(parent);
101            at = Some(parent);
102        }
103
104        let mut out = HashMap::new();
105        for &i in members {
106            let p = &snap[i];
107            let label = if p.pid == own_pid {
108                Some("Server".to_string())
109            } else {
110                match self.kinds.get(&p.key()) {
111                    Some(Kind::Cef(t)) => Some(t.clone()),
112                    Some(Kind::Srv(role)) => Some(role.to_string()),
113                    _ if hosts.contains(&i) => Some("Main process".to_string()),
114                    _ if ancestors.contains(&i) => Some("Launcher".to_string()),
115                    _ => None,
116                }
117            };
118            if let Some(label) = label {
119                out.insert(i, label);
120            }
121        }
122        out
123    }
124}
125
126/// One browser and the renderer serving it, as the window host reports it
127/// (`crates/cef/src/renderer_map.rs`, `POST /agentmux/browser/renderer_map`).
128#[derive(Debug, Clone, PartialEq, Deserialize)]
129pub struct RendererEntry {
130    pub pid: u32,
131    pub label: String,
132    /// The browser's own renderer, not one of its frames' (a cross-site
133    /// iframe's). An older host lists only its own, so absent means yes.
134    #[serde(default = "own_renderer")]
135    pub main: bool,
136    /// A browser pane's block id.
137    #[serde(default)]
138    pub block_id: Option<String>,
139    /// An unpromoted pool window, kept ready and not shown yet.
140    #[serde(default)]
141    pub pool: bool,
142    /// An app window's srv window id.
143    #[serde(default)]
144    pub window_id: Option<String>,
145}
146
147fn own_renderer() -> bool {
148    true
149}
150
151/// The host's `renderer_map` answer (`{ok, data: {renderers}}`) as entries;
152/// none for anything else, so an older host just leaves renderers unnamed.
153pub fn parse_renderer_map(answer: &serde_json::Value) -> Vec<RendererEntry> {
154    answer
155        .get("data")
156        .and_then(|d| d.get("renderers"))
157        .and_then(|r| serde_json::from_value(r.clone()).ok())
158        .unwrap_or_default()
159}
160
161/// What the renderer `pid` serves, for its row: "window Main", "browser pane
162/// github.com", "pool window (idle)", joined when one renderer serves several
163/// (Chromium may share one between same-site browsers). `page` names a
164/// browser pane by its block id, `workspace` a window by its srv id.
165pub fn renderer_serves(
166    entries: &[RendererEntry],
167    pid: u32,
168    page: &dyn Fn(&str) -> Option<String>,
169    workspace: &dyn Fn(&str) -> Option<String>,
170) -> Option<String> {
171    let mut names: Vec<String> = Vec::new();
172    for e in entries.iter().filter(|e| e.pid == pid) {
173        let name = if let Some(block_id) = &e.block_id {
174            let pane = page(block_id).map_or_else(|| "browser pane".to_string(), |p| format!("browser pane {p}"));
175            if e.main {
176                pane
177            } else {
178                format!("a frame in {pane}")
179            }
180        } else if e.pool {
181            "pool window (idle)".to_string()
182        } else {
183            e.window_id
184                .as_deref()
185                .and_then(workspace)
186                .map_or_else(|| "window".to_string(), |w| format!("window {w}"))
187        };
188        if !names.contains(&name) {
189            names.push(name);
190        }
191    }
192    (!names.is_empty()).then(|| names.join(", "))
193}
194
195/// A page URL's host, for a browser pane's renderer row: never its user,
196/// password, port, path or query (`https://user:pass@host:8080/x` → `host`).
197pub fn page_host(url: &str) -> Option<String> {
198    let parsed = url::Url::parse(url).ok()?;
199    parsed.host_str().filter(|h| !h.is_empty()).map(str::to_string)
200}
201
202/// The PID a process sees for itself, which is what a renderer reports.
203///
204/// On Linux, Chromium's namespace sandbox runs renderers in a PID namespace
205/// of their own, where `getpid()` is a small number (2, 3, …) unrelated to
206/// the host PID this backend lists. The kernel records every level in
207/// `/proc/<pid>/status` (`NSpid: <host> … <innermost>`), so a renderer row is
208/// looked up by the innermost one. AgentMux's renderers share one namespace
209/// per instance, and only this instance's processes are looked up, so the
210/// number is unique among them. Elsewhere there is no namespace: the PID.
211pub fn own_view_pid(pid: u32) -> u32 {
212    #[cfg(target_os = "linux")]
213    {
214        if let Some(inner) = std::fs::read_to_string(format!("/proc/{pid}/status"))
215            .ok()
216            .and_then(|s| innermost_ns_pid(&s))
217        {
218            return inner;
219        }
220    }
221    pid
222}
223
224/// The last PID on a `/proc/<pid>/status` `NSpid:` line.
225#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
226fn innermost_ns_pid(status: &str) -> Option<u32> {
227    status
228        .lines()
229        .find_map(|l| l.strip_prefix("NSpid:"))
230        .and_then(|rest| rest.split_whitespace().last())
231        .and_then(|p| p.parse().ok())
232}
233
234fn kind_of(p: &ProcInfo, cmdline: Option<&str>) -> Kind {
235    let Some(cmd) = cmdline else {
236        return mac_helper_type(&p.name).map_or(Kind::Unreadable(1), Kind::Cef);
237    };
238    let name = p.name.to_ascii_lowercase();
239    // The AgentMux group holds every unclaimed descendant of the launcher, not
240    // only AgentMux's binaries, so a `--type=` switch counts only on one of
241    // ours (the host exe, "agentmux-cef", or a macOS "AgentMux Helper").
242    if name.starts_with("agentmux") {
243        if let Some(ty) = switch(cmd, "type") {
244            return Kind::Cef(cef_label(ty, switch(cmd, "utility-sub-type")));
245        }
246    }
247    if name.starts_with("agentmux-srv") {
248        return Kind::Srv(if has_arg(cmd, "__extract") {
249            "Document parser"
250        } else if has_arg(cmd, "--crash-monitor") {
251            "Crash monitor"
252        } else {
253            "Server"
254        });
255    }
256    Kind::Plain
257}
258
259fn args(cmd: &str) -> impl Iterator<Item = &str> {
260    cmd.split_whitespace().map(|a| a.trim_matches('"'))
261}
262
263/// `--name=value` → `value`. Chromium writes its switches in that form, and
264/// none of the values read here contain spaces.
265fn switch<'a>(cmd: &'a str, name: &str) -> Option<&'a str> {
266    let key = format!("--{name}=");
267    args(cmd).find_map(|a| a.strip_prefix(key.as_str()))
268}
269
270fn has_arg(cmd: &str, arg: &str) -> bool {
271    args(cmd).any(|a| a == arg)
272}
273
274fn cef_label(ty: &str, utility_sub_type: Option<&str>) -> String {
275    match ty {
276        "renderer" => "Renderer".to_string(),
277        "gpu-process" => "GPU".to_string(),
278        "utility" => utility_label(utility_sub_type),
279        "crashpad-handler" => "Crash reporter".to_string(),
280        "zygote" => "Zygote".to_string(),
281        "ppapi" | "ppapi-broker" => "Plugin".to_string(),
282        // A fixed label: never text taken from a command line.
283        _ => "Subprocess".to_string(),
284    }
285}
286
287/// `network.mojom.NetworkService` → "Network service".
288fn utility_label(sub_type: Option<&str>) -> String {
289    let Some(service) = sub_type.and_then(|s| s.split('.').next()).filter(|s| !s.is_empty()) else {
290        return "Utility".to_string();
291    };
292    match service {
293        "network" => "Network service".to_string(),
294        "storage" => "Storage service".to_string(),
295        "audio" => "Audio service".to_string(),
296        "video_capture" => "Video capture service".to_string(),
297        "data_decoder" => "Data decoder".to_string(),
298        // A fixed label: never text taken from a command line.
299        _ => "Utility".to_string(),
300    }
301}
302
303/// macOS helper apps are named per type: "AgentMux Helper (GPU)" → "GPU". The
304/// plain "AgentMux Helper" runs utility processes.
305fn mac_helper_type(name: &str) -> Option<String> {
306    let rest = name.strip_prefix("AgentMux Helper")?;
307    let rest = rest.trim();
308    if rest.is_empty() {
309        return Some("Utility".to_string());
310    }
311    let ty = rest.strip_prefix('(')?.strip_suffix(')')?;
312    Some(match ty {
313        "Renderer" | "Alloy" => "Renderer".to_string(),
314        other => other.to_string(),
315    })
316}
317
318#[cfg(test)]
319mod tests {
320    use super::*;
321
322    fn p(pid: u32, ppid: u32, name: &str) -> ProcInfo {
323        ProcInfo {
324            pid,
325            ppid: Some(ppid).filter(|&x| x != 0),
326            start_key: pid as u64 * 10,
327            started_at_ms: Some(pid as u64 * 10),
328            name: name.to_string(),
329            cpu_ns: Some(0),
330            mem_private: Some(1000),
331            mem_resident: Some(2000),
332            mem_commit: None,
333        }
334    }
335
336    /// A Windows portable, as measured: the launcher starts the host and srv;
337    /// the host's CEF subprocesses hang off it; srv has a crash monitor.
338    fn windows_tree() -> (Vec<ProcInfo>, HashMap<u32, &'static str>) {
339        let snap = vec![
340            p(10, 1, "agentmux.exe"),
341            p(20, 10, "agentmux-0.59.18.exe"),
342            p(21, 20, "agentmux-0.59.18.exe"),
343            p(22, 20, "agentmux-0.59.18.exe"),
344            p(23, 20, "agentmux-0.59.18.exe"),
345            p(24, 20, "agentmux-0.59.18.exe"),
346            p(30, 10, "agentmux-srv-0.59.18-windows.x64.exe"),
347            p(31, 30, "agentmux-srv-0.59.18-windows.x64.exe"),
348            p(32, 30, "agentmux-srv-0.59.18-windows.x64.exe"),
349        ];
350        let cmd = HashMap::from([
351            (10, r#""C:\AgentMux\agentmux.exe""#),
352            (20, r#""C:\AgentMux\runtime\agentmux-0.59.18.exe" --some-flag"#),
353            (21, r#""C:\AgentMux\runtime\agentmux-0.59.18.exe" --type=gpu-process --gpu-preferences=abc"#),
354            (22, r#""C:\AgentMux\runtime\agentmux-0.59.18.exe" --type=renderer --renderer-client-id=4"#),
355            (23, r#""C:\AgentMux\runtime\agentmux-0.59.18.exe" --type=utility --utility-sub-type=network.mojom.NetworkService"#),
356            (24, r#""C:\AgentMux\runtime\agentmux-0.59.18.exe" --type=utility --utility-sub-type=video_capture.mojom.VideoCaptureService"#),
357            (31, r#""C:\AgentMux\runtime\agentmux-srv-0.59.18-windows.x64.exe" --crash-monitor"#),
358            (32, r#""C:\AgentMux\runtime\agentmux-srv-0.59.18-windows.x64.exe" __extract --kind pdf"#),
359        ]);
360        (snap, cmd)
361    }
362
363    fn labels(snap: &[ProcInfo], cmd: &HashMap<u32, &str>, own_pid: u32) -> HashMap<u32, String> {
364        let members: Vec<usize> = (0..snap.len()).collect();
365        let read = |k: ProcKey| cmd.get(&k.pid).map(|s| s.to_string());
366        Describer::default()
367            .describe(snap, &members, own_pid, &read)
368            .into_iter()
369            .map(|(i, l)| (snap[i].pid, l))
370            .collect()
371    }
372
373    #[test]
374    fn labels_every_process_of_a_windows_install() {
375        let (snap, cmd) = windows_tree();
376        let got = labels(&snap, &cmd, 30);
377        let want: HashMap<u32, String> = [
378            (10, "Launcher"),
379            (20, "Main process"),
380            (21, "GPU"),
381            (22, "Renderer"),
382            (23, "Network service"),
383            (24, "Video capture service"),
384            (30, "Server"),
385            (31, "Crash monitor"),
386            (32, "Document parser"),
387        ]
388        .into_iter()
389        .map(|(pid, l)| (pid, l.to_string()))
390        .collect();
391        assert_eq!(got, want);
392    }
393
394    #[test]
395    fn a_macos_helper_is_labelled_by_its_name_when_its_command_line_is_unreadable() {
396        let snap = vec![
397            p(10, 1, "agentmux-launcher"),
398            p(20, 10, "agentmux-cef"),
399            p(21, 20, "AgentMux Helper (GPU)"),
400            p(22, 20, "AgentMux Helper (Renderer)"),
401            p(23, 20, "AgentMux Helper"),
402            p(30, 10, "agentmux-srv-0.59.18-darwin.arm64"),
403        ];
404        let got = labels(&snap, &HashMap::new(), 30);
405        assert_eq!(got.get(&21).map(String::as_str), Some("GPU"));
406        assert_eq!(got.get(&22).map(String::as_str), Some("Renderer"));
407        assert_eq!(got.get(&23).map(String::as_str), Some("Utility"));
408        // The helpers make 20 the window host even without command lines.
409        assert_eq!(got.get(&20).map(String::as_str), Some("Main process"));
410        assert_eq!(got.get(&10).map(String::as_str), Some("Launcher"));
411        assert_eq!(got.get(&30).map(String::as_str), Some("Server"));
412    }
413
414    #[test]
415    fn a_process_that_is_neither_host_nor_launcher_gets_no_label() {
416        let snap = vec![p(10, 1, "agentmux.exe"), p(30, 10, "agentmux-srv.exe"), p(40, 30, "agentmux-helper-thing")];
417        let cmd = HashMap::from([(10, "agentmux.exe"), (40, "agentmux-helper-thing --x")]);
418        let got = labels(&snap, &cmd, 30);
419        assert_eq!(got.get(&40), None);
420        assert_eq!(got.get(&10).map(String::as_str), Some("Launcher"));
421    }
422
423    #[test]
424    fn reads_each_command_line_once_and_forgets_exited_processes() {
425        let (snap, cmd) = windows_tree();
426        let members: Vec<usize> = (0..snap.len()).collect();
427        let reads = std::cell::Cell::new(0);
428        let read = |k: ProcKey| {
429            reads.set(reads.get() + 1);
430            cmd.get(&k.pid).map(|s| s.to_string())
431        };
432        let mut d = Describer::default();
433        d.describe(&snap, &members, 30, &read);
434        let first = reads.get();
435        assert_eq!(first, snap.len() - 1, "every process but srv itself, once");
436        d.describe(&snap, &members, 30, &read);
437        assert_eq!(reads.get(), first, "a second sample reads nothing");
438        d.describe(&snap, &members[..2], 30, &read);
439        assert_eq!(d.kinds.len(), 2, "processes no longer present are forgotten");
440    }
441
442    fn entry(pid: u32, label: &str) -> RendererEntry {
443        RendererEntry { pid, label: label.to_string(), main: true, block_id: None, pool: false, window_id: None }
444    }
445
446    #[test]
447    fn names_what_each_renderer_serves() {
448        let entries = vec![
449            RendererEntry { window_id: Some("w1".into()), ..entry(1, "main") },
450            RendererEntry { block_id: Some("b1".into()), ..entry(2, "pane-b1") },
451            RendererEntry { pool: true, ..entry(3, "window-pool-2") },
452            RendererEntry { block_id: Some("gone".into()), ..entry(4, "pane-gone") },
453            entry(5, "floating-7"),
454        ];
455        let page = |id: &str| (id == "b1").then(|| "github.com".to_string());
456        let workspace = |id: &str| (id == "w1").then(|| "Main".to_string());
457        let serves = |pid| renderer_serves(&entries, pid, &page, &workspace);
458        assert_eq!(serves(1).as_deref(), Some("window Main"));
459        assert_eq!(serves(2).as_deref(), Some("browser pane github.com"));
460        assert_eq!(serves(3).as_deref(), Some("pool window (idle)"));
461        assert_eq!(serves(4).as_deref(), Some("browser pane"));
462        assert_eq!(serves(5).as_deref(), Some("window"));
463        assert_eq!(serves(9), None);
464    }
465
466    #[test]
467    fn one_renderer_serving_two_browsers_names_both_once() {
468        let entries = vec![
469            RendererEntry { block_id: Some("b1".into()), ..entry(2, "pane-a") },
470            RendererEntry { block_id: Some("b2".into()), ..entry(2, "pane-b") },
471            RendererEntry { block_id: Some("b3".into()), ..entry(2, "pane-c") },
472        ];
473        let page = |id: &str| Some(if id == "b3" { "a.test" } else { "b.test" }.to_string());
474        let none = |_: &str| None;
475        assert_eq!(
476            renderer_serves(&entries, 2, &page, &none).as_deref(),
477            Some("browser pane b.test, browser pane a.test")
478        );
479    }
480
481    #[test]
482    fn a_cross_site_frames_renderer_says_whose_page_it_is_in() {
483        let entries = vec![
484            RendererEntry { block_id: Some("b1".into()), ..entry(2, "pane-a") },
485            RendererEntry { block_id: Some("b1".into()), main: false, ..entry(3, "pane-a") },
486        ];
487        let page = |_: &str| Some("github.com".to_string());
488        let none = |_: &str| None;
489        assert_eq!(renderer_serves(&entries, 3, &page, &none).as_deref(), Some("a frame in browser pane github.com"));
490        assert_eq!(renderer_serves(&entries, 2, &page, &none).as_deref(), Some("browser pane github.com"));
491    }
492
493    #[test]
494    fn an_older_hosts_entry_is_its_browsers_own_renderer() {
495        let parsed = parse_renderer_map(&serde_json::json!({ "ok": true, "data": { "renderers": [{ "pid": 4, "label": "main" }] } }));
496        assert!(parsed[0].main);
497    }
498
499    #[test]
500    fn a_page_is_named_by_its_host_alone() {
501        assert_eq!(page_host("https://github.com/agentmuxai").as_deref(), Some("github.com"));
502        assert_eq!(page_host("https://user:secret@example.com:8080/a?b=c#d").as_deref(), Some("example.com"));
503        assert_eq!(page_host("http://127.0.0.1:5173/").as_deref(), Some("127.0.0.1"));
504        assert_eq!(page_host("about:blank"), None);
505        assert_eq!(page_host("not a url"), None);
506        assert_eq!(page_host(""), None);
507    }
508
509    #[test]
510    fn a_sandboxed_renderer_is_found_by_the_pid_it_sees_for_itself() {
511        // A renderer in Chromium's PID namespace, as the host sees it: host
512        // PID 48211, PID 3 inside the namespace, which is what it reported.
513        let status = "Name:\tagentmux-cef\nTgid:\t48211\nNSpid:\t48211\t3\nPPid:\t48190\n";
514        assert_eq!(innermost_ns_pid(status), Some(3));
515        // No namespace: one PID on the line.
516        assert_eq!(innermost_ns_pid("NSpid:\t912\n"), Some(912));
517        // An old kernel without the line.
518        assert_eq!(innermost_ns_pid("Name:\tx\nPid:\t912\n"), None);
519    }
520
521    #[test]
522    fn parses_the_hosts_answer_and_tolerates_anything_else() {
523        let answer = serde_json::json!({"ok": true, "data": {"renderers": [
524            {"pid": 7, "label": "main", "pool": false, "window_id": "w1"},
525            {"pid": 8, "label": "pane-x", "block_id": "b1", "pool": false}
526        ]}});
527        let got = parse_renderer_map(&answer);
528        assert_eq!(got.len(), 2);
529        assert_eq!(got[1].block_id.as_deref(), Some("b1"));
530        assert!(parse_renderer_map(&serde_json::json!({"ok": false, "error": "x"})).is_empty());
531        assert!(parse_renderer_map(&serde_json::json!({"ok": true, "data": {"renderers": "nope"}})).is_empty());
532    }
533
534    #[test]
535    fn a_command_line_that_could_not_be_read_is_tried_again_a_few_times() {
536        let (snap, cmd) = windows_tree();
537        let members: Vec<usize> = (0..snap.len()).collect();
538        // The GPU process (21) can't be read at first, then can.
539        let readable = std::cell::Cell::new(false);
540        let reads_of_21 = std::cell::Cell::new(0);
541        let read = |k: ProcKey| {
542            if k.pid == 21 {
543                reads_of_21.set(reads_of_21.get() + 1);
544                if !readable.get() {
545                    return None;
546                }
547            }
548            cmd.get(&k.pid).map(|s| s.to_string())
549        };
550        let mut d = Describer::default();
551        let first = d.describe(&snap, &members, 30, &read);
552        assert_eq!(first.get(&2), None, "unreadable at first: no label yet");
553        readable.set(true);
554        let second = d.describe(&snap, &members, 30, &read);
555        assert_eq!(second.get(&2).map(String::as_str), Some("GPU"));
556        assert_eq!(reads_of_21.get(), 2);
557        d.describe(&snap, &members, 30, &read);
558        assert_eq!(reads_of_21.get(), 2, "read once it's known");
559    }
560
561    #[test]
562    fn a_process_that_can_never_be_read_is_given_up_on() {
563        let snap = vec![p(10, 1, "agentmux.exe"), p(30, 10, "agentmux-srv.exe"), p(40, 30, "agentmux-thing")];
564        let members: Vec<usize> = (0..snap.len()).collect();
565        let reads = std::cell::Cell::new(0);
566        let read = |k: ProcKey| {
567            if k.pid == 40 {
568                reads.set(reads.get() + 1);
569            }
570            None
571        };
572        let mut d = Describer::default();
573        for _ in 0..10 {
574            d.describe(&snap, &members, 30, &read);
575        }
576        assert_eq!(reads.get(), READ_ATTEMPTS as usize);
577    }
578
579    #[test]
580    fn utility_sub_types() {
581        assert_eq!(utility_label(Some("storage.mojom.StorageService")), "Storage service");
582        assert_eq!(utility_label(Some("audio.mojom.AudioService")), "Audio service");
583        assert_eq!(utility_label(Some("proxy_resolver.mojom.ProxyResolverFactory")), "Utility");
584        assert_eq!(utility_label(None), "Utility");
585    }
586
587    #[test]
588    fn other_cef_types() {
589        assert_eq!(cef_label("crashpad-handler", None), "Crash reporter");
590        assert_eq!(cef_label("zygote", None), "Zygote");
591        assert_eq!(cef_label("broker", None), "Subprocess");
592    }
593
594    #[test]
595    fn a_type_switch_on_a_process_that_is_not_ours_means_nothing() {
596        // Some tool the user ran from an AgentMux terminal that wasn't claimed
597        // by a task, with a Chromium-style switch of its own.
598        let snap = vec![
599            p(10, 1, "agentmux.exe"),
600            p(30, 10, "agentmux-srv.exe"),
601            p(40, 30, "electron.exe"),
602        ];
603        let cmd = HashMap::from([(10, "agentmux.exe"), (40, "electron.exe --type=renderer")]);
604        let got = labels(&snap, &cmd, 30);
605        assert_eq!(got.get(&40), None);
606        // And it doesn't make its parent look like the window host.
607        assert_eq!(got.get(&30).map(String::as_str), Some("Server"));
608    }
609}