agentmux_srv/server/app_api/
gpu_panel.rs1use super::tower_pane::{not_an_agent_api, sample_local};
12use super::*;
13use crate::backend::gpu::{shape_processes, GpuSampler, MemoryLimits, Named};
14use std::collections::HashMap;
15
16pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
17 let state = state.clone();
18 engine.register_typed(COMMAND_GPU_SAMPLE, move |_req: GpuSampleReq, ctx| {
19 let state = state.clone();
20 async move {
21 not_an_agent_api(&ctx)?;
22 sample(&state).await
23 }
24 });
25}
26
27async fn sample(state: &AppState) -> Result<GpuSampleResult, String> {
28 let (sample, interval, widened) = tokio::task::spawn_blocking(|| GpuSampler::global().sample_for_panel())
30 .await
31 .map_err(|e| format!("gpu.sample: {e}"))?;
32 let names: HashMap<u32, Named> = if sample.reading.processes.is_empty() {
34 HashMap::new()
35 } else {
36 let req = TowerSampleReq { host: Some(true), ..Default::default() };
37 match sample_local(state, &req).await {
38 Ok(snap) => snap
39 .host
40 .map(|h| h.processes)
41 .unwrap_or_default()
42 .into_iter()
43 .map(|p| (p.pid, Named { name: p.name, label: p.detail, kind: p.kind }))
44 .collect(),
45 Err(e) => {
46 tracing::debug!(error = %e, "[gpu] couldn't name the processes");
47 HashMap::new()
48 }
49 }
50 };
51 let limits = MemoryLimits::of(&sample.reading.adapters);
52 let (processes, others) = shape_processes(&sample.reading.processes, limits, |pid| names.get(&pid).cloned());
53 Ok(GpuSampleResult {
54 ts_ms: agentmux_common::time::now_ms_u64(),
55 os: std::env::consts::OS.to_string(),
56 state: sample.state,
57 adapters: sample.reading.adapters,
58 processes,
59 others,
60 per_process: cfg!(any(windows, target_os = "linux")),
61 interval_ms: interval.as_millis() as u32,
62 sample_ms: sample.took.as_millis() as u32,
63 widened,
64 })
65}
66
67#[cfg(test)]
68mod tests {
69 use super::*;
70
71 async fn call(agent_id: &str) -> (serde_json::Value, String) {
72 let state = crate::server::tests::test_state();
73 let (engine, mut rx) = WshRpcEngine::new();
74 register(&engine, &state);
75 if agent_id.is_empty() {
76 engine.set_rpc_context(RpcContext::operator_for_tests());
77 } else {
78 engine.set_rpc_context(RpcContext { agent_id: agent_id.to_string(), ..Default::default() });
79 }
80 engine.handle_message(RpcMessage {
81 command: COMMAND_GPU_SAMPLE.to_string(),
82 reqid: "req-1".to_string(),
83 data: Some(serde_json::json!({})),
84 ..Default::default()
85 });
86 let resp = tokio::time::timeout(std::time::Duration::from_secs(20), rx.recv()).await.unwrap().unwrap();
87 (resp.data.unwrap_or_default(), resp.error)
88 }
89
90 #[tokio::test(flavor = "multi_thread")]
91 async fn the_window_gets_an_answer_whatever_this_machine_has() {
92 let (data, err) = call("").await;
93 assert_eq!(err, "");
94 let r: GpuSampleResult = serde_json::from_value(data).unwrap();
95 assert_eq!(r.os, std::env::consts::OS);
96 assert!(r.interval_ms >= 2000);
97 if !matches!(r.state, GpuSampleState::Ok) {
99 assert!(r.adapters.is_empty() && r.processes.is_empty());
100 }
101 }
102
103 #[tokio::test(flavor = "multi_thread")]
104 async fn a_registered_agent_is_refused() {
105 let (_, err) = call("AgentX").await;
106 assert!(err.contains("FORBIDDEN"), "{err}");
107 }
108}