Skip to main content

agentmux_srv/server/remote_ops/
app_ops.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `app.version` and `app.health`: the first operations, both reads
5//! (spec ยง4.3). Nothing here returns a credential, a path or an address.
6
7use serde_json::{json, Value};
8
9use super::{AppState, RemoteCaller, RemoteResult};
10use crate::server::messaging_health::MessagingHealth;
11
12/// What the last release check found, field by field: the status struct also holds the release
13/// asset's URL and the download's folder, installer path and error text, none of which leaves
14/// this machine (a read needs only the first-seen pin, and discovery is unauthenticated).
15fn update_summary() -> Value {
16    let u = crate::backend::update::check::current_status();
17    let mut out = json!({
18        "state": u.state,
19        "current": u.current,
20        "latest": u.latest,
21        "install": u.install,
22        "install_first": u.install_first,
23        "can_download": u.can_download,
24        "published_at": u.published_at,
25        "checked_ms": u.checked_ms,
26    });
27    if let (Some(d), Value::Object(map)) = (u.download, &mut out) {
28        map.insert("download".into(), download_summary(&d));
29    }
30    out
31}
32
33/// A download as it leaves this machine: the release and its state, and, after a restart that was asked for and
34/// not confirmed, when and why (a time and a word, no text).
35pub(crate) fn download_summary(d: &crate::backend::update::check::DownloadStatus) -> Value {
36    let mut out = json!({ "version": d.version, "state": d.state });
37    if let (Some(at), Some(why), Value::Object(map)) = (d.not_confirmed_at, d.not_confirmed.as_deref(), &mut out) {
38        map.insert("not_confirmed_at".into(), json!(at));
39        map.insert("not_confirmed".into(), json!(why));
40    }
41    out
42}
43
44/// MuxBus delivery, without the signed-in account's email or the error text.
45fn muxbus_summary() -> Value {
46    let m = crate::muxbus::delivery_status::status();
47    json!({
48        "state": serde_json::to_value(m.state).unwrap_or(Value::Null),
49        "since_ms": m.since_ms,
50        "last_ok_ms": m.last_ok_ms,
51        "sign_in_unreachable": m.sign_in_unreachable,
52    })
53}
54
55/// Which AgentMux this is: the facts the `AGENTMUX_VERSION`, `AGENTMUX_BUILD` and
56/// `AGENTMUX_INSTANCE_CHANNEL` variables carry, plus what the last release check found.
57fn identity(state: &AppState) -> Value {
58    let build = std::env::var("AGENTMUX_BUILD").ok().filter(|b| !b.is_empty()).unwrap_or_else(|| state.version.clone());
59    json!({
60        "machine": state.hostname,
61        "os": std::env::consts::OS,
62        "version": state.version,
63        "build": build,
64        // What the binary is (`release`, `local`, `dev`), never read off the channel: a release that a
65        // local build upgraded to keeps that build's channel, which only says where its data is.
66        "build_kind": agentmux_common::build_kind::build_kind().label(),
67        "channel": crate::backend::reactive::registry::local_channel_id(),
68        "update": update_summary(),
69    })
70}
71
72pub(super) async fn version(state: &AppState, _caller: &RemoteCaller, _params: Value) -> RemoteResult {
73    Ok(identity(state))
74}
75
76/// Whether a window of this AgentMux is focused: where the person is, for a notice meant for them.
77pub(super) async fn activity(state: &AppState, _caller: &RemoteCaller, _params: Value) -> RemoteResult {
78    Ok(json!({ "window_focused": crate::server::signin_notice::window_focused(state) }))
79}
80
81pub(super) async fn health(state: &AppState, _caller: &RemoteCaller, _params: Value) -> RemoteResult {
82    let messaging = MessagingHealth::probe(state.reactive_handler).await;
83    Ok(health_report(state, &messaging))
84}
85
86/// The upgrade spec's health report, on demand: the identity above, and what a steward checks
87/// after an upgrade (MuxBus, LAN peers, free disk, how many agents are in which state). Also
88/// what `GET /api/v1/app/health` gives this machine's own agents. `status` is `ok` or `degraded` (the messaging path stuck, or srv
89/// panicking in bulk), with the detail under `messaging`.
90pub(crate) fn health_report(state: &AppState, messaging: &MessagingHealth) -> Value {
91    let mut report = identity(state);
92    let disk = agentmux_common::data_paths::DataPaths::from_env()
93        .and_then(|paths| agentmux_common::disk_space::volume_free_total_bytes(&paths.data_dir))
94        .map(|(free, total)| json!({ "free_bytes": free, "total_bytes": total }));
95    let agents = agents_by_state(&state.fleet_feed.snapshot().agent_status);
96    if let Value::Object(map) = &mut report {
97        map.insert("status".into(), json!(messaging.status()));
98        map.insert("messaging".into(), messaging.to_json());
99        map.insert("lan_peers".into(), json!(state.lan_discovery.get_instances().len()));
100        map.insert("muxbus".into(), muxbus_summary());
101        map.insert("disk".into(), disk.unwrap_or(Value::Null));
102        map.insert("agents".into(), agents);
103        map.insert("remote_ops".into(), json!(if super::enabled(state) { "on" } else { "off" }));
104        // Incoming LAN requests refused, still unanswered after a few seconds, or timed out since this srv started.
105        map.insert("lan_refusals".into(), crate::server::lan_watch::counts());
106    }
107    report
108}
109
110/// How many agents are in each lifecycle state (`working`, `idle`, `limited`, `signed_out`...), the
111/// same state `Agents list` shows: the fleet feed's, from `agent_state::decide`.
112fn agents_by_state(status: &std::collections::BTreeMap<String, crate::backend::agent_state::AgentStatus>) -> Value {
113    let mut counts = serde_json::Map::new();
114    for s in status.values() {
115        let count = counts.get(s.state.as_str()).and_then(Value::as_u64).unwrap_or(0);
116        counts.insert(s.state.as_str().to_string(), json!(count + 1));
117    }
118    Value::Object(counts)
119}
120
121/// `GET /api/v1/app/health`: `App` with action `health`, for this machine.
122pub(crate) async fn handle_health(axum::extract::State(state): axum::extract::State<AppState>) -> axum::Json<Value> {
123    let messaging = MessagingHealth::probe(state.reactive_handler).await;
124    axum::Json(health_report(&state, &messaging))
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130    use crate::backend::agent_state::{AgentState, AgentStatus};
131
132    /// The report once counted every agent under `unknown`: an `AgentStatus` serializes as an object
133    /// (`{ state, since_ms }`), not a string, so the label was never read.
134    #[test]
135    fn the_agents_are_counted_by_their_lifecycle_state() {
136        let status = |state| AgentStatus { state, since_ms: 1 };
137        let fleet = std::collections::BTreeMap::from([
138            ("a".to_string(), status(AgentState::Working)),
139            ("b".to_string(), status(AgentState::Idle)),
140            ("c".to_string(), status(AgentState::Idle)),
141            ("d".to_string(), status(AgentState::Limited)),
142            ("e".to_string(), status(AgentState::SignedOut)),
143        ]);
144        assert_eq!(agents_by_state(&fleet), json!({ "working": 1, "idle": 2, "limited": 1, "signed_out": 1 }));
145        assert_eq!(agents_by_state(&Default::default()), json!({}));
146    }
147}