Skip to main content

agentmux_srv/server/
muxspect_browsers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `GET /api/v1/muxspect/browsers[?sample=SECS][&detail=1]`: which page each renderer of this
5//! instance draws, how busy it is, and what the page is doing
6//! (docs/specs/SPEC_RELEASE_BUILD_BROWSER_PAGE_DIAGNOSTIC_2026_11_13.md ยง3).
7//!
8//! The window host answers what only it knows (`renderer_map` and `page_probe`); this samples the
9//! operating system's process table twice, `sample` seconds apart, and joins the three
10//! (`backend::tower::browsers`, pure and unit-tested). It reads and stores nothing, and a page that
11//! is a person's shows only its origin and three facts: no title, no path, no animation names. A
12//! container agent reaches it like `muxspect layout` and sees nothing about a pane that adds to
13//! what that already lists, except that origin and those facts.
14
15use std::collections::HashSet;
16use std::time::{Duration, Instant};
17
18use agentmux_procstats::ProcInfo;
19use axum::extract::{Query, State};
20use axum::http::StatusCode;
21use axum::response::{IntoResponse, Json};
22use serde::Deserialize;
23use serde_json::{json, Value};
24
25use super::AppState;
26use crate::backend::tower::agentmux::{own_view_pid, parse_renderer_map, RendererEntry};
27use crate::backend::tower::browsers::{browser_rows, instance_pids, others, parse_page_probe, PageProbe, Sample};
28
29/// How long the sample lasts when the caller does not say: the unit the CPU runbook already uses.
30const DEFAULT_SAMPLE_SECS: f64 = 3.0;
31const MIN_SAMPLE_SECS: f64 = 1.0;
32const MAX_SAMPLE_SECS: f64 = 30.0;
33/// The host asks every page (1.5 s each, in parallel) before it answers.
34const HOST_WAIT: Duration = Duration::from_secs(6);
35
36/// The route's path: `muxspect --channel <name> browsers` forwards it, and this read outlasts the
37/// forward layer's usual 5 s (it sleeps the whole sample and asks the host twice).
38pub(super) const PATH: &str = "/api/v1/muxspect/browsers";
39
40/// The most a request for `query` can take: its sample, four host calls (the renderer map and the
41/// page facts, at each end of the sample, each bounded by [`HOST_WAIT`]), and a margin.
42pub(super) fn longest_answer(query: &str) -> Duration {
43    let asked = url::form_urlencoded::parse(query.as_bytes()).find(|(k, _)| k == "sample").and_then(|(_, v)| v.parse::<f64>().ok());
44    Duration::from_secs_f64(sample_secs(asked)) + HOST_WAIT * 4 + Duration::from_secs(5)
45}
46
47#[derive(Debug, Deserialize)]
48pub struct BrowsersQuery {
49    /// Seconds between the two samples (1 to 30; default 3).
50    pub sample: Option<f64>,
51    /// `1` or `true`: also read each page's main-thread time counters.
52    pub detail: Option<String>,
53}
54
55/// The sample length asked for, kept within bounds (a NaN or an absent value is the default).
56fn sample_secs(asked: Option<f64>) -> f64 {
57    asked.filter(|s| s.is_finite()).unwrap_or(DEFAULT_SAMPLE_SECS).clamp(MIN_SAMPLE_SECS, MAX_SAMPLE_SECS)
58}
59
60fn wants_detail(detail: Option<&str>) -> bool {
61    matches!(detail, Some("1" | "true" | "yes"))
62}
63
64/// One call to the window host; `None` when it cannot be asked (an older host has no `page_probe`).
65async fn ask_host(state: &AppState, route: &str, body: Value) -> Option<Value> {
66    let host = state.host_ipc.lock().await.clone()?;
67    match super::host_http::post_to_host(&state.http_client, &host, route, body, Some(HOST_WAIT)).await {
68        Ok(answer) => Some(answer),
69        Err(e) => {
70            tracing::debug!(route, error = %e, "[muxspect] the window host could not answer");
71            None
72        }
73    }
74}
75
76async fn processes() -> Result<Vec<ProcInfo>, String> {
77    tokio::task::spawn_blocking(agentmux_procstats::snapshot)
78        .await
79        .map_err(|e| e.to_string())?
80        .map_err(|e| e.to_string())
81}
82
83/// The host's renderer map and page facts at one moment.
84async fn read_host(state: &AppState, detail: bool) -> (Vec<RendererEntry>, Option<Vec<PageProbe>>) {
85    let entries = ask_host(state, "renderer_map", json!({})).await.map(|a| parse_renderer_map(&a)).unwrap_or_default();
86    let probes = ask_host(state, "page_probe", json!({ "detail": detail })).await.map(|a| parse_page_probe(&a));
87    (entries, probes)
88}
89
90pub async fn handle_muxspect_browsers(State(state): State<AppState>, Query(q): Query<BrowsersQuery>) -> impl IntoResponse {
91    let secs = sample_secs(q.sample);
92    let detail = wants_detail(q.detail.as_deref());
93    if state.host_ipc.lock().await.is_none() {
94        let error = "the window host has not registered with this server, so there are no pages to ask about";
95        return (StatusCode::SERVICE_UNAVAILABLE, Json(json!({ "error": error }))).into_response();
96    }
97    // With `detail` the page's counters are read at both ends of the sample.
98    let before_probes = if detail { read_host(&state, true).await.1.unwrap_or_default() } else { Vec::new() };
99    let (before, started) = match processes().await {
100        Ok(p) => (p, Instant::now()),
101        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": format!("process list: {e}") }))).into_response(),
102    };
103    tokio::time::sleep(Duration::from_secs_f64(secs)).await;
104    let (entries, probes) = read_host(&state, detail).await;
105    let after = match processes().await {
106        Ok(p) => p,
107        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "error": format!("process list: {e}") }))).into_response(),
108    };
109    let elapsed = started.elapsed().as_secs_f64();
110    let sample = Sample { before: &before, after: &after, secs: elapsed };
111    // A renderer reports the pid it sees for itself (the sandbox namespace's on Linux): find the OS's.
112    let instance = instance_pids(&after, std::process::id());
113    let view_to_host: std::collections::HashMap<u32, u32> = instance.iter().map(|p| (own_view_pid(*p), *p)).collect();
114    let host_pid = |reported: u32| view_to_host.get(&reported).copied();
115    let rows = browser_rows(&entries, probes.as_deref().unwrap_or_default(), &before_probes, &sample, &host_pid);
116    let page_pids: HashSet<u32> = rows.iter().filter_map(|r| r.pid).collect();
117    let rest = others(&instance, &page_pids, &sample);
118    Json(json!({
119        "sample_secs": elapsed,
120        "detail": detail,
121        "page_facts": probes.is_some(),
122        "browsers": rows,
123        "others": rest,
124    }))
125    .into_response()
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn the_sample_length_is_kept_within_bounds() {
134        assert_eq!(sample_secs(None), 3.0);
135        assert_eq!(sample_secs(Some(0.0)), 1.0);
136        assert_eq!(sample_secs(Some(600.0)), 30.0);
137        assert_eq!(sample_secs(Some(f64::NAN)), 3.0);
138        assert_eq!(sample_secs(Some(5.0)), 5.0);
139    }
140
141    #[test]
142    fn a_forwarded_request_may_take_its_whole_sample_and_the_host_reads() {
143        // The forward layer's default is 5 s; a 30 s sample must not be cut at that.
144        assert!(longest_answer("sample=30") >= Duration::from_secs(30 + 24));
145        assert!(longest_answer("") > Duration::from_secs(5 + 3));
146        // A bad or huge value is bounded like the handler bounds it.
147        assert_eq!(longest_answer("sample=nope"), longest_answer(""));
148        assert_eq!(longest_answer("sample=9999"), longest_answer("sample=30"));
149    }
150
151    #[test]
152    fn detail_is_asked_for_by_name() {
153        assert!(wants_detail(Some("1")) && wants_detail(Some("true")));
154        assert!(!wants_detail(None) && !wants_detail(Some("0")) && !wants_detail(Some("")));
155    }
156}