1use 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
37pub const STALE_AFTER_MS: u64 = 60_000;
41
42pub const HIDE_AFTER_MS: u64 = 10 * 60_000;
46
47#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
48pub struct RemoteAgent {
49 pub name: String,
50 pub block_id: String,
53 #[serde(skip_serializing_if = "Option::is_none")]
56 pub status: Option<AgentState>,
57 #[serde(skip_serializing_if = "Option::is_none")]
60 pub line: Option<String>,
61 #[serde(skip_serializing_if = "Option::is_none")]
65 pub provider: Option<String>,
66 #[serde(skip_serializing_if = "Option::is_none")]
71 pub seat: Option<crate::backend::rpc_types::SeatSummary>,
72 #[serde(skip_serializing_if = "Option::is_none")]
75 pub account: Option<String>,
76 #[serde(skip_serializing_if = "Option::is_none")]
79 pub account_label: Option<String>,
80 #[serde(skip_serializing_if = "Option::is_none")]
83 pub runtime: Option<RuntimeKind>,
84}
85
86#[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
95pub type ChannelStatuses = HashMap<String, ChannelReport>;
97
98#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
99pub struct RemoteChannel {
100 pub channel: String,
101 pub seen_at_ms: u64,
103 pub stale: bool,
105 pub os: String,
109 pub agents: Vec<RemoteAgent>,
111 #[serde(skip)]
115 pub route: Option<PeerRoute>,
116 #[serde(skip_serializing_if = "Option::is_none")]
121 pub paired_computer: Option<String>,
122}
123
124#[derive(Clone, PartialEq, Eq)]
126pub struct PeerRoute {
127 pub url: String,
128 pub auth_key: String,
129}
130
131impl 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 pub host_id: String,
142 pub display_name: String,
143 pub tier: &'static str,
145 pub channels: Vec<RemoteChannel>,
147}
148
149#[derive(Debug, Clone, PartialEq, Eq)]
151pub struct PairedComputer {
152 pub id: String,
153 pub host: String,
155 pub hostname: String,
156 pub channel: String,
159}
160
161pub 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#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
172pub struct SwarmOtherInstancesResult {
173 pub hostname: String,
176 pub channel: String,
177 pub hosts: Vec<RemoteHost>,
178 #[serde(skip_serializing_if = "Option::is_none")]
181 pub cloud: Option<&'static str>,
182}
183
184pub 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 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
250fn 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
270fn 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
286pub 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 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 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 let host = hosts
327 .entry(format!("{}@{}", display.to_lowercase(), p.address))
328 .or_insert_with(|| (display.clone(), BTreeMap::new()));
329 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 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 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
388fn 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
406const CHANNEL_STATUS_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(1500);
410
411#[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
425pub 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
464pub 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
504pub 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
536pub type DefinedProviders = HashMap<String, String>;
539
540pub 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
566pub 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
591pub type AccountLabels = HashMap<String, String>;
594
595pub 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 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 #[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 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 #[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 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 #[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 #[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 #[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 #[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 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 #[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 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 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 #[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 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 #[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 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 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 #[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 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}