Skip to main content

agentmux_srv_core/backend/
swarm_remote.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The agents of other AgentMux instances, for the Swarm's sections below this
5//! instance's own tree (`docs/specs/SPEC_SWARM_OTHER_HOSTS_AND_CHANNELS_2026_10_02.md`).
6//!
7//! Phase 2 adds LAN hosts, from the LAN discovery peer list (mDNS and the UDP
8//! route): one host per hostname, one channel per advertising instance, names
9//! from each peer's `agents` list.
10//!
11//! Phase 1: other channels on this machine, read from the host-global shared
12//! registry (`reactive::registry::list_all_shared`), the same source the
13//! `/agentmux/discovery` endpoint's `host.cross_channel` uses. Names only: the
14//! registry carries no status, provider or summary. LAN hosts and cloud installs
15//! are later phases and arrive as more `RemoteHost`s with their own `tier`.
16//!
17//! Phase 4 adds each agent's state (working, waiting, idle, ...) where its
18//! instance reports one: a LAN peer's from the `agent-names` poll the discovery
19//! loop already makes, another channel's from the same route asked over
20//! loopback ([`channel_statuses`]). With it, by the owner's decision of
21//! 2026-10-13, each agent's summary line where its instance shares one
22//! (`backend::agent_line`).
23//!
24//! Nothing here carries a credential to the frontend: the registry's `auth_key`
25//! and `local_url` are dropped.
26
27use serde::Serialize;
28
29use std::collections::{BTreeMap, HashMap, HashSet};
30use std::net::IpAddr;
31
32use crate::backend::agent_state::AgentState;
33use crate::backend::lan::discovery::LanInstance;
34use crate::backend::reactive::registry::AgentEntry;
35use crate::backend::runtime_adapter::RuntimeKind;
36
37/// A registry entry not rewritten for this long is shown as stale. The registry
38/// heartbeat rewrites every live agent's entry every 20 s, so this is three
39/// missed beats.
40pub const STALE_AFTER_MS: u64 = 60_000;
41
42/// Past this an entry is not shown at all. The registry's own startup sweep only
43/// drops entries older than 4 h, and a crashed channel should not look present
44/// for that long.
45pub const HIDE_AFTER_MS: u64 = 10 * 60_000;
46
47#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
48pub struct RemoteAgent {
49    pub name: String,
50    /// The agent's block in its own instance. Not usable from this one; kept so a
51    /// later phase can address it (the cross-channel fleet forwarder does).
52    pub block_id: String,
53    /// What its instance last said it is doing; absent when that instance
54    /// gave no state (a build from before it did, or a terminal pane).
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub status: Option<AgentState>,
57    /// Its summary line as its instance last shared it; absent when that
58    /// instance shared none (an older build, or `swarm:sharesummaries` off).
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub line: Option<String>,
61    /// Its provider id (`claude`, `codex`, ...) as its instance reported it,
62    /// a known one only; absent from an older build. Display only: the Swarm's
63    /// provider icon (SPEC_SWARM_REFINEMENTS_2026_10_17.md §3).
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub provider: Option<String>,
66    /// Its seat as its instance reported it: a LAN peer's `agent_seats`
67    /// (SPEC_AGENT_SEATS_IN_THE_UI_2026_10_23.md §5), bounded by
68    /// `agent_seat::sanitize_peer_summary`. Absent when it has none, or for
69    /// this machine's other channels, which don't report one. Display only.
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub seat: Option<crate::backend::rpc_types::SeatSummary>,
72    /// Its account's stable id as a LAN peer reported it (`agent_accounts`); absent
73    /// when none was, and for this machine's other channels. Display only.
74    #[serde(skip_serializing_if = "Option::is_none")]
75    pub account: Option<String>,
76    /// This machine's own label for that account, when the same account is signed
77    /// in here ([`fill_account_labels`]); absent otherwise. Display only.
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub account_label: Option<String>,
80    /// Where it runs, `host` or `container`, as its instance reported it (`agent_kinds`); absent when
81    /// that instance did not say (an older build). Never guessed.
82    #[serde(skip_serializing_if = "Option::is_none")]
83    pub runtime: Option<RuntimeKind>,
84}
85
86/// What one channel of this machine said about its agents, by lower-cased name.
87#[derive(Debug, Clone, Default, PartialEq, Eq)]
88pub struct ChannelReport {
89    pub status: BTreeMap<String, AgentState>,
90    pub lines: BTreeMap<String, String>,
91    pub providers: BTreeMap<String, String>,
92    pub kinds: BTreeMap<String, RuntimeKind>,
93}
94
95/// Each channel's report, by channel.
96pub type ChannelStatuses = HashMap<String, ChannelReport>;
97
98#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
99pub struct RemoteChannel {
100    pub channel: String,
101    /// Newest `updated_at` among the channel's entries, Unix ms.
102    pub seen_at_ms: u64,
103    /// No entry of this channel rewritten within [`STALE_AFTER_MS`].
104    pub stale: bool,
105    /// The instance's operating system (`windows`, `macos`, `linux`), for the
106    /// platform tag. Empty when unknown: a peer from before it was advertised.
107    /// Self-reported and display only (`host_os`).
108    pub os: String,
109    /// Sorted by name, case-insensitively.
110    pub agents: Vec<RemoteAgent>,
111    /// How to reach a LAN peer's instance, for a Swarm broadcast to one of its
112    /// agents (SPEC_SWARM_REFINEMENTS_2026_10_17.md §4.2). Never serialized:
113    /// the answer to the frontend carries no address or credential.
114    #[serde(skip)]
115    pub route: Option<PeerRoute>,
116    /// The computer this one paired with to watch its agents (`backend::remote_panes`) that this instance is: its id, set
117    /// for a LAN instance at the paired computer's address, with its name and channel. What a click on the instance's
118    /// agent opens a remote pane through: a pairing is one instance's viewer, so the host as a whole can't say, nor can
119    /// a name (two machines may share one).
120    #[serde(skip_serializing_if = "Option::is_none")]
121    pub paired_computer: Option<String>,
122}
123
124/// A LAN peer's address and the broadcast key it advertised.
125#[derive(Clone, PartialEq, Eq)]
126pub struct PeerRoute {
127    pub url: String,
128    pub auth_key: String,
129}
130
131// By hand, so the key never reaches a log line.
132impl std::fmt::Debug for PeerRoute {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        f.debug_struct("PeerRoute").field("url", &self.url).field("auth_key", &"<redacted>").finish()
135    }
136}
137
138#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
139pub struct RemoteHost {
140    /// Stable id for UI state (collapse): `host:<hostname>` for this machine.
141    pub host_id: String,
142    pub display_name: String,
143    /// How it was found: `host` (this machine), later `lan` or `cloud`.
144    pub tier: &'static str,
145    /// Sorted by channel name.
146    pub channels: Vec<RemoteChannel>,
147}
148
149/// A computer this one paired with, as far as the Swarm needs it to tell which LAN host it is.
150#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct PairedComputer {
152    pub id: String,
153    /// Its address (no port), as the pairing link gave it.
154    pub host: String,
155    pub hostname: String,
156    /// The channel of the instance it paired with, as that instance said at pairing; empty for a pairing made before
157    /// it was kept.
158    pub channel: String,
159}
160
161/// The computers this one paired with to watch their agents.
162pub fn paired_computers() -> Vec<PairedComputer> {
163    super::tower::peers::Peers::global()
164        .computers()
165        .into_iter()
166        .map(|p| PairedComputer { id: p.id, host: p.host, hostname: p.hostname, channel: p.channel })
167        .collect()
168}
169
170/// Response of `swarm.other-instances`.
171#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
172pub struct SwarmOtherInstancesResult {
173    /// This machine's name and this instance's channel, for the naming rule
174    /// ("name the channel only when a host has more than one").
175    pub hostname: String,
176    pub channel: String,
177    pub hosts: Vec<RemoteHost>,
178    /// How the read of the account's other installs went: `off`, `ok` or `unavailable` (`swarm_cloud`).
179    /// Absent until the cloud has been asked.
180    #[serde(skip_serializing_if = "Option::is_none")]
181    pub cloud: Option<&'static str>,
182}
183
184/// Group the shared registry's entries into this machine's other channels.
185///
186/// Skips this instance's own channel and URL (a stale self-entry after a crash),
187/// entries past [`HIDE_AFTER_MS`], and entries with no channel (per-channel
188/// registry rows, which never belong in the shared directory). An agent listed
189/// twice in one channel (two files racing) appears once.
190pub fn other_channels(
191    entries: &[AgentEntry],
192    statuses: &ChannelStatuses,
193    own_channel: &str,
194    own_url: &str,
195    now_ms: u64,
196) -> Vec<RemoteChannel> {
197    use std::collections::BTreeMap;
198    let mut by_channel: BTreeMap<String, (u64, BTreeMap<String, RemoteAgent>)> = BTreeMap::new();
199    for e in entries {
200        if e.channel.is_empty()
201            || e.channel == own_channel
202            || (!own_url.is_empty() && e.local_url == own_url)
203        {
204            continue;
205        }
206        if now_ms.saturating_sub(e.updated_at) > HIDE_AFTER_MS {
207            continue;
208        }
209        let slot = by_channel.entry(e.channel.clone()).or_default();
210        slot.0 = slot.0.max(e.updated_at);
211        slot.1
212            .entry(e.agent_id.to_lowercase())
213            .or_insert_with(|| {
214                let report = statuses.get(&e.channel);
215                let key = e.agent_id.to_lowercase();
216                RemoteAgent {
217                    name: e.agent_id.clone(),
218                    block_id: e.block_id.clone(),
219                    status: report.and_then(|r| r.status.get(&key)).copied(),
220                    line: report.and_then(|r| r.lines.get(&key)).cloned(),
221                    provider: report.and_then(|r| r.providers.get(&key)).cloned(),
222                    seat: None,
223                    account: None,
224                    account_label: None,
225                    runtime: report.and_then(|r| r.kinds.get(&key)).copied(),
226                }
227            });
228    }
229    by_channel
230        .into_iter()
231        .map(|(channel, (seen_at_ms, agents))| RemoteChannel {
232            route: None,
233            paired_computer: None,
234            channel,
235            seen_at_ms,
236            stale: now_ms.saturating_sub(seen_at_ms) > STALE_AFTER_MS,
237            // Every channel on this machine runs on its operating system.
238            os: crate::backend::host_os::local_os(),
239            agents: agents.into_values().collect(),
240        })
241        .collect()
242}
243
244pub(crate) fn fnv1a32(text: &str) -> u32 {
245    text.bytes().fold(0x811c_9dc5u32, |h, b| {
246        (h ^ u32::from(b)).wrapping_mul(0x0100_0193)
247    })
248}
249
250/// A host's instances as channels, with a channel name that appears more than
251/// once suffixed by its port ("stable :29702"), so the sections stay apart.
252fn label_repeated_channels(by_instance: BTreeMap<String, RemoteChannel>) -> Vec<RemoteChannel> {
253    let mut count: BTreeMap<String, usize> = BTreeMap::new();
254    for c in by_instance.values() {
255        *count.entry(c.channel.clone()).or_default() += 1;
256    }
257    by_instance
258        .into_iter()
259        .map(|(key, mut c)| {
260            if count[&c.channel] > 1 {
261                if let Some((_, port)) = key.rsplit_once('@') {
262                    c.channel = format!("{} :{port}", c.channel);
263                }
264            }
265            c
266        })
267        .collect()
268}
269
270/// One agent of LAN peer `p`, with what the peer reported about it, by lower-cased name.
271fn lan_agent(p: &LanInstance, name: &str) -> RemoteAgent {
272    let key = name.to_lowercase();
273    RemoteAgent {
274        name: name.to_string(),
275        block_id: String::new(),
276        status: p.agent_status.get(&key).copied(),
277        line: p.agent_lines.get(&key).cloned(),
278        provider: p.agent_providers.get(&key).cloned(),
279        seat: p.agent_seats.get(&key).cloned(),
280        account: p.agent_accounts.get(&key).cloned(),
281        account_label: None,
282        runtime: p.agent_kinds.get(&key).copied(),
283    }
284}
285
286/// LAN hosts from the discovery peer list. A peer at one of this machine's own
287/// addresses is another channel on this host, which the registry already lists
288/// (with more detail), so it is left out here. A peer that did not advertise its
289/// channel (an older build) is labelled by its port, so two of them on one host
290/// stay apart.
291pub fn lan_hosts(
292    peers: &[LanInstance],
293    own_addrs: &HashSet<IpAddr>,
294    paired: &[PairedComputer],
295    now_ms: u64,
296) -> Vec<RemoteHost> {
297    let mut hosts: BTreeMap<String, (String, BTreeMap<String, RemoteChannel>)> = BTreeMap::new();
298    for p in peers {
299        if p.address
300            .parse::<IpAddr>()
301            .is_ok_and(|a| own_addrs.contains(&a))
302        {
303            continue;
304        }
305        // The address is the grouping key only, never a label: the answer
306        // carries no addresses (Codex P2 on #4241).
307        let display = if p.hostname.trim().is_empty() {
308            "unnamed host".to_string()
309        } else {
310            p.hostname.trim().to_string()
311        };
312        let channel = if p.channel.is_empty() {
313            format!(":{}", p.port)
314        } else {
315            p.channel.clone()
316        };
317        // Heard from by mDNS or answered a poll, whichever is later.
318        let seen_at_ms = p.last_seen.max(p.last_polled_ok).saturating_mul(1000);
319        let mut agents: Vec<RemoteAgent> = p.agents.iter().map(|name| lan_agent(p, name)).collect();
320        agents.sort_by_key(|a| a.name.to_lowercase());
321        agents.dedup_by(|a, b| a.name.eq_ignore_ascii_case(&b.name));
322        // A machine is its hostname AND its address: two machines that share a
323        // name (cloned VMs both called `ubuntu`) must not merge, or one would hide
324        // the other's agents (Codex P2 on #4241). Two channels on one machine
325        // share the address, so they still group.
326        let host = hosts
327            .entry(format!("{}@{}", display.to_lowercase(), p.address))
328            .or_insert_with(|| (display.clone(), BTreeMap::new()));
329        // One entry per instance, which on a machine is its port: two records
330        // for the same instance (mDNS and UDP before they merge) keep the fresher
331        // one, while two instances on one channel (an installed and a portable
332        // build, say) both stay (Codex P2 on #4241).
333        let instance_key = format!("{channel}@{}", p.port);
334        let keep = host
335            .1
336            .get(&instance_key)
337            .is_none_or(|c| c.seen_at_ms < seen_at_ms);
338        if keep {
339            host.1.insert(
340                instance_key,
341                RemoteChannel {
342                    route: Some(PeerRoute { url: super::lan::discovery::peer_base_url(&p.address, p.port), auth_key: p.auth_key.clone() }),
343                    paired_computer: None,
344                    channel,
345                    seen_at_ms,
346                    stale: now_ms.saturating_sub(seen_at_ms) > STALE_AFTER_MS,
347                    os: p.os.clone(),
348                    agents,
349                },
350            );
351        }
352    }
353    // A name shared by several machines gets a number per machine, in key
354    // (address) order, so the sections can be told apart without showing an
355    // address; a unique name stays bare.
356    let mut name_count: BTreeMap<String, usize> = BTreeMap::new();
357    for (display, _) in hosts.values() {
358        *name_count.entry(display.to_lowercase()).or_default() += 1;
359    }
360    let mut name_seen: BTreeMap<String, usize> = BTreeMap::new();
361    hosts
362        .into_iter()
363        .map(|(key, (display, channels))| {
364            // Stable for the UI's collapse state, without putting the address
365            // in the answer: a short hash of name and address.
366            let host_id = format!("lan:{}#{:08x}", display.to_lowercase(), fnv1a32(&key));
367            let address = key.rsplit_once('@').map_or("", |(_, a)| a);
368            let mut channels = channels;
369            mark_paired(&mut channels, address, &display, paired);
370            let lower = display.to_lowercase();
371            let display_name = if name_count[&lower] > 1 {
372                let n = name_seen.entry(lower).or_default();
373                *n += 1;
374                format!("{display} ({n})")
375            } else {
376                display
377            };
378            RemoteHost {
379                host_id,
380                display_name,
381                tier: "lan",
382                channels: label_repeated_channels(channels),
383            }
384        })
385        .collect()
386}
387
388/// Marks the instances of one LAN host (at `address`, named `display`) that are a computer this one paired with. A
389/// pairing is one instance's viewer: the paired computer at that address with that name and channel is that channel's
390/// instance, not the others on the host. A pairing from before its channel was kept is the host's only instance, when
391/// it has one.
392fn mark_paired(channels: &mut BTreeMap<String, RemoteChannel>, address: &str, display: &str, paired: &[PairedComputer]) {
393    let several = channels.len() > 1;
394    for instance in channels.values_mut() {
395        instance.paired_computer = paired
396            .iter()
397            .find(|c| {
398                c.host == address
399                    && c.hostname.trim().eq_ignore_ascii_case(display.trim())
400                    && if c.channel.is_empty() { !several } else { c.channel == instance.channel }
401            })
402            .map(|c| c.id.clone());
403    }
404}
405
406/// How long another channel on this machine gets to say what its agents are
407/// doing. It is loopback, so one that takes longer is hung, and the Swarm's poll
408/// shouldn't wait on it: its rows show names only until it answers.
409const CHANNEL_STATUS_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(1500);
410
411/// One instance to ask for its agents' states: `(channel, local_url, auth_key)`.
412#[derive(Debug, Clone, PartialEq, Eq)]
413pub struct ChannelStatusTarget {
414    pub channel: String,
415    pub local_url: String,
416    pub auth_key: String,
417}
418
419fn is_loopback_url(url: &str) -> bool {
420    ["http://127.0.0.1:", "http://localhost:", "http://[::1]:"]
421        .iter()
422        .any(|prefix| url.starts_with(prefix))
423}
424
425/// The instances whose agents [`other_channels`] lists and that are worth
426/// asking: one per `local_url`, loopback only (as the cross-channel fleet
427/// forwarder requires), never this instance, and not a stale one, whose rows
428/// are dimmed and show no state.
429///
430/// Each instance is asked with its freshest entry's key: an instance that
431/// restarted on the same URL has a new per-launch key, while its older entries
432/// keep the old one until they are rewritten or age out (#4703).
433pub fn channel_status_targets(
434    entries: &[AgentEntry],
435    own_channel: &str,
436    own_url: &str,
437    now_ms: u64,
438) -> Vec<ChannelStatusTarget> {
439    let mut by_url: BTreeMap<&str, &AgentEntry> = BTreeMap::new();
440    for e in entries {
441        if e.channel.is_empty()
442            || e.channel == own_channel
443            || e.local_url == own_url
444            || !is_loopback_url(&e.local_url)
445            || now_ms.saturating_sub(e.updated_at) > STALE_AFTER_MS
446        {
447            continue;
448        }
449        let slot = by_url.entry(&e.local_url).or_insert(e);
450        if e.updated_at > slot.updated_at {
451            *slot = e;
452        }
453    }
454    by_url
455        .into_values()
456        .map(|e| ChannelStatusTarget {
457            channel: e.channel.clone(),
458            local_url: e.local_url.clone(),
459            auth_key: e.auth_key.clone(),
460        })
461        .collect()
462}
463
464/// Asks each target's `agent-names` route, concurrently, for its agents'
465/// states and lines. A target that fails, times out or answers badly
466/// contributes nothing.
467pub async fn channel_statuses(
468    http: &reqwest::Client,
469    targets: &[ChannelStatusTarget],
470) -> ChannelStatuses {
471    let answers = futures_util::future::join_all(targets.iter().map(|t| async move {
472        let resp = http
473            .get(format!("{}/agentmux/reactive/agent-names", t.local_url))
474            .header(agentmux_common::AUTH_KEY_HEADER, &t.auth_key)
475            .timeout(CHANNEL_STATUS_TIMEOUT)
476            .send()
477            .await
478            .ok()
479            .filter(|r| r.status().is_success())?;
480        let body = crate::backend::lan::discovery::LanDiscovery::read_body_capped(
481            resp,
482            crate::backend::lan::discovery::LAN_AGENT_NAMES_MAX_RESPONSE_BYTES,
483        )
484        .await
485        .ok()?;
486        let value: serde_json::Value = serde_json::from_slice(&body).ok()?;
487        Some((
488            t.channel.clone(),
489            crate::backend::lan::discovery::parse_agent_names_body(&value),
490        ))
491    }))
492    .await;
493    let mut out = ChannelStatuses::new();
494    for (channel, peer) in answers.into_iter().flatten() {
495        let report = out.entry(channel).or_default();
496        report.status.extend(peer.status);
497        report.lines.extend(peer.lines);
498        report.providers.extend(peer.providers);
499        report.kinds.extend(peer.kinds);
500    }
501    out
502}
503
504/// The full answer: this machine's other channels as one host (absent when there
505/// are none), then the LAN hosts.
506pub fn snapshot(
507    entries: &[AgentEntry],
508    statuses: &ChannelStatuses,
509    lan: &[LanInstance],
510    own_addrs: &HashSet<IpAddr>,
511    paired: &[PairedComputer],
512    hostname: &str,
513    own_channel: &str,
514    own_url: &str,
515    now_ms: u64,
516) -> SwarmOtherInstancesResult {
517    let channels = other_channels(entries, statuses, own_channel, own_url, now_ms);
518    let mut hosts = Vec::new();
519    if !channels.is_empty() {
520        hosts.push(RemoteHost {
521            host_id: format!("host:{hostname}"),
522            display_name: hostname.to_string(),
523            tier: "host",
524            channels,
525        });
526    }
527    hosts.extend(lan_hosts(lan, own_addrs, paired, now_ms));
528    SwarmOtherInstancesResult {
529        hostname: hostname.to_string(),
530        channel: own_channel.to_string(),
531        hosts,
532        cloud: None,
533    }
534}
535
536/// Each agent's provider id as this machine's agent definitions record it, by
537/// the `uid` its registry entry carries; a known id only.
538pub type DefinedProviders = HashMap<String, String>;
539
540/// The definitions' providers for `entries`, read from the host-global
541/// definition store. Blocking: it reads one file per agent.
542pub fn defined_providers(entries: &[AgentEntry]) -> DefinedProviders {
543    let Some(store) = crate::registry::resolve_shared_definitions_dir()
544        .and_then(|dir| crate::registry::DefinitionStore::open(dir).ok())
545    else {
546        return DefinedProviders::new();
547    };
548    defined_providers_from(entries, |uid| store.get(uid).ok().flatten().map(|r| r.data.provider))
549}
550
551fn defined_providers_from(entries: &[AgentEntry], lookup: impl Fn(&str) -> Option<String>) -> DefinedProviders {
552    let mut out = DefinedProviders::new();
553    for e in entries {
554        if e.uid.is_empty() || out.contains_key(&e.uid) {
555            continue;
556        }
557        let Some(raw) = lookup(&e.uid) else { continue };
558        let id = crate::backend::providers::resolve_provider_alias(raw.trim());
559        if !id.is_empty() {
560            out.insert(e.uid.clone(), id.to_string());
561        }
562    }
563    out
564}
565
566/// Give this machine's other channels' agents the provider their definition
567/// records, where their instance reported none: an instance from before it
568/// reported providers (0.59.30 and older) still shows its agents' icons
569/// (REPORT_SWARM_REMOTE_PROVIDER_ICON_RCA_2026_10_18.md §6.1). A provider the
570/// instance reported wins: it describes the live pane. LAN hosts are left as
571/// they are: their definitions aren't on this machine.
572pub fn fill_defined_providers(result: &mut SwarmOtherInstancesResult, entries: &[AgentEntry], defined: &DefinedProviders) {
573    let uid_of: HashMap<(&str, String), &str> = entries
574        .iter()
575        .filter(|e| !e.uid.is_empty())
576        .map(|e| ((e.channel.as_str(), e.agent_id.to_lowercase()), e.uid.as_str()))
577        .collect();
578    for host in result.hosts.iter_mut().filter(|h| h.tier == "host") {
579        for ch in &mut host.channels {
580            let channel = ch.channel.clone();
581            for a in ch.agents.iter_mut().filter(|a| a.provider.is_none()) {
582                a.provider = uid_of
583                    .get(&(channel.as_str(), a.name.to_lowercase()))
584                    .and_then(|uid| defined.get(*uid))
585                    .cloned();
586            }
587        }
588    }
589}
590
591/// This machine's label for each account signed in on it, by the id every
592/// machine agrees on (`identity::stable_account`).
593pub type AccountLabels = HashMap<String, String>;
594
595/// Name each remote agent's account when the same account is signed in on this
596/// machine: two machines' sign-ins of one provider account share the stable id,
597/// and the label is this machine's own. An account that is not signed in here
598/// keeps its id and gets no label.
599pub fn fill_account_labels(result: &mut SwarmOtherInstancesResult, labels: &AccountLabels) {
600    for agent in result.hosts.iter_mut().flat_map(|h| &mut h.channels).flat_map(|c| &mut c.agents) {
601        agent.account_label = agent.account.as_ref().and_then(|id| labels.get(id)).cloned();
602    }
603}
604
605#[cfg(test)]
606mod tests {
607    use super::*;
608
609    fn remote_agent(name: &str, account: Option<&str>) -> RemoteAgent {
610        RemoteAgent {
611            name: name.into(),
612            block_id: String::new(),
613            status: None,
614            line: None,
615            provider: None,
616            seat: None,
617            account: account.map(str::to_string),
618            account_label: None,
619            runtime: None,
620        }
621    }
622
623    #[test]
624    fn an_account_signed_in_here_too_gets_this_machines_label() {
625        let agents = vec![
626            remote_agent("Opaz", Some("claude:0123456789abcdef")),
627            remote_agent("Parlo", Some("claude:fedcba9876543210")),
628            remote_agent("Maricon", None),
629        ];
630        let channel = RemoteChannel { channel: "stable".into(), seen_at_ms: NOW, stale: false, os: String::new(), agents, route: None, paired_computer: None };
631        let mut snap = SwarmOtherInstancesResult {
632            hostname: "narko".into(),
633            channel: "stable".into(),
634            hosts: vec![RemoteHost { host_id: "lan:charlie".into(), display_name: "charlie".into(), tier: "lan", channels: vec![channel] }],
635            cloud: None,
636        };
637        let labels: AccountLabels = [("claude:0123456789abcdef".to_string(), "Work".to_string())].into();
638        fill_account_labels(&mut snap, &labels);
639        let got: Vec<Option<&str>> = snap.hosts[0].channels[0].agents.iter().map(|a| a.account_label.as_deref()).collect();
640        assert_eq!(got, [Some("Work"), None, None], "one signed in here, one that is not, one with no account");
641    }
642
643    const NOW: u64 = 1_000_000_000;
644
645    fn entry(name: &str, channel: &str, age_ms: u64) -> AgentEntry {
646        AgentEntry {
647            agent_id: name.to_string(),
648            local_url: format!("http://127.0.0.1:{}", 29700 + channel.len()),
649            block_id: format!("blk-{name}"),
650            pid: 1,
651            updated_at: NOW - age_ms,
652            auth_key: "secret".to_string(),
653            channel: channel.to_string(),
654            registration_nonce: 0,
655            jekt_public_key: String::new(),
656            uid: String::new(),
657            uid_public_key: String::new(),
658            jekt_features: Vec::new(),
659        }
660    }
661
662    #[test]
663    fn groups_other_channels_and_leaves_this_one_out() {
664        let entries = [
665            entry("Korp", "dev-fix-lan", 5_000),
666            entry("Loap", "dev-fix-lan", 1_000),
667            entry("AgentX", "stable", 0),
668        ];
669        let chans = other_channels(&entries, &ChannelStatuses::new(), "stable", "", NOW);
670        assert_eq!(chans.len(), 1);
671        assert_eq!(chans[0].channel, "dev-fix-lan");
672        assert_eq!(
673            chans[0]
674                .agents
675                .iter()
676                .map(|a| a.name.as_str())
677                .collect::<Vec<_>>(),
678            ["Korp", "Loap"]
679        );
680        assert_eq!(chans[0].seen_at_ms, NOW - 1_000, "newest entry");
681        assert!(!chans[0].stale);
682    }
683
684    #[test]
685    fn a_stale_self_entry_by_url_is_left_out() {
686        let mut me = entry("AgentX", "old-name", 0);
687        me.local_url = "http://127.0.0.1:29706".to_string();
688        assert!(other_channels(
689            &[me],
690            &ChannelStatuses::new(),
691            "stable",
692            "http://127.0.0.1:29706",
693            NOW
694        )
695        .is_empty());
696    }
697
698    #[test]
699    fn freshness_marks_stale_then_hides() {
700        let stale = other_channels(
701            &[entry("Korp", "dev", STALE_AFTER_MS + 1)],
702            &ChannelStatuses::new(),
703            "stable",
704            "",
705            NOW,
706        );
707        assert!(stale[0].stale);
708        assert!(other_channels(
709            &[entry("Korp", "dev", HIDE_AFTER_MS + 1)],
710            &ChannelStatuses::new(),
711            "stable",
712            "",
713            NOW
714        )
715        .is_empty());
716    }
717
718    #[test]
719    fn an_agent_listed_twice_in_a_channel_appears_once() {
720        let chans = other_channels(
721            &[entry("Korp", "dev", 0), entry("korp", "dev", 10)],
722            &ChannelStatuses::new(),
723            "stable",
724            "",
725            NOW,
726        );
727        assert_eq!(chans[0].agents.len(), 1);
728    }
729
730    #[test]
731    fn entries_without_a_channel_are_not_another_channel() {
732        assert!(other_channels(
733            &[entry("Korp", "", 0)],
734            &ChannelStatuses::new(),
735            "stable",
736            "",
737            NOW
738        )
739        .is_empty());
740    }
741
742    #[test]
743    fn the_snapshot_names_this_machine_and_carries_no_credentials() {
744        let snap = snapshot(
745            &[entry("Korp", "dev", 0)],
746            &ChannelStatuses::new(),
747            &[],
748            &HashSet::new(),
749            &[],
750            "narko",
751            "stable",
752            "",
753            NOW,
754        );
755        assert_eq!(
756            (snap.hostname.as_str(), snap.channel.as_str()),
757            ("narko", "stable")
758        );
759        assert_eq!(snap.hosts.len(), 1);
760        assert_eq!(
761            (snap.hosts[0].display_name.as_str(), snap.hosts[0].tier),
762            ("narko", "host")
763        );
764        let json = serde_json::to_string(&snap).unwrap();
765        assert!(
766            !json.contains("secret") && !json.contains("local_url") && !json.contains("127.0.0.1"),
767            "{json}"
768        );
769        // No other channel: no host section at all.
770        assert!(snapshot(
771            &[],
772            &ChannelStatuses::new(),
773            &[],
774            &HashSet::new(),
775            &[],
776            "narko",
777            "stable",
778            "",
779            NOW
780        )
781        .hosts
782        .is_empty());
783    }
784
785    fn peer(
786        host: &str,
787        channel: &str,
788        addr: &str,
789        port: u16,
790        agents: &[&str],
791        age_secs: u64,
792    ) -> LanInstance {
793        LanInstance {
794            instance_id: format!("{host}-{port}"),
795            hostname: host.to_string(),
796            version: "0.59.5".to_string(),
797            channel: channel.to_string(),
798            os: String::new(),
799            install: String::new(),
800            build: String::new(),
801            address: addr.to_string(),
802            port,
803            auth_key: "lan-secret".to_string(),
804            agents: agents.iter().map(|a| a.to_string()).collect(),
805            agent_status: Default::default(),
806            agent_lines: Default::default(),
807            agent_providers: Default::default(),
808            agent_kinds: Default::default(),
809            agent_accounts: Default::default(),
810            agent_resets: Default::default(),
811            agent_seats: Default::default(),
812            first_seen: 0,
813            last_seen: NOW / 1000 - age_secs,
814            last_polled_ok: 0,
815            install_id: String::new(),
816            other_ttl_secs: 4500,
817        }
818    }
819
820    #[test]
821    fn lan_peers_group_into_hosts_with_a_channel_each() {
822        let peers = [
823            peer("Area54", "stable", "10.0.0.26", 29700, &["Manoz"], 5),
824            peer(
825                "starpower",
826                "stable",
827                "10.0.0.195",
828                29700,
829                &["Opaz", "korp"],
830                5,
831            ),
832            peer("starpower", "dev", "10.0.0.195", 29702, &["Loap"], 5),
833        ];
834        let hosts = lan_hosts(&peers, &HashSet::new(), &[], NOW);
835        let shape: Vec<(&str, &str, usize)> = hosts
836            .iter()
837            .map(|h| (h.display_name.as_str(), h.tier, h.channels.len()))
838            .collect();
839        assert_eq!(shape, [("Area54", "lan", 1), ("starpower", "lan", 2)]);
840        let chans: Vec<&str> = hosts[1]
841            .channels
842            .iter()
843            .map(|c| c.channel.as_str())
844            .collect();
845        assert_eq!(chans, ["dev", "stable"]);
846        let names: Vec<&str> = hosts[1].channels[1]
847            .agents
848            .iter()
849            .map(|a| a.name.as_str())
850            .collect();
851        assert_eq!(names, ["korp", "Opaz"]);
852    }
853
854    /// Codex P2 on #4241: cloned VMs that share a hostname are two machines.
855    #[test]
856    fn two_machines_with_the_same_hostname_stay_apart() {
857        let peers = [
858            peer("ubuntu", "stable", "10.0.0.40", 29700, &["A"], 5),
859            peer("ubuntu", "stable", "10.0.0.41", 29700, &["B"], 5),
860        ];
861        let hosts = lan_hosts(&peers, &HashSet::new(), &[], NOW);
862        assert_eq!(hosts.len(), 2, "neither hides the other");
863        let names: Vec<&str> = hosts.iter().map(|h| h.display_name.as_str()).collect();
864        assert_eq!(names, ["ubuntu (1)", "ubuntu (2)"]);
865        // And still no address anywhere in the answer (Codex P2 on #4241).
866        let json = serde_json::to_string(&hosts).unwrap();
867        assert!(!json.contains("10.0.0.4"), "{json}");
868        assert_ne!(hosts[0].host_id, hosts[1].host_id);
869        let agents: Vec<&str> = hosts
870            .iter()
871            .map(|h| h.channels[0].agents[0].name.as_str())
872            .collect();
873        assert_eq!(agents, ["A", "B"]);
874    }
875
876    /// A pairing is one instance's viewer: the paired computer is found by address, name and channel, so two machines
877    /// of one name are told apart, a host's other channels are not the paired instance, and the answer carries no address.
878    #[test]
879    fn a_lan_instance_is_the_paired_computer_at_its_address_with_its_name_and_channel() {
880        let peers = [
881            peer("ubuntu", "stable", "10.0.0.40", 29700, &["A"], 5),
882            peer("ubuntu", "stable", "10.0.0.41", 29700, &["B"], 5),
883            peer("ubuntu", "dev", "10.0.0.41", 29702, &["B2"], 5),
884            peer("charlie", "stable", "10.0.0.50", 29700, &["C"], 5),
885        ];
886        let paired = [
887            PairedComputer { id: "c-41".into(), host: "10.0.0.41".into(), hostname: "Ubuntu".into(), channel: "dev".into() },
888            // Same address as charlie but another name: not that host.
889            PairedComputer { id: "c-wrong".into(), host: "10.0.0.50".into(), hostname: "other".into(), channel: String::new() },
890        ];
891        let hosts = lan_hosts(&peers, &HashSet::new(), &paired, NOW);
892        let found: Vec<(&str, &str, Option<&str>)> = hosts
893            .iter()
894            .flat_map(|h| h.channels.iter().map(move |c| (h.display_name.as_str(), c.channel.as_str(), c.paired_computer.as_deref())))
895            .collect();
896        assert_eq!(
897            found,
898            [("charlie", "stable", None), ("ubuntu (1)", "stable", None), ("ubuntu (2)", "dev", Some("c-41")), ("ubuntu (2)", "stable", None)]
899        );
900        let json = serde_json::to_string(&hosts).unwrap();
901        assert!(!json.contains("10.0.0.4") && !json.contains("10.0.0.5"), "{json}");
902    }
903
904    /// A pairing from before its channel was kept is the host's one instance, when it has only one.
905    #[test]
906    fn a_pairing_without_a_channel_is_the_only_instance_of_its_host_and_no_other() {
907        let paired = [PairedComputer { id: "old".into(), host: "10.0.0.60".into(), hostname: "solo".into(), channel: String::new() }];
908        let one = lan_hosts(&[peer("solo", "stable", "10.0.0.60", 29700, &["A"], 5)], &HashSet::new(), &paired, NOW);
909        assert_eq!(one[0].channels[0].paired_computer.as_deref(), Some("old"));
910        let two = lan_hosts(
911            &[peer("solo", "stable", "10.0.0.60", 29700, &["A"], 5), peer("solo", "dev", "10.0.0.60", 29702, &["B"], 5)],
912            &HashSet::new(),
913            &paired,
914            NOW,
915        );
916        assert!(two[0].channels.iter().all(|c| c.paired_computer.is_none()));
917    }
918
919    #[test]
920    fn a_lan_peer_at_one_of_our_own_addresses_is_left_to_the_registry() {
921        let own: HashSet<IpAddr> = ["10.0.0.230".parse().unwrap()].into_iter().collect();
922        let peers = [peer("narko", "dev", "10.0.0.230", 29702, &["Loap"], 5)];
923        assert!(lan_hosts(&peers, &own, &[], NOW).is_empty());
924    }
925
926    #[test]
927    fn a_peer_without_a_channel_is_labelled_by_its_port() {
928        let peers = [
929            peer("old", "", "10.0.0.9", 29700, &["A"], 5),
930            peer("old", "", "10.0.0.9", 29701, &["B"], 5),
931        ];
932        let hosts = lan_hosts(&peers, &HashSet::new(), &[], NOW);
933        let chans: Vec<&str> = hosts[0]
934            .channels
935            .iter()
936            .map(|c| c.channel.as_str())
937            .collect();
938        assert_eq!(chans, [":29700", ":29701"]);
939    }
940
941    #[test]
942    fn a_quiet_lan_peer_is_stale_and_no_lan_key_or_address_leaves() {
943        let quiet = [peer(
944            "Area54",
945            "stable",
946            "10.0.0.26",
947            29700,
948            &["Manoz"],
949            90,
950        )];
951        assert!(lan_hosts(&quiet, &HashSet::new(), &[], NOW)[0].channels[0].stale);
952        let fresh = [peer(
953            "Area54",
954            "stable",
955            "10.0.0.26",
956            29700,
957            &["Manoz"],
958            5,
959        )];
960        let snap = snapshot(
961            &[],
962            &ChannelStatuses::new(),
963            &fresh,
964            &HashSet::new(),
965            &[],
966            "narko",
967            "stable",
968            "",
969            NOW,
970        );
971        let json = serde_json::to_string(&snap).unwrap();
972        assert!(
973            !json.contains("lan-secret") && !json.contains("10.0.0.26"),
974            "{json}"
975        );
976    }
977
978    /// Codex P1 on #4241: an mDNS-only peer is re-resolved tens of minutes apart,
979    /// so a peer that answers the agent-name poll is live, whatever `last_seen` says.
980    #[test]
981    fn a_peer_that_answers_polls_is_not_stale() {
982        let mut p = peer("Area54", "stable", "10.0.0.26", 29700, &["Manoz"], 1800);
983        assert!(lan_hosts(std::slice::from_ref(&p), &HashSet::new(), &[], NOW)[0].channels[0].stale);
984        p.last_polled_ok = NOW / 1000 - 10;
985        assert!(!lan_hosts(&[p], &HashSet::new(), &[], NOW)[0].channels[0].stale);
986    }
987
988    #[test]
989    fn a_host_with_no_name_is_not_labelled_by_its_address() {
990        let hosts = lan_hosts(
991            &[peer("", "stable", "10.0.0.77", 29700, &["A"], 5)],
992            &HashSet::new(),
993            &[],
994            NOW,
995        );
996        assert_eq!(hosts[0].display_name, "unnamed host");
997    }
998
999    /// Codex P2 on #4241: two instances on one machine and channel (an installed
1000    /// and a portable build) host different agents; neither may replace the other.
1001    #[test]
1002    fn two_instances_on_one_channel_both_stay() {
1003        let peers = [
1004            peer("narko2", "stable", "10.0.0.50", 29700, &["A"], 5),
1005            peer("narko2", "stable", "10.0.0.50", 29702, &["B"], 5),
1006        ];
1007        let hosts = lan_hosts(&peers, &HashSet::new(), &[], NOW);
1008        assert_eq!(hosts.len(), 1);
1009        let chans: Vec<&str> = hosts[0]
1010            .channels
1011            .iter()
1012            .map(|c| c.channel.as_str())
1013            .collect();
1014        assert_eq!(chans, ["stable :29700", "stable :29702"]);
1015    }
1016
1017    #[test]
1018    fn the_same_instance_seen_twice_is_listed_once() {
1019        let older = peer("Area54", "stable", "10.0.0.26", 29700, &["Old"], 50);
1020        let newer = peer("Area54", "stable", "10.0.0.26", 29700, &["New"], 5);
1021        let hosts = lan_hosts(&[older, newer], &HashSet::new(), &[], NOW);
1022        assert_eq!(hosts[0].channels.len(), 1);
1023        assert_eq!(hosts[0].channels[0].channel, "stable");
1024        assert_eq!(hosts[0].channels[0].agents[0].name, "New");
1025    }
1026
1027    // The platform tag (SPEC_SWARM_REMOTE_AGENTS_PLATFORM_TAG_AND_SELECTION_2026_10_03.md §3).
1028    #[test]
1029    fn this_machines_other_channels_carry_this_machines_platform() {
1030        let chans = other_channels(
1031            &[entry("Loap", "dev-fix", 0)],
1032            &ChannelStatuses::new(),
1033            "stable",
1034            "",
1035            NOW,
1036        );
1037        assert_eq!(chans[0].os, crate::backend::host_os::local_os());
1038    }
1039
1040    #[test]
1041    fn a_lan_peer_carries_the_platform_it_advertised_and_none_when_it_did_not() {
1042        let mut mac = peer("Area54", "stable", "10.0.0.26", 29700, &["Manoz"], 5);
1043        mac.os = "macos".to_string();
1044        let old = peer("starpower", "stable", "10.0.0.27", 29700, &["Opaz"], 5);
1045        let hosts = lan_hosts(&[mac, old], &HashSet::new(), &[], NOW);
1046        let os_of = |name: &str| {
1047            hosts
1048                .iter()
1049                .find(|h| h.display_name == name)
1050                .unwrap()
1051                .channels[0]
1052                .os
1053                .clone()
1054        };
1055        assert_eq!(os_of("Area54"), "macos");
1056        assert_eq!(os_of("starpower"), "");
1057    }
1058
1059    #[test]
1060    fn two_instances_on_one_host_keep_their_own_platform() {
1061        // A Windows machine that also runs an instance inside WSL.
1062        let mut win = peer("narko2", "stable", "10.0.0.30", 29700, &["A"], 5);
1063        win.os = "windows".to_string();
1064        let mut wsl = peer("narko2", "stable", "10.0.0.30", 29702, &["B"], 5);
1065        wsl.os = "linux".to_string();
1066        let hosts = lan_hosts(&[win, wsl], &HashSet::new(), &[], NOW);
1067        let mut oses: Vec<String> = hosts[0].channels.iter().map(|c| c.os.clone()).collect();
1068        oses.sort();
1069        assert_eq!(oses, vec!["linux".to_string(), "windows".to_string()]);
1070    }
1071
1072    // Phase 4: each agent's state (SPEC_SWARM_OTHER_HOSTS_AND_CHANNELS_2026_10_02.md §3.4).
1073    #[test]
1074    fn another_channels_agents_carry_the_state_that_channel_reported() {
1075        let report = ChannelReport {
1076            status: [("korp".to_string(), AgentState::Waiting)].into_iter().collect(),
1077            lines: [("korp".to_string(), "Fixing the login race".to_string())].into_iter().collect(),
1078            providers: [("korp".to_string(), "codex".to_string())].into_iter().collect(),
1079            kinds: Default::default(),
1080        };
1081        let statuses: ChannelStatuses = [("dev".to_string(), report)].into_iter().collect();
1082        let chans = other_channels(
1083            &[entry("Korp", "dev", 0), entry("Loap", "dev", 0)],
1084            &statuses,
1085            "stable",
1086            "",
1087            NOW,
1088        );
1089        let got: Vec<(&str, Option<AgentState>)> = chans[0]
1090            .agents
1091            .iter()
1092            .map(|a| (a.name.as_str(), a.status))
1093            .collect();
1094        assert_eq!(got, [("Korp", Some(AgentState::Waiting)), ("Loap", None)]);
1095        // An agent with no state has no `status` key at all.
1096        let json = serde_json::to_value(&chans[0].agents).unwrap();
1097        assert_eq!(json[0]["status"], "waiting");
1098        assert!(json[1].get("status").is_none(), "{json}");
1099        // The same for the line, and the provider.
1100        assert_eq!(json[0]["line"], "Fixing the login race");
1101        assert!(json[1].get("line").is_none(), "{json}");
1102        assert_eq!(json[0]["provider"], "codex");
1103        assert!(json[1].get("provider").is_none(), "{json}");
1104    }
1105
1106    #[test]
1107    fn a_lan_peers_agents_carry_the_state_it_reported() {
1108        let mut p = peer(
1109            "Area54",
1110            "stable",
1111            "10.0.0.26",
1112            29700,
1113            &["Manoz", "Opaz"],
1114            5,
1115        );
1116        p.agent_status.insert("manoz".into(), AgentState::Working);
1117        p.agent_lines.insert("manoz".into(), "Fixing the login race".into());
1118        p.agent_providers.insert("manoz".into(), "claude".into());
1119        let hosts = lan_hosts(&[p], &HashSet::new(), &[], NOW);
1120        let got: Vec<(Option<AgentState>, Option<&str>, Option<&str>)> = hosts[0].channels[0]
1121            .agents
1122            .iter()
1123            .map(|a| (a.status, a.line.as_deref(), a.provider.as_deref()))
1124            .collect();
1125        assert_eq!(
1126            got,
1127            [
1128                (Some(AgentState::Working), Some("Fixing the login race"), Some("claude")),
1129                (None, None, None)
1130            ]
1131        );
1132    }
1133
1134    /// The Swarm and the map draw an agent as host or container: from what its instance said, and
1135    /// nothing when it said nothing.
1136    #[test]
1137    fn remote_agents_carry_where_their_instance_says_they_run() {
1138        let mut p = peer("Area54", "stable", "10.0.0.26", 29700, &["Manoz", "Opaz"], 5);
1139        p.agent_kinds.insert("opaz".into(), RuntimeKind::Container);
1140        let hosts = lan_hosts(&[p], &HashSet::new(), &[], NOW);
1141        let got: Vec<Option<RuntimeKind>> = hosts[0].channels[0].agents.iter().map(|a| a.runtime).collect();
1142        assert_eq!(got, [None, Some(RuntimeKind::Container)]);
1143        let json = serde_json::to_value(&hosts[0].channels[0].agents).unwrap();
1144        assert!(json[0].get("runtime").is_none(), "{json}");
1145        assert_eq!(json[1]["runtime"], "container");
1146
1147        // Another channel of this machine: from the same answer, over loopback.
1148        let mut report = ChannelReport::default();
1149        report.kinds.insert("korp".into(), RuntimeKind::Container);
1150        let statuses: ChannelStatuses = [("dev".to_string(), report)].into();
1151        let chans = other_channels(&[entry("Korp", "dev", 0), entry("Loap", "dev", 0)], &statuses, "stable", "", NOW);
1152        let got: Vec<Option<RuntimeKind>> = chans[0].agents.iter().map(|a| a.runtime).collect();
1153        assert_eq!(got, [Some(RuntimeKind::Container), None]);
1154    }
1155
1156    #[test]
1157    fn a_lan_peers_agents_carry_the_seat_it_reported() {
1158        let mut p = peer("Area54", "stable", "10.0.0.26", 29700, &["Manoz", "Opaz"], 5);
1159        let seat = crate::backend::rpc_types::SeatSummary {
1160            role: "specialist".into(),
1161            qualifier: None,
1162            lead: Some(crate::backend::rpc_types::SeatLead { id: "uid-agentx".into(), name: Some("AgentX".into()) }),
1163            area: Some("agent pane lifecycle".into()),
1164        };
1165        p.agent_seats.insert("manoz".into(), seat.clone());
1166        let hosts = lan_hosts(&[p], &HashSet::new(), &[], NOW);
1167        let got: Vec<Option<&crate::backend::rpc_types::SeatSummary>> =
1168            hosts[0].channels[0].agents.iter().map(|a| a.seat.as_ref()).collect();
1169        assert_eq!(got, [Some(&seat), None]);
1170    }
1171
1172    #[test]
1173    fn status_targets_are_live_loopback_instances_other_than_this_one() {
1174        let at = |name: &str, channel: &str, url: &str, age_ms: u64| {
1175            let mut e = entry(name, channel, age_ms);
1176            e.local_url = url.to_string();
1177            e
1178        };
1179        let entries = [
1180            at("Korp", "dev", "http://127.0.0.1:29702", 0),
1181            at("Loap", "dev", "http://127.0.0.1:29702", 0),
1182            at("Old", "gone", "http://127.0.0.1:29703", STALE_AFTER_MS + 1),
1183            at("Far", "lan", "http://10.0.0.9:29700", 0),
1184            at("Me", "renamed", "http://127.0.0.1:29700", 0),
1185            at("Self", "stable", "http://127.0.0.1:29701", 0),
1186            at("Nochan", "", "http://127.0.0.1:29704", 0),
1187            at("Six", "v6", "http://[::1]:29705", 0),
1188        ];
1189        let targets = channel_status_targets(&entries, "stable", "http://127.0.0.1:29700", NOW);
1190        let urls: Vec<(&str, &str)> = targets
1191            .iter()
1192            .map(|t| (t.channel.as_str(), t.local_url.as_str()))
1193            .collect();
1194        assert_eq!(
1195            urls,
1196            [
1197                ("dev", "http://127.0.0.1:29702"),
1198                ("v6", "http://[::1]:29705")
1199            ],
1200            "one per instance; not stale, not off-machine, not this instance"
1201        );
1202        assert_eq!(targets[0].auth_key, "secret");
1203    }
1204
1205    /// An instance that restarted on the same URL has a new key, and its older
1206    /// entries keep the old one for a while. Whatever order the registry lists
1207    /// them in, the freshest entry's key is used (#4703).
1208    #[test]
1209    fn a_restarted_instance_is_asked_with_its_newest_key() {
1210        let at = |name: &str, age_ms: u64, key: &str| {
1211            let mut e = entry(name, "dev", age_ms);
1212            e.local_url = "http://127.0.0.1:29702".to_string();
1213            e.auth_key = key.to_string();
1214            e
1215        };
1216        let entries = [
1217            at("Korp", 30_000, "old-key"),
1218            at("Loap", 1_000, "new-key"),
1219            at("Opaz", 20_000, "old-key"),
1220        ];
1221        for order in [entries.to_vec(), entries.iter().rev().cloned().collect()] {
1222            let targets = channel_status_targets(&order, "stable", "", NOW);
1223            assert_eq!(targets.len(), 1);
1224            assert_eq!(targets[0].auth_key, "new-key");
1225        }
1226    }
1227
1228    /// One-shot HTTP server answering any request with `body`, and the request it
1229    /// received.
1230    async fn serve_once(body: &'static str) -> (String, tokio::sync::oneshot::Receiver<String>) {
1231        use tokio::io::{AsyncReadExt, AsyncWriteExt};
1232        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1233        let url = format!("http://{}", listener.local_addr().unwrap());
1234        let (tx, rx) = tokio::sync::oneshot::channel();
1235        tokio::spawn(async move {
1236            let Ok((mut stream, _)) = listener.accept().await else {
1237                return;
1238            };
1239            let mut buf = [0u8; 4096];
1240            let n = stream.read(&mut buf).await.unwrap_or(0);
1241            let _ = tx.send(String::from_utf8_lossy(&buf[..n]).into_owned());
1242            let response = format!(
1243                "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
1244                body.len()
1245            );
1246            let _ = stream.write_all(response.as_bytes()).await;
1247        });
1248        (url, rx)
1249    }
1250
1251    #[tokio::test]
1252    async fn channel_statuses_asks_each_instance_and_skips_one_that_fails() {
1253        let (url, request) = serve_once(
1254            r#"{"agents":["Korp"],"now_ms":1,"agent_status":{"Korp":{"state":"working","since_ms":1}},"agent_lines":{"Korp":"Building"}}"#,
1255        )
1256        .await;
1257        let targets = [
1258            ChannelStatusTarget {
1259                channel: "dev".into(),
1260                local_url: url,
1261                auth_key: "chan-key".into(),
1262            },
1263            // Nothing listens on the discard port.
1264            ChannelStatusTarget {
1265                channel: "dead".into(),
1266                local_url: "http://127.0.0.1:9".into(),
1267                auth_key: "k".into(),
1268            },
1269        ];
1270        let statuses = channel_statuses(&reqwest::Client::new(), &targets).await;
1271        assert_eq!(statuses.len(), 1, "{statuses:?}");
1272        assert_eq!(statuses["dev"].status.get("korp"), Some(&AgentState::Working));
1273        assert_eq!(statuses["dev"].lines.get("korp").map(String::as_str), Some("Building"));
1274        let request = request.await.unwrap().to_lowercase();
1275        assert!(
1276            request.starts_with("get /agentmux/reactive/agent-names "),
1277            "{request}"
1278        );
1279        assert!(
1280            request.contains(&format!(
1281                "{}: chan-key",
1282                agentmux_common::AUTH_KEY_HEADER.to_lowercase()
1283            )),
1284            "{request}"
1285        );
1286    }
1287
1288    fn with_uid(name: &str, channel: &str, uid: &str) -> AgentEntry {
1289        AgentEntry { uid: uid.to_string(), ..entry(name, channel, 0) }
1290    }
1291
1292    /// REPORT_SWARM_REMOTE_PROVIDER_ICON_RCA_2026_10_18.md: an instance from
1293    /// before providers were reported still shows its agents' providers, from
1294    /// this machine's definitions.
1295    #[test]
1296    fn an_older_channels_agents_get_their_defined_provider() {
1297        let entries = [with_uid("Camper", "dev", "uid-camper"), with_uid("Clamk", "dev", "uid-clamk"), entry("Loap", "dev", 0)];
1298        let defined: DefinedProviders =
1299            [("uid-camper".to_string(), "claude".to_string()), ("uid-clamk".to_string(), "codex".to_string())].into();
1300        let mut snap = snapshot(&entries, &ChannelStatuses::new(), &[], &HashSet::new(), &[], "narko", "stable", "", NOW);
1301        fill_defined_providers(&mut snap, &entries, &defined);
1302        let got: Vec<(&str, Option<&str>)> =
1303            snap.hosts[0].channels[0].agents.iter().map(|a| (a.name.as_str(), a.provider.as_deref())).collect();
1304        // Loap's entry has no uid, so nothing is known about it.
1305        assert_eq!(got, vec![("Camper", Some("claude")), ("Clamk", Some("codex")), ("Loap", None)]);
1306    }
1307
1308    #[test]
1309    fn the_instances_own_report_wins_over_the_definition() {
1310        let entries = [with_uid("Camper", "dev", "uid-camper")];
1311        let mut report = ChannelReport::default();
1312        report.providers.insert("camper".into(), "codex".into());
1313        let statuses: ChannelStatuses = [("dev".to_string(), report)].into();
1314        let defined: DefinedProviders = [("uid-camper".to_string(), "claude".to_string())].into();
1315        let mut snap = snapshot(&entries, &statuses, &[], &HashSet::new(), &[], "narko", "stable", "", NOW);
1316        fill_defined_providers(&mut snap, &entries, &defined);
1317        assert_eq!(snap.hosts[0].channels[0].agents[0].provider.as_deref(), Some("codex"));
1318    }
1319
1320    #[test]
1321    fn lan_hosts_are_left_as_they_are() {
1322        let entries = [with_uid("Camper", "dev", "uid-camper")];
1323        let defined: DefinedProviders = [("uid-camper".to_string(), "claude".to_string())].into();
1324        let agent = remote_agent("Camper", None);
1325        let channel = RemoteChannel { channel: "dev".into(), seen_at_ms: NOW, stale: false, os: String::new(), agents: vec![agent], route: None, paired_computer: None };
1326        let mut snap = SwarmOtherInstancesResult {
1327            hostname: "narko".into(),
1328            channel: "stable".into(),
1329            hosts: vec![RemoteHost { host_id: "lan:x".into(), display_name: "x".into(), tier: "lan", channels: vec![channel] }],
1330            cloud: None,
1331        };
1332        fill_defined_providers(&mut snap, &entries, &defined);
1333        assert_eq!(snap.hosts[0].channels[0].agents[0].provider, None, "another machine's agent isn't this machine's definition");
1334    }
1335
1336    #[test]
1337    fn only_known_providers_are_read_from_the_definitions() {
1338        let entries = [with_uid("A", "dev", "u1"), with_uid("B", "dev", "u2"), with_uid("C", "dev", "u3"), entry("D", "dev", 0)];
1339        let defined = defined_providers_from(&entries, |uid| match uid {
1340            "u1" => Some(" claude ".to_string()),
1341            "u2" => Some("<b>made-up</b>".to_string()),
1342            _ => None,
1343        });
1344        assert_eq!(defined, [("u1".to_string(), "claude".to_string())].into());
1345    }
1346}