Skip to main content

agentmux_srv_core/backend/tower/
browsers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `muxspect browsers`: which page each renderer draws, how busy it is, and what the page is doing
5//! (docs/specs/SPEC_RELEASE_BUILD_BROWSER_PAGE_DIAGNOSTIC_2026_11_13.md ยง3.4).
6//!
7//! The window host knows the pages (`page_probe`) and which renderer serves which browser
8//! (`renderer_map`); the operating system knows each process's CPU. This joins the three, with no
9//! I/O, so every case is a unit test: a renderer shared by several browsers, one that serves only a
10//! frame, a pid present in only one sample, a page that did not answer, a Linux namespace pid.
11
12use std::collections::{BTreeMap, HashMap, HashSet};
13
14use agentmux_procstats::ProcInfo;
15use serde::{Deserialize, Serialize};
16
17use super::agentmux::RendererEntry;
18
19/// The host's row for one browser (`crates/cef/src/browser_api/page_probe.rs`).
20#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
21pub struct PageProbe {
22    pub label: String,
23    #[serde(default)]
24    pub role: String,
25    #[serde(default)]
26    pub block_id: Option<String>,
27    #[serde(default)]
28    pub window_id: Option<String>,
29    #[serde(default)]
30    pub origin: String,
31    #[serde(default)]
32    pub answer: String,
33    #[serde(default)]
34    pub visibility: Option<String>,
35    #[serde(default)]
36    pub has_focus: Option<bool>,
37    #[serde(default)]
38    pub animations: Option<u64>,
39    #[serde(default)]
40    pub kinds: Vec<String>,
41    #[serde(default)]
42    pub title: Option<String>,
43    #[serde(default)]
44    pub metrics: Option<BTreeMap<String, f64>>,
45    #[serde(default)]
46    pub error: Option<String>,
47}
48
49const PANE: &str = "browser-pane";
50
51/// The host's `page_probe` answer (`{ok, data: {browsers}}`) as rows; none for anything else, so an
52/// older host just leaves the page facts out. A browser pane's row is cut down again here, whatever
53/// the host sent: a person's page never contributes a title or an animation name.
54pub fn parse_page_probe(answer: &serde_json::Value) -> Vec<PageProbe> {
55    let mut rows: Vec<PageProbe> = answer
56        .get("data")
57        .and_then(|d| d.get("browsers"))
58        .and_then(|r| serde_json::from_value(r.clone()).ok())
59        .unwrap_or_default();
60    for row in rows.iter_mut().filter(|r| r.role == PANE) {
61        row.title = None;
62        row.kinds.clear();
63    }
64    rows
65}
66
67/// One renderer's row (or, with no `pid`, a browser that has none: its page is asleep).
68#[derive(Debug, Clone, PartialEq, Serialize)]
69pub struct BrowserRow {
70    /// The process id as the OS lists it (on Linux the host's, not the sandbox namespace's).
71    pub pid: Option<u32>,
72    pub label: String,
73    pub role: String,
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub block_id: Option<String>,
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub window_id: Option<String>,
78    #[serde(skip_serializing_if = "String::is_empty")]
79    pub origin: String,
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub title: Option<String>,
82    /// How the page's facts were read: `answered`, `asleep`, `frozen`, `no_answer`, `failed`, or
83    /// `unknown` when the host could not be asked.
84    pub answer: String,
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub visibility: Option<String>,
87    #[serde(skip_serializing_if = "Option::is_none")]
88    pub has_focus: Option<bool>,
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub animations: Option<u64>,
91    #[serde(skip_serializing_if = "Vec::is_empty")]
92    pub kinds: Vec<String>,
93    /// Why a page's facts could not be read (`failed`), cut short.
94    #[serde(skip_serializing_if = "Option::is_none")]
95    pub error: Option<String>,
96    /// This renderer serves only a frame of the page (a cross-site iframe), not its main document.
97    pub frame: bool,
98    /// Other browsers the same renderer serves; its CPU is the process's and is not split.
99    #[serde(skip_serializing_if = "Vec::is_empty")]
100    pub shared_with: Vec<String>,
101    /// Percent of one core over the sample.
102    pub cpu_pct: Option<f64>,
103    /// Why there is no CPU figure.
104    #[serde(skip_serializing_if = "Option::is_none")]
105    pub cpu_note: Option<String>,
106    /// With `detail`: percent of the sample the page's main thread spent in each kind of work.
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub main_thread_pct: Option<BTreeMap<String, f64>>,
109}
110
111/// The AgentMux processes that serve no page, for scale next to the page rows.
112#[derive(Debug, Clone, PartialEq, Serialize)]
113pub struct Others {
114    pub processes: usize,
115    pub cpu_pct: f64,
116}
117
118/// Two process snapshots `secs` apart.
119pub struct Sample<'a> {
120    pub before: &'a [ProcInfo],
121    pub after: &'a [ProcInfo],
122    pub secs: f64,
123}
124
125impl Sample<'_> {
126    /// CPU percent of one core for `pid`, or why it has none.
127    fn cpu(&self, pid: u32) -> Result<f64, &'static str> {
128        let after = self.after.iter().find(|p| p.pid == pid).ok_or("not running at the end of the sample")?;
129        let before = self.before.iter().find(|p| p.key() == after.key()).ok_or("started during the sample")?;
130        match (before.cpu_ns, after.cpu_ns) {
131            (Some(b), Some(a)) if self.secs > 0.0 => Ok(a.saturating_sub(b) as f64 / self.secs / 1e9 * 100.0),
132            _ => Err("the OS gave no CPU time for it"),
133        }
134    }
135}
136
137/// Where the main thread's time went, as percent of the interval between the two reads. The page's
138/// own clock (`Timestamp`) is the interval when both reads have it.
139fn main_thread_pct(before: &BTreeMap<String, f64>, after: &BTreeMap<String, f64>, secs: f64) -> Option<BTreeMap<String, f64>> {
140    let interval = match (before.get("Timestamp"), after.get("Timestamp")) {
141        (Some(b), Some(a)) if a > b => a - b,
142        _ => secs,
143    };
144    if interval <= 0.0 {
145        return None;
146    }
147    let out: BTreeMap<String, f64> = after
148        .iter()
149        .filter(|(name, _)| name.as_str() != "Timestamp")
150        .filter_map(|(name, a)| Some((name.clone(), ((a - before.get(name)?) / interval * 100.0).max(0.0))))
151        .collect();
152    (!out.is_empty()).then_some(out)
153}
154
155fn role_of(e: &RendererEntry) -> &'static str {
156    if e.block_id.is_some() {
157        PANE
158    } else if e.pool {
159        "pool-window"
160    } else if e.window_id.is_some() {
161        "app-window"
162    } else {
163        // Not positively AgentMux's own (the host reads such a page as a person's).
164        PANE
165    }
166}
167
168/// A row with the page's facts from `probe` (if the host gave one).
169fn row(label: &str, pid: Option<u32>, entry: Option<&RendererEntry>, probe: Option<&PageProbe>) -> BrowserRow {
170    let blank = PageProbe::default();
171    let p = probe.unwrap_or(&blank);
172    BrowserRow {
173        pid,
174        label: label.to_string(),
175        role: if !p.role.is_empty() { p.role.clone() } else { entry.map_or("", |e| role_of(e)).to_string() },
176        block_id: p.block_id.clone().or_else(|| entry.and_then(|e| e.block_id.clone())),
177        window_id: p.window_id.clone().or_else(|| entry.and_then(|e| e.window_id.clone())),
178        origin: p.origin.clone(),
179        title: p.title.clone(),
180        answer: if probe.is_some() { p.answer.clone() } else { "unknown".to_string() },
181        visibility: p.visibility.clone(),
182        has_focus: p.has_focus,
183        animations: p.animations,
184        kinds: p.kinds.clone(),
185        error: p.error.as_ref().map(|e| e.chars().take(160).collect()),
186        frame: false,
187        shared_with: Vec::new(),
188        cpu_pct: None,
189        cpu_note: None,
190        main_thread_pct: None,
191    }
192}
193
194/// One row per renderer, then one per browser that has none (its page is asleep), busiest first.
195///
196/// `host_pid` maps the pid a renderer reported for itself to the pid the OS lists (the same pid
197/// except on Linux, where the sandbox's PID namespace makes the reported one small and local).
198pub fn browser_rows(
199    entries: &[RendererEntry],
200    probes: &[PageProbe],
201    before_probes: &[PageProbe],
202    sample: &Sample<'_>,
203    host_pid: &dyn Fn(u32) -> Option<u32>,
204) -> Vec<BrowserRow> {
205    let probe_of: HashMap<&str, &PageProbe> = probes.iter().map(|p| (p.label.as_str(), p)).collect();
206    let before_of: HashMap<&str, &PageProbe> = before_probes.iter().map(|p| (p.label.as_str(), p)).collect();
207    let mut by_pid: BTreeMap<u32, Vec<&RendererEntry>> = BTreeMap::new();
208    for e in entries {
209        by_pid.entry(e.pid).or_default().push(e);
210    }
211    let mut served: HashSet<&str> = HashSet::new();
212    let mut rows: Vec<BrowserRow> = Vec::new();
213    for (reported, es) in &by_pid {
214        let mut labels: Vec<&str> = es.iter().map(|e| e.label.as_str()).collect();
215        labels.sort_unstable();
216        labels.dedup();
217        // The browser whose own renderer this is; a renderer that serves only frames is shown under
218        // the first browser it serves, marked as a frame.
219        let main = es.iter().filter(|e| e.main).map(|e| e.label.as_str()).min();
220        let primary = main.unwrap_or(labels[0]);
221        let entry = es.iter().find(|e| e.label == primary).copied();
222        served.extend(labels.iter().copied());
223        let mut r = row(primary, host_pid(*reported), entry, probe_of.get(primary).copied());
224        r.frame = main.is_none();
225        if r.frame {
226            // The facts are the main document's, which another process runs: not this one's.
227            (r.visibility, r.has_focus, r.animations, r.title) = (None, None, None, None);
228            r.kinds.clear();
229        }
230        r.shared_with = labels.iter().filter(|l| **l != primary).map(|l| l.to_string()).collect();
231        match r.pid.map(|pid| sample.cpu(pid)) {
232            Some(Ok(cpu)) => r.cpu_pct = Some(cpu),
233            Some(Err(why)) => r.cpu_note = Some(why.to_string()),
234            None => r.cpu_note = Some("no such process on this computer".to_string()),
235        }
236        // A frame-only renderer's own main thread is not the page's, which the metrics read.
237        if let (false, Some(b), Some(a)) = (r.frame, before_of.get(primary).and_then(|p| p.metrics.as_ref()), probe_of.get(primary).and_then(|p| p.metrics.as_ref())) {
238            r.main_thread_pct = main_thread_pct(b, a, sample.secs);
239        }
240        rows.push(r);
241    }
242    // A browser with no renderer: its page is asleep (or its renderer has not reported yet).
243    let mut rest: Vec<&PageProbe> = probes.iter().filter(|p| !served.contains(p.label.as_str())).collect();
244    rest.sort_by(|a, b| a.label.cmp(&b.label));
245    rows.extend(rest.into_iter().map(|p| row(&p.label, None, None, Some(p))));
246    rows.sort_by(|a, b| {
247        let key = |r: &BrowserRow| r.cpu_pct.unwrap_or(-1.0);
248        key(b).partial_cmp(&key(a)).unwrap_or(std::cmp::Ordering::Equal).then_with(|| a.label.cmp(&b.label))
249    });
250    rows
251}
252
253/// The processes of this AgentMux instance: the launcher above `own_pid` and everything under it.
254/// AgentMux's own executables carry the name, so another program a shell started is not climbed into.
255pub fn instance_pids(snap: &[ProcInfo], own_pid: u32) -> HashSet<u32> {
256    let by_pid: HashMap<u32, &ProcInfo> = snap.iter().map(|p| (p.pid, p)).collect();
257    let parent = |p: &ProcInfo| p.ppid.and_then(|pp| by_pid.get(&pp).copied()).filter(|q| p.is_child_of(q));
258    let ours = |p: &ProcInfo| p.name.to_ascii_lowercase().starts_with("agentmux");
259    let Some(mut root) = by_pid.get(&own_pid).copied() else { return HashSet::new() };
260    for _ in 0..16 {
261        match parent(root).filter(|q| ours(q)) {
262            Some(q) => root = q,
263            None => break,
264        }
265    }
266    snap.iter()
267        .filter(|p| {
268            let mut at = *p;
269            for _ in 0..16 {
270                if at.pid == root.pid {
271                    return true;
272                }
273                match parent(at) {
274                    Some(q) => at = q,
275                    None => return false,
276                }
277            }
278            false
279        })
280        .map(|p| p.pid)
281        .collect()
282}
283
284/// The instance's processes that serve no page (GPU, network service, window host, srv, launcher),
285/// and their CPU together, over processes measured in both samples.
286pub fn others(instance: &HashSet<u32>, page_pids: &HashSet<u32>, sample: &Sample<'_>) -> Others {
287    let rest: Vec<u32> = instance.iter().copied().filter(|p| !page_pids.contains(p)).collect();
288    let cpu_pct: f64 = rest.iter().filter_map(|p| sample.cpu(*p).ok()).sum();
289    Others { processes: rest.len(), cpu_pct }
290}
291
292#[cfg(test)]
293mod tests {
294    use super::*;
295    use serde_json::json;
296
297    const SEC: u64 = 1_000_000_000;
298
299    fn proc(pid: u32, ppid: u32, name: &str, cpu_secs: u64) -> ProcInfo {
300        ProcInfo { pid, ppid: Some(ppid), start_key: pid as u64 * 10, started_at_ms: Some(1000 + pid as u64), name: name.into(), cpu_ns: Some(cpu_secs * SEC), mem_private: None, mem_resident: None, mem_commit: None }
301    }
302
303    fn entry(pid: u32, label: &str, main: bool, block_id: Option<&str>, pool: bool) -> RendererEntry {
304        RendererEntry { pid, label: label.into(), main, block_id: block_id.map(Into::into), pool, window_id: None }
305    }
306
307    fn probe(label: &str, role: &str, answer: &str) -> PageProbe {
308        PageProbe { label: label.into(), role: role.into(), answer: answer.into(), visibility: Some("visible".into()), animations: Some(0), ..PageProbe::default() }
309    }
310
311    fn rows(entries: &[RendererEntry], probes: &[PageProbe]) -> Vec<BrowserRow> {
312        let before = [proc(10, 1, "agentmux-cef", 5), proc(20, 1, "agentmux-cef", 5), proc(30, 1, "agentmux-cef", 5)];
313        let after = [proc(10, 1, "agentmux-cef", 8), proc(20, 1, "agentmux-cef", 5), proc(30, 1, "agentmux-cef", 6)];
314        browser_rows(entries, probes, &[], &Sample { before: &before, after: &after, secs: 3.0 }, &Some)
315    }
316
317    #[test]
318    fn cpu_is_the_process_time_over_the_sample() {
319        let r = rows(&[entry(10, "main", true, None, false)], &[probe("main", "app-window", "answered")]);
320        assert_eq!(r.len(), 1);
321        assert_eq!(r[0].cpu_pct, Some(100.0));
322        assert_eq!(r[0].role, "app-window");
323        assert_eq!(r[0].visibility.as_deref(), Some("visible"));
324    }
325
326    #[test]
327    fn a_shared_renderer_is_one_row_that_names_the_others_and_is_not_split() {
328        let r = rows(
329            &[entry(10, "pane-b", true, Some("b2"), false), entry(10, "pane-a", true, Some("b1"), false)],
330            &[probe("pane-a", "browser-pane", "answered"), probe("pane-b", "browser-pane", "answered")],
331        );
332        assert_eq!(r.len(), 1);
333        assert_eq!((r[0].label.as_str(), r[0].shared_with.clone()), ("pane-a", vec!["pane-b".to_string()]));
334        assert_eq!(r[0].cpu_pct, Some(100.0));
335    }
336
337    #[test]
338    fn a_frame_only_renderer_is_a_frame_row_with_the_page_it_belongs_to() {
339        let r = rows(&[entry(10, "pane-a", true, Some("b1"), false), entry(30, "pane-a", false, Some("b1"), false)], &[probe("pane-a", "browser-pane", "answered")]);
340        assert_eq!(r.len(), 2);
341        let frame = r.iter().find(|x| x.pid == Some(30)).unwrap();
342        assert!(frame.frame && frame.label == "pane-a");
343        // The page's facts are its main document's, which the other process runs.
344        assert_eq!((frame.visibility.clone(), frame.animations, frame.has_focus), (None, None, None));
345        let main = r.iter().find(|x| x.pid == Some(10)).unwrap();
346        assert!(!main.frame && main.visibility.as_deref() == Some("visible"));
347    }
348
349    #[test]
350    fn a_frame_only_renderer_is_not_given_the_pages_main_thread_time() {
351        let m = |t: f64, task: f64| BTreeMap::from([("Timestamp".to_string(), t), ("TaskDuration".to_string(), task)]);
352        let mut before = probe("pane-a", "browser-pane", "answered");
353        before.metrics = Some(m(1.0, 0.0));
354        let mut after = before.clone();
355        after.metrics = Some(m(3.0, 1.0));
356        let procs = [proc(10, 1, "agentmux-cef", 0), proc(30, 1, "agentmux-cef", 0)];
357        let sample = Sample { before: &procs, after: &procs, secs: 3.0 };
358        let entries = [entry(10, "pane-a", true, Some("b1"), false), entry(30, "pane-a", false, Some("b1"), false)];
359        let r = browser_rows(&entries, &[after], &[before], &sample, &Some);
360        assert!(r.iter().find(|x| x.pid == Some(10)).unwrap().main_thread_pct.is_some());
361        assert!(r.iter().find(|x| x.pid == Some(30)).unwrap().main_thread_pct.is_none());
362    }
363
364    #[test]
365    fn a_failed_page_says_why() {
366        let mut p = probe("main", "app-window", "failed");
367        p.error = Some("CDP Page.getFrameTree: no main frame".into());
368        let r = rows(&[entry(10, "main", true, None, false)], &[p]);
369        assert_eq!(r[0].error.as_deref(), Some("CDP Page.getFrameTree: no main frame"));
370    }
371
372    #[test]
373    fn a_pid_in_only_one_sample_has_no_cpu_and_says_why() {
374        let before = [proc(10, 1, "agentmux-cef", 5)];
375        let after = [proc(10, 1, "agentmux-cef", 8), proc(20, 1, "agentmux-cef", 1)];
376        let sample = Sample { before: &before, after: &after, secs: 3.0 };
377        let r = browser_rows(&[entry(20, "new", true, None, false), entry(99, "gone", true, None, false)], &[], &[], &sample, &Some);
378        let new = r.iter().find(|x| x.pid == Some(20)).unwrap();
379        assert_eq!((new.cpu_pct, new.cpu_note.as_deref()), (None, Some("started during the sample")));
380        assert_eq!(r.iter().find(|x| x.pid == Some(99)).unwrap().cpu_note.as_deref(), Some("not running at the end of the sample"));
381    }
382
383    #[test]
384    fn a_page_that_did_not_answer_keeps_its_pid_and_cpu() {
385        let r = rows(&[entry(10, "main", true, None, false)], &[probe("main", "app-window", "no_answer")]);
386        assert_eq!((r[0].answer.as_str(), r[0].cpu_pct), ("no_answer", Some(100.0)));
387    }
388
389    #[test]
390    fn a_browser_with_no_renderer_is_a_row_with_no_pid() {
391        let r = rows(&[entry(10, "main", true, None, false)], &[probe("main", "app-window", "answered"), probe("pane-z", "browser-pane", "asleep")]);
392        let asleep = r.iter().find(|x| x.label == "pane-z").unwrap();
393        assert_eq!((asleep.pid, asleep.answer.as_str(), asleep.cpu_pct), (None, "asleep", None));
394    }
395
396    #[test]
397    fn an_older_host_without_page_facts_still_gives_rows() {
398        let r = rows(&[entry(10, "window-pool-1", true, None, true)], &[]);
399        assert_eq!((r[0].role.as_str(), r[0].answer.as_str()), ("pool-window", "unknown"));
400    }
401
402    #[test]
403    fn a_linux_namespace_pid_is_shown_as_the_hosts() {
404        let before = [proc(4242, 1, "agentmux-cef", 0)];
405        let after = [proc(4242, 1, "agentmux-cef", 3)];
406        let sample = Sample { before: &before, after: &after, secs: 3.0 };
407        let r = browser_rows(&[entry(7, "main", true, None, false)], &[], &[], &sample, &|p| (p == 7).then_some(4242));
408        assert_eq!((r[0].pid, r[0].cpu_pct), (Some(4242), Some(100.0)));
409    }
410
411    #[test]
412    fn rows_are_busiest_first() {
413        let r = rows(&[entry(10, "a", true, None, false), entry(20, "b", true, None, false), entry(30, "c", true, None, false)], &[]);
414        assert_eq!(r.iter().map(|x| x.label.as_str()).collect::<Vec<_>>(), ["a", "c", "b"]);
415    }
416
417    #[test]
418    fn the_main_thread_split_uses_the_pages_own_clock() {
419        let m = |t: f64, task: f64, script: f64| BTreeMap::from([("Timestamp".to_string(), t), ("TaskDuration".to_string(), task), ("ScriptDuration".to_string(), script)]);
420        let got = main_thread_pct(&m(100.0, 1.0, 0.5), &m(102.0, 1.5, 1.5), 3.0).unwrap();
421        assert_eq!((got["TaskDuration"], got["ScriptDuration"]), (25.0, 50.0));
422        assert!(!got.contains_key("Timestamp"));
423        assert!(main_thread_pct(&m(1.0, 0.0, 0.0), &BTreeMap::new(), 3.0).is_none());
424    }
425
426    #[test]
427    fn a_pane_row_never_keeps_a_title_or_animation_names_whatever_the_host_sent() {
428        let answer = json!({ "ok": true, "data": { "browsers": [
429            { "label": "p", "role": "browser-pane", "answer": "answered", "title": "Bank", "kinds": ["CSSAnimation:x"], "origin": "https://a.test" },
430            { "label": "main", "role": "app-window", "answer": "answered", "title": "AgentMux", "kinds": ["CSSAnimation:startup-spin"] },
431        ] } });
432        let rows = parse_page_probe(&answer);
433        assert_eq!((rows[0].title.clone(), rows[0].kinds.len()), (None, 0));
434        assert_eq!(rows[0].origin, "https://a.test");
435        assert_eq!((rows[1].title.as_deref(), rows[1].kinds.len()), (Some("AgentMux"), 1));
436        assert!(parse_page_probe(&json!({ "ok": false })).is_empty());
437    }
438
439    #[test]
440    fn the_instance_is_the_launcher_and_what_runs_under_it_not_a_shell_above_it() {
441        let snap = [
442            proc(1, 0, "explorer", 0),
443            proc(2, 1, "agentmux-launcher", 0),
444            proc(3, 2, "agentmux-cef", 0),
445            proc(4, 3, "agentmux-srv", 0),
446            proc(5, 3, "agentmux-cef", 0),
447            proc(6, 1, "other-tool", 0),
448            proc(7, 99, "agentmux-cef", 0),
449        ];
450        let mut got: Vec<u32> = instance_pids(&snap, 4).into_iter().collect();
451        got.sort_unstable();
452        assert_eq!(got, vec![2, 3, 4, 5]);
453        assert!(instance_pids(&snap, 500).is_empty());
454    }
455
456    #[test]
457    fn the_rest_of_the_instance_is_summed_for_scale() {
458        let before = [proc(2, 1, "agentmux-launcher", 0), proc(3, 2, "agentmux-cef", 0), proc(5, 3, "agentmux-cef", 0)];
459        let after = [proc(2, 1, "agentmux-launcher", 0), proc(3, 2, "agentmux-cef", 3), proc(5, 3, "agentmux-cef", 6)];
460        let instance: HashSet<u32> = [2, 3, 5].into();
461        let o = others(&instance, &[5].into(), &Sample { before: &before, after: &after, secs: 3.0 });
462        assert_eq!((o.processes, o.cpu_pct), (2, 100.0));
463    }
464}