Skip to main content

agentmux_srv_core/backend/
swarm_cloud.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Swarm's cloud tier: the account's other installs, as hosts of tier `cloud`
5//! (`docs/specs/SPEC_SWARM_CLOUD_TIER_2026_11_14.md`). One record is one install, so one host with one channel.
6//!
7//! Display only. A cloud channel has no route, so a broadcast and a stop skip it, and its rows carry what a signed
8//! presence record carries (a state, a line, where it runs) and no provider, seat or account. The answer holds no
9//! address, key, instance id or signature.
10
11use super::agent_state::AgentState;
12use super::lan::discovery::LanInstance;
13use super::runtime_adapter::RuntimeKind;
14use super::swarm_remote::{fnv1a32, RemoteAgent, RemoteChannel, RemoteHost, SwarmOtherInstancesResult};
15use crate::muxbus::cloud_installs::{CloudInstall, CloudView};
16use crate::muxbus::cloud_installs::NewerInstall;
17use crate::muxbus::install_presence::InstallPresence;
18
19/// A record not heard from for this long is shown as stale: three missed beats of the one-minute publisher.
20pub const STALE_AFTER_MS: u64 = 3 * 60_000;
21/// Past this a record is not shown at all.
22pub const HIDE_AFTER_MS: u64 = 10 * 60_000;
23
24/// Adds the cloud hosts to `snapshot`, and says how the read went in its `cloud` field. `view` is `None` where
25/// this build has no sign-in to read with.
26pub fn add_cloud(snapshot: &mut SwarmOtherInstancesResult, view: Option<&CloudView>, own_wan_id: Option<&str>, lan: &[LanInstance], now_ms: u64) {
27    let Some(view) = view else {
28        snapshot.cloud = Some("off");
29        return;
30    };
31    snapshot.cloud = Some(view.state.label());
32    // This machine's other channels, as the registry listed them: the same machines, in more detail.
33    let mut here: Vec<String> = vec![snapshot.channel.to_lowercase()];
34    for host in snapshot.hosts.iter().filter(|h| h.tier == "host") {
35        here.extend(host.channels.iter().map(|c| c.channel.to_lowercase()));
36    }
37    let hosts = cloud_hosts(&view.installs, own_wan_id, &snapshot.hostname, &here, lan, now_ms);
38    snapshot.hosts.extend(hosts);
39    let newer = newer_hosts(&view.newer, own_wan_id, &snapshot.hostname, &here, lan, now_ms);
40    snapshot.hosts.extend(newer);
41}
42
43/// The computers whose presence records are of a format this build cannot read, each as one host with no agents that says what it
44/// needs: shown, not missing. Left out when it is this install, another channel of this machine, a LAN peer (which lists it in
45/// full), or past [`HIDE_AFTER_MS`]. Nothing about it is verified, so nothing but its name, channel and platform is shown.
46pub fn newer_hosts(newer: &[NewerInstall], own_wan_id: Option<&str>, hostname: &str, channels_here: &[String], lan: &[LanInstance], now_ms: u64) -> Vec<RemoteHost> {
47    let same = |a: &str, b: &str| a.trim().eq_ignore_ascii_case(b.trim());
48    let mut hosts: Vec<RemoteHost> = newer
49        .iter()
50        .filter(|n| own_wan_id != Some(n.instance_id.as_str()) && now_ms.saturating_sub(n.seen_at_ms) <= HIDE_AFTER_MS)
51        .filter(|n| !(same(&n.hostname, hostname) && channels_here.iter().any(|ch| same(ch, &n.channel))))
52        .filter(|n| !lan.iter().any(|p| same(&p.hostname, &n.hostname) && same(&p.channel, &n.channel)))
53        .map(|n| newer_host_of(n, now_ms))
54        .collect();
55    hosts.sort_by(|a, b| a.display_name.to_lowercase().cmp(&b.display_name.to_lowercase()));
56    hosts
57}
58
59fn newer_host_of(n: &NewerInstall, now_ms: u64) -> RemoteHost {
60    let needs = if n.app_version.is_empty() { "needs a newer AgentMux".to_string() } else { format!("needs AgentMux {} or newer", n.app_version) };
61    RemoteHost {
62        host_id: format!("cloud:{}#{:08x}", n.hostname.to_lowercase(), fnv1a32(&n.instance_id)),
63        display_name: format!("{} ({needs})", n.hostname),
64        tier: "cloud",
65        channels: vec![RemoteChannel {
66            channel: n.channel.clone(),
67            seen_at_ms: n.seen_at_ms,
68            stale: now_ms.saturating_sub(n.seen_at_ms) > STALE_AFTER_MS,
69            os: n.os.clone(),
70            agents: Vec::new(),
71            route: None,
72            paired_computer: None,
73        }],
74    }
75}
76
77/// The hosts for `installs`, leaving out what is listed elsewhere: this install's own record, another channel of
78/// this machine (`channels_here`), and a LAN peer that is the same machine (see [`on_the_lan`]).
79pub fn cloud_hosts(
80    installs: &[CloudInstall],
81    own_wan_id: Option<&str>,
82    hostname: &str,
83    channels_here: &[String],
84    lan: &[LanInstance],
85    now_ms: u64,
86) -> Vec<RemoteHost> {
87    let same = |a: &str, b: &str| a.trim().eq_ignore_ascii_case(b.trim());
88    let mut hosts: Vec<RemoteHost> = installs
89        .iter()
90        .filter(|c| shown(c, own_wan_id, now_ms))
91        .filter(|c| !(same(&c.record.hostname, hostname) && channels_here.iter().any(|ch| same(ch, &c.record.channel))))
92        .filter(|c| !lan.iter().any(|p| on_the_lan(p, &c.record) || replaced_by(p, c, now_ms)))
93        .map(|c| host_of(c, now_ms))
94        .collect();
95    hosts.sort_by(|a, b| (a.display_name.to_lowercase(), &a.channels[0].channel).cmp(&(b.display_name.to_lowercase(), &b.channels[0].channel)));
96    hosts
97}
98
99/// Whether the LAN peer `peer` is the install `record` describes. The host name and channel must agree (a peer from
100/// before it advertised its channel matches nothing). Then, when the peer advertises its WAN instance id, the ids
101/// must agree too: two machines with one name and one channel are told apart, and the one the LAN lists no longer
102/// hides the other's cloud row. The id only narrows a host-and-channel match and never makes one: it is a public
103/// identifier the peer chose, not proof, so a peer that claims another install's id, with another host name or
104/// channel, hides nothing, and the cloud row stays that install's own.
105fn on_the_lan(peer: &LanInstance, record: &InstallPresence) -> bool {
106    let same = |a: &str, b: &str| a.trim().eq_ignore_ascii_case(b.trim());
107    !peer.channel.is_empty()
108        && same(&peer.hostname, &record.hostname)
109        && same(&peer.channel, &record.channel)
110        && (peer.install_id.is_empty() || peer.install_id == record.instance_id)
111}
112
113/// Whether the LAN peer `peer` is the same machine as the stale record `install`, reinstalled: the host name and channel agree
114/// but the peer's id is another one (a new key), and the record has gone quiet ([`STALE_AFTER_MS`]), as the old install's does
115/// once it is gone. Its row would show for up to [`HIDE_AFTER_MS`] beside the peer's own. A record that is still fresh stays:
116/// it may be a live second machine with the same name. The id never makes a match, as in [`on_the_lan`]: the host name and
117/// channel must agree first.
118fn replaced_by(peer: &LanInstance, install: &CloudInstall, now_ms: u64) -> bool {
119    let same = |a: &str, b: &str| a.trim().eq_ignore_ascii_case(b.trim());
120    let record = &install.record;
121    !peer.channel.is_empty()
122        && !peer.install_id.is_empty()
123        && peer.install_id != record.instance_id
124        && same(&peer.hostname, &record.hostname)
125        && same(&peer.channel, &record.channel)
126        && now_ms.saturating_sub(install.seen_at_ms) > STALE_AFTER_MS
127}
128
129/// A record the tier shows at all: not this install's own, and not past [`HIDE_AFTER_MS`].
130fn shown(install: &CloudInstall, own_wan_id: Option<&str>, now_ms: u64) -> bool {
131    own_wan_id != Some(install.record.instance_id.as_str()) && now_ms.saturating_sub(install.seen_at_ms) <= HIDE_AFTER_MS
132}
133
134/// This install's own WAN instance id (public: a hash of its public key), when it has a WAN identity.
135pub fn own_wan_id() -> Option<String> {
136    let wan = super::storage::wan_identity::global()?;
137    wan.instance_ensure(&super::reactive::registry::local_host_label()).ok().map(|instance| instance.instance_id)
138}
139
140/// The state (`working`, `waiting`, `idle`, `stopped`, `error`) the list gives the agent called `name`, whatever
141/// the case, from the newest record that is shown (see [`shown`]) and has the agent. `None` when no such record
142/// has it, or that record says no state (one from before states).
143pub fn agent_state<'a>(view: &'a CloudView, name: &str, own_wan_id: Option<&str>, now_ms: u64) -> Option<&'a str> {
144    let seen = view.installs.iter().filter(|c| shown(c, own_wan_id, now_ms));
145    let with_agent = seen.filter_map(|c| c.record.agents.iter().find(|a| a.name.eq_ignore_ascii_case(name)).map(|a| (c.seen_at_ms, a)));
146    with_agent.max_by_key(|(seen_at_ms, _)| *seen_at_ms).and_then(|(_, a)| a.state.as_deref())
147}
148
149fn host_of(install: &CloudInstall, now_ms: u64) -> RemoteHost {
150    let record = &install.record;
151    let agents = record
152        .agents
153        .iter()
154        .map(|a| RemoteAgent {
155            name: a.name.clone(),
156            block_id: String::new(),
157            status: a.state.as_deref().and_then(|s| serde_json::from_value::<AgentState>(serde_json::Value::String(s.to_string())).ok()),
158            line: a.line.as_deref().and_then(super::agent_line::clean_line),
159            provider: None,
160            seat: None,
161            account: None,
162            account_label: None,
163            runtime: RuntimeKind::parse(&a.kind),
164        })
165        .collect();
166    RemoteHost {
167        // A short hash of the install's id keeps two installs of one name apart without putting the id in the answer.
168        host_id: format!("cloud:{}#{:08x}", record.hostname.to_lowercase(), fnv1a32(&record.instance_id)),
169        display_name: record.hostname.clone(),
170        tier: "cloud",
171        channels: vec![RemoteChannel {
172            channel: record.channel.clone(),
173            seen_at_ms: install.seen_at_ms,
174            stale: now_ms.saturating_sub(install.seen_at_ms) > STALE_AFTER_MS,
175            os: record.os.clone(),
176            agents,
177            route: None,
178            paired_computer: None,
179        }],
180    }
181}
182
183#[cfg(test)]
184mod tests;