Skip to main content

agentmux_srv/server/
http_viewer_sysinfo.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! This computer's CPU and memory for a paired device's Sysinfo, read-only
5//! (agentmux-mobile's PLAN_CHANNEL_AS_ONE_LIST_2026_10_13 ยง3a):
6//!
7//! - `GET /agentmux/viewer/sysinfo`: the latest sample, a `TimeSeriesData`
8//!   (`{ts, values, uptime_secs}`, the metric names the desktop's Sysinfo
9//!   reads: `cpu`, `cpu:N`, `mem:*`, `net:*`, `disk:*`). 204 before the
10//!   first sample.
11//! - `GET /agentmux/viewer/sysinfo/feed?since=<ms>`: the same as SSE, one
12//!   `sample` event per sample, its `id` its `ts`: first the kept history
13//!   after `since` (or after `Last-Event-ID`; all of it with neither), then
14//!   each new sample, with a heartbeat on a quiet stream.
15//!
16//! Both read the samples the sysinfo loop already keeps
17//! (`Broker::read_event_history`), so a phone watching costs no extra
18//! sampling. Built on REPORT_SYSINFO_REWRITE_AND_MODERN_MONITOR_2026_10_13's
19//! data layer as agreed with its author: when that layer's shared scheduler
20//! and `since seq N` read exist, the feed holds a lease while open and
21//! resumes by sequence, and `since=<ms>` keeps working.
22
23use std::convert::Infallible;
24use std::sync::Arc;
25use std::time::Duration;
26
27use axum::body::Bytes;
28use axum::extract::Query;
29use futures_util::Stream;
30use serde::Deserialize;
31
32use super::http_viewer::{ViewerCaller, FEED_HEARTBEAT, HEARTBEAT, RETRY_PREAMBLE};
33use super::*;
34use crate::backend::mps::{Broker, EVENT_SYS_INFO};
35use crate::backend::viewer::FeedLease;
36
37/// How often the feed looks for new samples: the sysinfo loop's own cadence.
38const SAMPLE_POLL: Duration = Duration::from_secs(1);
39/// The most samples one poll reads back. More than a poll can miss even
40/// when the loop runs at its fastest (0.2 s) through a long stall.
41const POLL_READ: usize = 64;
42/// The most samples kept, and so the most a feed sends first.
43const HISTORY_READ: usize = 1024;
44
45/// The samples kept for the whole computer (the sysinfo loop also files them
46/// under its connection's scope; the unscoped ring holds them all).
47const GLOBAL_SCOPE: &str = "";
48
49#[derive(Deserialize, Default)]
50pub(crate) struct SysinfoFeedQuery {
51    since: Option<i64>,
52}
53
54/// One kept sample, as `(ts, the TimeSeriesData as sent)`.
55fn samples(broker: &Broker, max: usize) -> Vec<(i64, serde_json::Value)> {
56    broker
57        .read_event_history(EVENT_SYS_INFO, GLOBAL_SCOPE, max)
58        .into_iter()
59        .filter_map(|e| {
60            let data = e.data?;
61            let ts = data.get("ts")?.as_i64()?;
62            Some((ts, data))
63        })
64        .collect()
65}
66
67pub(super) async fn handle_viewer_sysinfo(State(state): State<AppState>) -> Response {
68    match samples(&state.broker, 1).pop() {
69        Some((_, data)) => Json(data).into_response(),
70        None => StatusCode::NO_CONTENT.into_response(),
71    }
72}
73
74pub(super) async fn handle_viewer_sysinfo_feed(
75    State(state): State<AppState>,
76    Extension(caller): Extension<ViewerCaller>,
77    Query(q): Query<SysinfoFeedQuery>,
78    headers: axum::http::HeaderMap,
79) -> Response {
80    let lease = match state.viewer.open_feed(&caller.device_id, None) {
81        Ok(lease) => lease,
82        Err(why) => return super::http_viewer::feed_refused(why),
83    };
84    // A reconnect resumes after the last sample it got.
85    let since = headers
86        .get("last-event-id")
87        .and_then(|v| v.to_str().ok())
88        .and_then(|v| v.trim().parse::<i64>().ok())
89        .or(q.since);
90    tracing::info!(device = %caller.device_id, resume = since.is_some(), "viewer sysinfo feed: opened");
91    let stream = sysinfo_stream(state.broker.clone(), since, lease, SysinfoTiming::default());
92    (
93        [(header::CONTENT_TYPE, "text/event-stream"), (header::CACHE_CONTROL, "no-cache")],
94        Body::from_stream(stream),
95    )
96        .into_response()
97}
98
99/// A Sysinfo feed's clocks.
100#[derive(Debug, Clone, Copy)]
101pub(crate) struct SysinfoTiming {
102    pub heartbeat: Duration,
103    pub poll: Duration,
104}
105
106impl Default for SysinfoTiming {
107    fn default() -> Self {
108        Self { heartbeat: FEED_HEARTBEAT, poll: SAMPLE_POLL }
109    }
110}
111
112fn sample_event(ts: i64, data: &serde_json::Value) -> Bytes {
113    Bytes::from(format!("event: sample\nid: {ts}\ndata: {data}\n\n"))
114}
115
116/// The kept samples a resume asks for: those after `since`, by their time.
117/// All of them with no `since`, or when every kept sample is older than it
118/// (the computer's clock went back since the device's last one).
119fn history_after(kept: Vec<(i64, serde_json::Value)>, since: Option<i64>) -> Vec<(i64, serde_json::Value)> {
120    let Some(since) = since else { return kept };
121    if kept.iter().all(|(ts, _)| *ts < since) {
122        return kept;
123    }
124    kept.into_iter().filter(|(ts, _)| *ts > since).collect()
125}
126
127/// The samples kept after `cursor` (the last one sent), by their place in
128/// the ring, not their time: a clock that goes back doesn't hide new ones.
129/// The newest `POLL_READ` usually hold it; when they don't (a stalled
130/// stream), the whole ring is read, so nothing kept is skipped. A cursor
131/// no longer kept means everything kept is newer.
132fn samples_after(broker: &Broker, cursor: Option<&serde_json::Value>) -> Vec<(i64, serde_json::Value)> {
133    let recent = samples(broker, POLL_READ);
134    let Some(cursor) = cursor else { return recent };
135    if let Some(at) = recent.iter().rposition(|(_, d)| d == cursor) {
136        return recent[at + 1..].to_vec();
137    }
138    let kept = samples(broker, HISTORY_READ);
139    match kept.iter().rposition(|(_, d)| d == cursor) {
140        Some(at) => kept[at + 1..].to_vec(),
141        None => kept,
142    }
143}
144
145/// The kept samples after `since` (all of them with none), then each new
146/// one; a heartbeat when nothing new came for `timing.heartbeat`. Ends when
147/// the device is revoked or goes away.
148pub(crate) fn sysinfo_stream(
149    broker: Arc<Broker>,
150    since: Option<i64>,
151    lease: FeedLease,
152    timing: SysinfoTiming,
153) -> impl Stream<Item = Result<Bytes, Infallible>> + Send + 'static {
154    async_stream::stream! {
155        let lease = lease;
156        yield Ok(Bytes::from_static(RETRY_PREAMBLE));
157        let kept = samples(&broker, HISTORY_READ);
158        // The newest kept sample is where the live part starts, whether or
159        // not the resume sent it.
160        let mut cursor: Option<serde_json::Value> = kept.last().map(|(_, d)| d.clone());
161        for (ts, data) in history_after(kept, since) {
162            yield Ok(sample_event(ts, &data));
163        }
164        let mut poll = tokio::time::interval_at(tokio::time::Instant::now() + timing.poll, timing.poll);
165        poll.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
166        let mut quiet_since = tokio::time::Instant::now();
167        loop {
168            tokio::select! {
169                biased;
170                _ = lease.token.cancelled() => break,
171                _ = poll.tick() => {
172                    let mut sent = false;
173                    for (ts, data) in samples_after(&broker, cursor.as_ref()) {
174                        sent = true;
175                        yield Ok(sample_event(ts, &data));
176                        cursor = Some(data);
177                    }
178                    if sent {
179                        quiet_since = tokio::time::Instant::now();
180                    } else if quiet_since.elapsed() >= timing.heartbeat {
181                        quiet_since = tokio::time::Instant::now();
182                        yield Ok(Bytes::from_static(HEARTBEAT));
183                    }
184                }
185            }
186        }
187    }
188}
189
190#[cfg(test)]
191#[path = "tests/viewer/viewer_sysinfo_tests.rs"]
192mod tests;