Skip to main content

agentmux_srv/server/app_api/
blockstats.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `blockstats.detail`: a terminal's stats badge and its tooltip
5//! (`backend::blockstats_detail`). The window's, not an agent API: a
6//! connection registered as an agent is refused.
7//!
8//! - A local pane: its processes here, the same Tower task the badge counts
9//!   (`sampler::panes::tower_snapshot`).
10//! - A remote pane (SSH, WSL): its processes on that machine, asked of
11//!   AgentMux's helper there, and the machine's name and address.
12
13use super::*;
14use super::tower_pane::not_an_agent_api;
15use crate::backend::blockcontroller::durable_ssh::META_KEY_SESSION_ID;
16use crate::backend::blockstats_detail;
17use crate::backend::sampler::panes;
18use crate::backend::tower::sampler::{block_label, BlockLabel};
19use crate::backend::remote::address as remote_address;
20use crate::backend::remote::ConnTarget;
21
22/// How long asking a remote pane's helper may take before the badge reads
23/// "not measured" for this round.
24const REMOTE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
25
26pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
27    let mstore = state.mstore.clone();
28    engine.register_typed(COMMAND_BLOCKSTATS_DETAIL, move |req: BlockStatsDetailReq, ctx| {
29        let mstore = mstore.clone();
30        async move {
31            not_an_agent_api(&ctx)?;
32            let meta = mstore.get::<Block>(&req.block_id).ok().flatten().map(|b| b.meta);
33            let meta_str = |key: &str| meta.as_ref().map(|m| obj::meta_get_string(m, key, "")).unwrap_or_default();
34            let conn = meta_str("connection");
35            // Only a terminal has a remote shell to measure; any other pane on
36            // a connection (Files, preview) is not asked of the machine.
37            let remote_terminal = meta_str("view") == "term";
38            if remote_terminal && matches!(ConnTarget::parse(&conn), Ok(ConnTarget::Ssh(_) | ConnTarget::Wsl(_))) {
39                // The machine's name and address, and the pane's processes
40                // there, side by side.
41                let session = meta_str(META_KEY_SESSION_ID);
42                let (connection, remote) = tokio::join!(connection(&conn), remote(&conn, &req.block_id, &session));
43                return Ok(BlockStatsDetail { local: None, connection, remote: Some(remote) });
44            }
45            // The process table and the store: off the async workers.
46            let block_id = req.block_id;
47            let local = tokio::task::spawn_blocking(move || {
48                // Named as the badge names panes; the pane asked about is
49                // grouped even if the store doesn't know it.
50                let labels = |id: &str| {
51                    block_label(&mstore, id).or_else(|| {
52                        (id == block_id).then(|| BlockLabel { label: "Terminal".to_string(), agent: false, provider: None })
53                    })
54                };
55                let snap = panes::tower_snapshot(labels).map_err(|e| format!("blockstats.detail: {e}"))?;
56                let task = snap
57                    .tasks
58                    .iter()
59                    .find(|t| t.id == block_id && t.kind != TowerTaskKind::Agentmux)
60                    .ok_or("no process for this pane")?;
61                Ok::<_, String>(blockstats_detail::from_task(task, &snap.memory_metric))
62            })
63            .await
64            .map_err(|e| format!("blockstats.detail: {e}"))??;
65            Ok(BlockStatsDetail { local: Some(local), connection: None, remote: None })
66        }
67    });
68}
69
70/// A remote pane's machine; `None` for a local pane.
71async fn connection(name: &str) -> Option<BlockStatsConnection> {
72    let kind = match ConnTarget::parse(name).ok()? {
73        ConnTarget::Local => return None,
74        ConnTarget::Ssh(_) => "ssh",
75        ConnTarget::Wsl(_) => "wsl",
76    };
77    let found = remote_address::of(name).await.unwrap_or_default();
78    Some(BlockStatsConnection {
79        name: name.trim().to_string(),
80        kind: kind.to_string(),
81        host: found.host,
82        address: found.address,
83    })
84}
85
86/// A remote pane's processes on its machine. WSL: the helper Tower runs in
87/// the distribution. SSH: the host's helper, only over a connection that
88/// needs no prompt and no install (`files::connect_quiet`): this is asked
89/// every few seconds, never on the user's word.
90async fn remote(conn: &str, block_id: &str, session: &str) -> BlockStatsRemote {
91    let ask = async {
92        let helper = match ConnTarget::parse(conn)? {
93            ConnTarget::Wsl(distro) => crate::backend::tower::remote::wsl_helper(&distro).await?,
94            ConnTarget::Ssh(_) => crate::backend::remote::files::connect_quiet(conn).await.map_err(|e| e.message)?,
95            ConnTarget::Local => return Err("not a remote pane".to_string()),
96        };
97        helper.pane_procs(block_id, session).await.map_err(|e| e.message)
98    };
99    match tokio::time::timeout(REMOTE_TIMEOUT, ask).await {
100        Ok(Ok(frame)) => blockstats_detail::remote(block_id, frame),
101        Ok(Err(why)) => blockstats_detail::remote_unavailable(why),
102        Err(_) => blockstats_detail::remote_unavailable("the machine didn't answer in time".to_string()),
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    async fn call(data: serde_json::Value, agent_id: &str) -> (serde_json::Value, String) {
111        let state = crate::server::tests::test_state();
112        let (engine, mut rx) = WshRpcEngine::new();
113        register(&engine, &state);
114        if agent_id.is_empty() {
115            engine.set_rpc_context(RpcContext::operator_for_tests());
116        } else {
117            engine.set_rpc_context(RpcContext { agent_id: agent_id.to_string(), ..Default::default() });
118        }
119        engine.handle_message(RpcMessage {
120            command: COMMAND_BLOCKSTATS_DETAIL.to_string(),
121            reqid: "req-1".to_string(),
122            data: Some(data),
123            ..Default::default()
124        });
125        let resp = tokio::time::timeout(std::time::Duration::from_secs(20), rx.recv()).await.unwrap().unwrap();
126        (resp.data.unwrap_or_default(), resp.error)
127    }
128
129    /// A process that lives long enough to be measured.
130    fn sleeper() -> std::process::Child {
131        let mut cmd = if cfg!(windows) {
132            let mut c = std::process::Command::new("ping");
133            c.args(["-n", "30", "127.0.0.1"]);
134            c
135        } else {
136            let mut c = std::process::Command::new("sleep");
137            c.arg("30");
138            c
139        };
140        cmd.stdout(std::process::Stdio::null()).spawn().expect("spawn a stand-in shell")
141    }
142
143    #[tokio::test(flavor = "multi_thread")]
144    async fn a_registered_pane_gets_its_tower_task() {
145        // A child stands in for the pane's shell: this test process is
146        // another test's (`sampler::loop_tests`), and one process is in one task.
147        let mut shell = sleeper();
148        let block_id = "blockstats-detail-test-block";
149        blockcontroller::pidregistry::register(block_id, shell.id());
150        // Past Tower's reuse window, so the sample sees the new pane.
151        tokio::time::sleep(std::time::Duration::from_millis(1000)).await;
152        let (data, err) = call(json!({ "block_id": block_id }), "").await;
153        blockcontroller::pidregistry::unregister(block_id);
154        let _ = shell.kill();
155        let _ = shell.wait();
156        assert_eq!(err, "");
157        let d: BlockStatsDetail = serde_json::from_value(data).unwrap();
158        assert!(d.connection.is_none() && d.remote.is_none(), "{d:?}");
159        let d = d.local.expect("a local pane's figures");
160        assert!(d.processes >= 1);
161        assert!(d.started_at_ms.is_some());
162        assert!(d.mem_private.unwrap_or(0) > 0, "{d:?}");
163        assert_eq!(d.mem_commit.is_some(), cfg!(windows), "{d:?}");
164    }
165
166    #[tokio::test(flavor = "multi_thread")]
167    async fn an_unknown_pane_is_an_error() {
168        let (_, err) = call(json!({ "block_id": "no-such-block" }), "").await;
169        assert!(err.contains("no process"), "{err}");
170    }
171
172    #[tokio::test(flavor = "multi_thread")]
173    async fn a_local_pane_has_no_connection_and_a_wsl_pane_names_its_distro() {
174        assert_eq!(connection("").await, None);
175        assert_eq!(connection("local").await, None);
176        let wsl = connection("wsl://NoSuchDistro").await.unwrap();
177        assert_eq!((wsl.kind.as_str(), wsl.host.as_deref()), ("wsl", Some("NoSuchDistro")));
178        assert_eq!(wsl.address, None, "a distro that doesn't exist has no address");
179    }
180
181    /// An SSH pane's machine answers through its helper's connection (here
182    /// the real request handling, in process): this test process carries no
183    /// pane's marker, so the host's figures come back without the pane's.
184    #[tokio::test(flavor = "multi_thread")]
185    async fn a_remote_pane_is_measured_by_its_machines_helper() {
186        let home = tempfile::tempdir().unwrap();
187        crate::backend::remote::files::connect_in_process("me@stats-test-host", home.path().to_path_buf()).await;
188        let r = remote("me@stats-test-host", "no-pane-has-this-id", "").await;
189        assert_eq!(r.found, "none", "{r:?}");
190        let host = r.host.expect("the host's figures");
191        assert!(host.processes > 1 && host.cpu_count >= 1, "{host:?}");
192        assert!(r.figures.is_none());
193    }
194
195    #[tokio::test(flavor = "multi_thread")]
196    async fn a_remote_pane_whose_helper_isnt_there_is_unavailable_not_an_error() {
197        let r = remote("me@no-helper-here.invalid", "b", "").await;
198        assert_eq!(r.found, "unavailable", "{r:?}");
199        assert!(r.reason.is_some());
200    }
201
202    #[tokio::test(flavor = "multi_thread")]
203    async fn a_registered_agent_is_refused() {
204        let (_, err) = call(json!({ "block_id": "x" }), "AgentX").await;
205        assert!(err.contains("FORBIDDEN"), "{err}");
206    }
207}