Skip to main content

agentmux_srv_core/backend/lan/discovery/
agent_names.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Reading an instance's `/agentmux/reactive/agent-names` answer: the names a
5//! LAN peer's poll (and the Swarm's ask of this machine's other channels) list,
6//! and each listed agent's state and summary line, for the Swarm's remote rows
7//! (SPEC_SWARM_OTHER_HOSTS_AND_CHANNELS_2026_10_02.md §3.4 Phase 4).
8
9use super::*;
10use crate::backend::runtime_adapter::RuntimeKind;
11use std::collections::HashSet;
12
13/// This instance's `/agentmux/reactive/agent-names` answer. Readable with the
14/// LAN key, so public to the local network: each field needed the owner's
15/// decision.
16/// - `agents`, enumerating names (2026-09-08): a `lan_key` holder could
17///   already confirm a specific name via `/agentmux/reactive/agent?id=…`.
18/// - `agent_kinds` (`{name: "host" | "container"}`, 2026-10-06, agentmux-mobile's
19///   SPEC_FLEET_HOST_TAGS_AND_CLOUD_HOSTS_2026_10_06 §5.2, §11).
20/// - `agent_status` (`{name: {state, since_ms}}`) and `now_ms`, decision D1 of
21///   2026-10-07 (agentmux-mobile's SPEC_AGENT_STATUS_AND_LIVE_PANE_FEED_2026_10_07
22///   §3.4, §11), also on the fleet feed this route is the fallback for.
23/// - `agent_lines` (`{name: line}`, 2026-10-13): content, each agent's Swarm
24///   summary line (`backend::agent_line`); absent with `swarm:sharesummaries` off.
25/// - `agent_providers` (`{name: provider id}`, decision D1 of 2026-10-17,
26///   SPEC_SWARM_REFINEMENTS_2026_10_17 §3, §7): the Swarm's provider icon on
27///   remote rows. Only an id this build knows (`providers::resolve_provider_alias`).
28/// - `agent_seats` (`{name: {role, qualifier, lead: {id, name}, area}}`,
29///   SPEC_AGENT_SEATS_IN_THE_UI_2026_10_23.md §5, approved 2026-10-23): each
30///   agent's seat as the operator set it (or a spawned worker's effective one),
31///   for the Swarm's remote rows and `Agents list`'s `lan` entries.
32/// - `agent_accounts` (`{name: stable account id}`, SPEC_AGENTS_OPERATE_OTHER_MACHINES_2026_10_30.md
33///   §4.4, approved by the operator 2026-10-30): the account each agent's pane runs on, so
34///   `Agents list` and the Swarm can show "out until ..., on account X" for another machine.
35///   The id (`identity::stable_account`) is a hash, never the email, a provider id or a local id.
36/// - `agent_resets` (`{name: unix ms}`, SPEC_AGENT_AVAILABILITY_EVERY_PATH_ONE_DECISION_2026_10_31.md
37///   D5): when a limited agent's usage limit lifts, for the agents whose provider named a time. A
38///   time only; never the account, the title or the failure text.
39///
40/// An agent with no kind, state, line, provider or seat is left out of that map.
41pub fn agent_names_body(
42    mstore: &crate::backend::storage::store::Store,
43    settings: &crate::backend::wconfig::SettingsType,
44    agents: &[crate::backend::reactive::types::AgentRegistration],
45    account_of_block: impl Fn(&str) -> Option<String>,
46) -> serde_json::Value {
47    let pairs = || agents.iter().map(|a| (a.agent_id.as_str(), a.block_id.as_str()));
48    let kinds = crate::backend::fleet_source::kinds_by_name(pairs(), |block_id| {
49        crate::backend::operator_config_seed::agent_kind_of_block(mstore, block_id)
50    });
51    let status: BTreeMap<&str, _> = pairs()
52        .filter_map(|(name, block_id)| crate::backend::agent_state::agent_status_of_block(mstore, block_id).map(|s| (name, s)))
53        .collect();
54    let providers: BTreeMap<&str, &str> = pairs()
55        .filter_map(|(name, block_id)| {
56            let block = mstore.get::<crate::backend::obj::Block>(block_id).ok()??;
57            let raw = crate::backend::obj::meta_get_string(&block.meta, "agentProvider", "");
58            let id = crate::backend::providers::resolve_provider_alias(&raw);
59            (!id.is_empty()).then_some((name, id))
60        })
61        .collect();
62    let accounts: BTreeMap<&str, String> = pairs().filter_map(|(name, block_id)| Some((name, account_of_block(block_id)?))).collect();
63    let now_ms = agentmux_common::time::now_ms_u64();
64    let resets: BTreeMap<&str, u64> = pairs()
65        .filter_map(|(name, block_id)| {
66            let out = crate::backend::agent_state::unavailable_of_block(mstore, None, block_id, now_ms)?;
67            (out.state == AgentState::Limited).then_some(())?;
68            Some((name, out.resets_at_ms?))
69        })
70        .collect();
71    let seats: BTreeMap<&str, crate::backend::rpc_types::SeatSummary> = agents
72        .iter()
73        .filter_map(|a| {
74            let uid = a.uid.as_deref().filter(|u| !u.is_empty())?;
75            let seat = crate::backend::agent_seat::effective_seat_by_id(mstore, uid)?;
76            let summary = crate::backend::agent_seat::summarize(&seat, |id| {
77                mstore.agent_def_get(id).ok().flatten().map(|d| d.name)
78            });
79            Some((a.agent_id.as_str(), summary))
80        })
81        .collect();
82    let mut body = json!({
83        "agents": agents.iter().map(|a| a.agent_id.as_str()).collect::<Vec<_>>(),
84        "agent_kinds": kinds,
85        "now_ms": now_ms,
86        "agent_status": status,
87        "agent_providers": providers,
88    });
89    if !seats.is_empty() {
90        body["agent_seats"] = json!(seats);
91    }
92    if !accounts.is_empty() {
93        body["agent_accounts"] = json!(accounts);
94    }
95    if !resets.is_empty() {
96        body["agent_resets"] = json!(resets);
97    }
98    if let Some(lines) = crate::backend::agent_line::lines_by_name(mstore, settings, pairs()) {
99        body["agent_lines"] = json!(lines);
100    }
101    body
102}
103
104/// What an instance's `/agentmux/reactive/agent-names` answer says about its
105/// agents.
106#[derive(Debug, Default, Clone, PartialEq, Eq)]
107pub struct PeerAgents {
108    pub names: Vec<String>,
109    /// Lower-cased name → state, for listed names only.
110    pub status: BTreeMap<String, AgentState>,
111    /// Lower-cased name → summary line (`backend::agent_line`), for listed
112    /// names only, each cleaned again here.
113    pub lines: BTreeMap<String, String>,
114    /// Lower-cased name → provider id, for listed names only, and only an id
115    /// this build knows (`providers::resolve_provider_alias`), so a peer can't
116    /// put free text in a row (SPEC_SWARM_REFINEMENTS_2026_10_17.md §3).
117    pub providers: BTreeMap<String, String>,
118    /// Lower-cased name → where it runs, for listed names only, and only `host` or `container`
119    /// (`RuntimeKind::parse`), so a peer can't put free text in a row.
120    pub kinds: BTreeMap<String, RuntimeKind>,
121    /// Lower-cased name → seat, for listed names only, bounded by
122    /// `agent_seat::sanitize_peer_summary` (SPEC_AGENT_SEATS_IN_THE_UI_2026_10_23.md §5).
123    pub seats: BTreeMap<String, crate::backend::rpc_types::SeatSummary>,
124    /// Lower-cased name → stable account id, for listed names only, and only one of the
125    /// form `identity::stable_account` makes (`is_stable_id`).
126    pub accounts: BTreeMap<String, String>,
127    /// Lower-cased name → when its usage limit lifts (unix ms), for listed names only.
128    pub resets: BTreeMap<String, u64>,
129}
130
131/// The `agent_kinds` of an `agent-names` body: `host` or `container` for a listed name, nothing else.
132fn parse_kinds(value: &serde_json::Value, listed: &HashSet<String>) -> BTreeMap<String, RuntimeKind> {
133    let Some(map) = value.get("agent_kinds").and_then(|s| s.as_object()) else { return BTreeMap::new() };
134    map.iter()
135        .filter(|(name, _)| listed.contains(&name.to_lowercase()))
136        .filter_map(|(name, kind)| Some((name.to_lowercase(), RuntimeKind::parse(kind.as_str()?)?)))
137        .collect()
138}
139
140/// Reads an `agent-names` body: the names, capped as above, and each listed
141/// agent's state from `agent_status` (`{name: {state, since_ms}}`). A state for
142/// a name the body doesn't list, or one this build doesn't know, is dropped,
143/// so the map is never larger than the name list. The same goes for
144/// `agent_lines` (`{name: line}`). A body from a build before `agent_status`
145/// gives names only.
146pub fn parse_agent_names_body(value: &serde_json::Value) -> PeerAgents {
147    let names: Vec<String> = value
148        .get("agents")
149        .and_then(|a| a.as_array())
150        .map(|a| {
151            a.iter()
152                .filter_map(|n| n.as_str())
153                .filter(|n| n.len() <= LAN_AGENT_NAMES_MAX_NAME_LEN)
154                .take(LAN_AGENT_NAMES_MAX_COUNT)
155                .map(str::to_string)
156                .collect()
157        })
158        .unwrap_or_default();
159    let listed: HashSet<String> = names.iter().map(|n| n.to_lowercase()).collect();
160    let status = value
161        .get("agent_status")
162        .and_then(|s| s.as_object())
163        .map(|map| {
164            map.iter()
165                .filter(|(name, _)| listed.contains(&name.to_lowercase()))
166                .filter_map(|(name, s)| {
167                    let state =
168                        serde_json::from_value::<AgentState>(s.get("state")?.clone()).ok()?;
169                    Some((name.to_lowercase(), state))
170                })
171                .collect()
172        })
173        .unwrap_or_default();
174    let lines = value
175        .get("agent_lines")
176        .and_then(|s| s.as_object())
177        .map(|map| {
178            map.iter()
179                .filter(|(name, _)| listed.contains(&name.to_lowercase()))
180                .filter_map(|(name, line)| {
181                    let line = crate::backend::agent_line::clean_line(line.as_str()?)?;
182                    Some((name.to_lowercase(), line))
183                })
184                .collect()
185        })
186        .unwrap_or_default();
187    let providers = value
188        .get("agent_providers")
189        .and_then(|s| s.as_object())
190        .map(|map| {
191            map.iter()
192                .filter(|(name, _)| listed.contains(&name.to_lowercase()))
193                .filter_map(|(name, provider)| {
194                    let id = crate::backend::providers::resolve_provider_alias(provider.as_str()?);
195                    (!id.is_empty()).then(|| (name.to_lowercase(), id.to_string()))
196                })
197                .collect()
198        })
199        .unwrap_or_default();
200    let kinds = parse_kinds(value, &listed);
201    let seats = value
202        .get("agent_seats")
203        .and_then(|s| s.as_object())
204        .map(|map| {
205            map.iter()
206                .filter(|(name, _)| listed.contains(&name.to_lowercase()))
207                .filter_map(|(name, seat)| {
208                    let seat = crate::backend::agent_seat::sanitize_peer_summary(seat, LAN_AGENT_NAMES_MAX_NAME_LEN)?;
209                    Some((name.to_lowercase(), seat))
210                })
211                .collect()
212        })
213        .unwrap_or_default();
214    let accounts = value
215        .get("agent_accounts")
216        .and_then(|s| s.as_object())
217        .map(|map| {
218            map.iter()
219                .filter(|(name, _)| listed.contains(&name.to_lowercase()))
220                .filter_map(|(name, id)| {
221                    let id = id.as_str()?;
222                    crate::identity::stable_account::is_stable_id(id).then(|| (name.to_lowercase(), id.to_string()))
223                })
224                .collect()
225        })
226        .unwrap_or_default();
227    let resets = value
228        .get("agent_resets")
229        .and_then(|s| s.as_object())
230        .map(|map| {
231            map.iter()
232                .filter(|(name, _)| listed.contains(&name.to_lowercase()))
233                .filter_map(|(name, at)| Some((name.to_lowercase(), at.as_u64()?)))
234                .collect()
235        })
236        .unwrap_or_default();
237    PeerAgents { names, status, lines, providers, kinds, seats, accounts, resets }
238}
239
240/// Applies one poll of a peer's `agent-names` route to its entry, and says
241/// whether what the frontend shows changed. A failed poll keeps the last-known
242/// names, since a flapping list is worse than a slightly old one, but clears
243/// the states and lines: mDNS can keep the peer looking fresh long after it
244/// stopped answering, and its last "working" would otherwise show indefinitely
245/// (#4703).
246pub(super) fn apply_agent_names_poll(
247    entry: &mut LanInstance,
248    peer: Option<PeerAgents>,
249    now_secs: u64,
250) -> bool {
251    let Some(peer) = peer else {
252        let changed = !entry.agent_status.is_empty()
253            || !entry.agent_lines.is_empty()
254            || !entry.agent_accounts.is_empty()
255            || !entry.agent_resets.is_empty();
256        entry.agent_status.clear();
257        entry.agent_lines.clear();
258        entry.agent_accounts.clear();
259        entry.agent_resets.clear();
260        return changed;
261    };
262    entry.last_polled_ok = now_secs;
263    let changed = entry.agents != peer.names
264        || entry.agent_status != peer.status
265        || entry.agent_lines != peer.lines
266        || entry.agent_providers != peer.providers
267        || entry.agent_kinds != peer.kinds
268        || entry.agent_seats != peer.seats
269        || entry.agent_accounts != peer.accounts
270        || entry.agent_resets != peer.resets;
271    entry.agents = peer.names;
272    // Kept after the peer goes quiet, so a message to one of these agents is held instead of lost.
273    crate::backend::lan::seen_agents::remember(&entry.agents, &entry.hostname, now_secs);
274    entry.agent_status = peer.status;
275    entry.agent_lines = peer.lines;
276    entry.agent_providers = peer.providers;
277    entry.agent_kinds = peer.kinds;
278    entry.agent_seats = peer.seats;
279    entry.agent_accounts = peer.accounts;
280    entry.agent_resets = peer.resets;
281    changed
282}
283
284#[cfg(test)]
285mod tests {
286    use super::*;
287
288    /// The Swarm's status chip on remote rows
289    /// (SPEC_SWARM_OTHER_HOSTS_AND_CHANNELS_2026_10_02.md §3.4 Phase 4).
290    #[test]
291    fn agent_status_is_kept_for_listed_agents_with_a_known_state() {
292        let body = serde_json::json!({
293            "agents": ["Manoz", "Opaz", "Loap", "Korp"],
294            "now_ms": 5_000,
295            "agent_status": {
296                "Manoz": {"state": "working", "since_ms": 1_000},
297                "opaz": {"state": "waiting", "since_ms": 2_000},
298                "Loap": {"state": "dreaming", "since_ms": 2_000},
299                "Korp": {"since_ms": 2_000},
300                "Ghost": {"state": "idle", "since_ms": 2_000},
301            },
302        });
303        let peer = parse_agent_names_body(&body);
304        assert_eq!(peer.names, ["Manoz", "Opaz", "Loap", "Korp"]);
305        let status: Vec<(&str, AgentState)> = peer
306            .status
307            .iter()
308            .map(|(k, v): (&String, &AgentState)| (k.as_str(), *v))
309            .collect();
310        // Keyed by lower-cased name; an unknown state, a missing state and a
311        // name the body doesn't list are all dropped.
312        assert_eq!(
313            status,
314            [
315                ("manoz", AgentState::Working),
316                ("opaz", AgentState::Waiting)
317            ]
318        );
319    }
320
321    #[test]
322    fn agent_lines_are_kept_for_listed_agents_as_one_bounded_line() {
323        let body = serde_json::json!({
324            "agents": ["Manoz", "Opaz", "Loap"],
325            "agent_lines": {
326                "Manoz": "Fixing the\nlogin race",
327                "opaz": "x".repeat(500),
328                "Loap": 7,
329                "Ghost": "Not listed",
330            },
331        });
332        let peer = parse_agent_names_body(&body);
333        assert_eq!(peer.lines.get("manoz").map(String::as_str), Some("Fixing the login race"));
334        assert_eq!(
335            peer.lines.get("opaz").map(|l| l.chars().count()),
336            Some(crate::backend::agent_line::MAX_LINE_CHARS)
337        );
338        assert_eq!(peer.lines.len(), 2, "{:?}", peer.lines);
339    }
340
341    /// `agent_accounts` is a name -> stable account id map: only listed agents, only ids of the
342    /// shape `identity::stable_account` makes, so a peer cannot put free text or an email in a row.
343    #[test]
344    fn agent_accounts_keep_only_stable_ids_for_listed_agents() {
345        let body = serde_json::json!({
346            "agents": ["Manoz", "Opaz", "Loap"],
347            "agent_accounts": {
348                "Manoz": "claude:0123456789abcdef",
349                "Opaz": "me@example.com",
350                "Loap": "claude:e0123456789abcde",
351                "Gone": "claude:0123456789abcdef",
352            }
353        });
354        let peer = parse_agent_names_body(&body);
355        let got: Vec<(&str, &str)> = peer.accounts.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
356        assert_eq!(got, vec![("loap", "claude:e0123456789abcde"), ("manoz", "claude:0123456789abcdef")]);
357        assert!(parse_agent_names_body(&serde_json::json!({"agents": ["Manoz"]})).accounts.is_empty());
358    }
359
360    /// The body carries what the lookup says, and a failed poll forgets it with the states.
361    #[test]
362    fn agent_accounts_are_sent_and_a_failed_poll_clears_them() {
363        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
364        let reg = |name: &str| crate::backend::reactive::types::AgentRegistration {
365            agent_id: name.into(),
366            block_id: format!("blk-{name}"),
367            tab_id: None,
368            uid: None,
369            registered_at: 0,
370            last_seen: 0,
371            registration_nonce: 0,
372        };
373        let agents = [reg("Loap"), reg("shell")];
374        let body = agent_names_body(&store, &Default::default(), &agents, |b| (b == "blk-Loap").then(|| "claude:0123456789abcdef".to_string()));
375        assert_eq!(body["agent_accounts"], serde_json::json!({ "Loap": "claude:0123456789abcdef" }));
376        let none = agent_names_body(&store, &Default::default(), &agents, |_| None);
377        assert!(none.get("agent_accounts").is_none(), "no account, no field: {none}");
378
379        let mut inst = instance();
380        assert!(apply_agent_names_poll(&mut inst, Some(parse_agent_names_body(&body)), 1));
381        assert_eq!(inst.agent_accounts.get("loap").map(String::as_str), Some("claude:0123456789abcdef"));
382        assert!(apply_agent_names_poll(&mut inst, None, 2));
383        assert!(inst.agent_accounts.is_empty());
384    }
385
386    /// The Swarm's provider icon on remote rows (SPEC_SWARM_REFINEMENTS_2026_10_17.md §3).
387    #[test]
388    fn agent_providers_keep_only_known_ids_for_listed_agents() {
389        let body = serde_json::json!({
390            "agents": ["Manoz", "Opaz", "Loap", "Korp"],
391            "agent_providers": {
392                "Manoz": "claude",
393                "opaz": "codex-cli",
394                "Loap": "<script>",
395                "Korp": 7,
396                "Ghost": "gemini",
397            },
398        });
399        let peer = parse_agent_names_body(&body);
400        let got: Vec<(&str, &str)> = peer.providers.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
401        // A legacy alias resolves to its id; free text, a non-string and a name
402        // the body doesn't list are dropped.
403        assert_eq!(got, [("manoz", "claude"), ("opaz", "codex")]);
404    }
405
406    /// Where a peer's agents run: kept for listed agents with a known value, carried onto the entry,
407    /// and left out of its JSON when the peer said nothing (an older build).
408    #[test]
409    fn agent_kinds_keep_only_host_or_container_for_listed_agents() {
410        let body = serde_json::json!({
411            "agents": ["Manoz", "Opaz", "Loap", "Korp"],
412            "agent_kinds": { "Manoz": "host", "opaz": "container", "Loap": "wsl", "Korp": 7, "Ghost": "container" },
413        });
414        let peer = parse_agent_names_body(&body);
415        let got: Vec<(&str, RuntimeKind)> = peer.kinds.iter().map(|(k, v)| (k.as_str(), *v)).collect();
416        assert_eq!(got, [("manoz", RuntimeKind::Host), ("opaz", RuntimeKind::Container)]);
417
418        let mut inst = instance();
419        assert!(apply_agent_names_poll(&mut inst, Some(peer.clone()), 1));
420        assert!(!apply_agent_names_poll(&mut inst, Some(peer), 2), "the same kinds change nothing");
421        assert_eq!(serde_json::to_value(&inst).unwrap()["agent_kinds"], serde_json::json!({ "manoz": "host", "opaz": "container" }));
422        assert!(serde_json::to_value(instance()).unwrap().get("agent_kinds").is_none());
423        assert!(parse_agent_names_body(&serde_json::json!({"agents": ["Manoz"]})).kinds.is_empty());
424    }
425
426    /// Seats on remote rows (SPEC_AGENT_SEATS_IN_THE_UI_2026_10_23.md §5): kept
427    /// for listed agents with a known role, bounded, and carried onto the entry.
428    #[test]
429    fn agent_seats_are_kept_for_listed_agents_and_applied() {
430        let body = serde_json::json!({
431            "agents": ["Manoz", "Opaz", "Loap"],
432            "agent_seats": {
433                "Manoz": { "role": "leader", "qualifier": "product", "lead": null, "area": "x".repeat(300) },
434                "opaz": { "role": "worker", "qualifier": null, "lead": { "id": "uid-m", "name": "Manoz" }, "area": null },
435                "Loap": { "role": "overlord", "qualifier": null, "lead": null, "area": null },
436                "Ghost": { "role": "leader", "qualifier": null, "lead": null, "area": null },
437            },
438        });
439        let peer = parse_agent_names_body(&body);
440        assert_eq!(peer.seats.keys().map(String::as_str).collect::<Vec<_>>(), ["manoz", "opaz"]);
441        assert_eq!(peer.seats["manoz"].area.as_ref().map(|a| a.chars().count()), Some(crate::backend::agent_seat::MAX_AREA_CHARS));
442        assert_eq!(peer.seats["opaz"].lead.as_ref().and_then(|l| l.name.as_deref()), Some("Manoz"));
443
444        let mut inst = instance();
445        assert!(apply_agent_names_poll(&mut inst, Some(peer.clone()), 1));
446        assert_eq!(inst.agent_seats, peer.seats);
447        assert!(!apply_agent_names_poll(&mut inst, Some(peer), 2), "the same seats change nothing");
448        // The entry's JSON (the `lan` of `Agents list`) carries them, and
449        // leaves the key out when there are none.
450        let json = serde_json::to_value(&inst).unwrap();
451        assert_eq!(json["agent_seats"]["manoz"]["role"], "leader");
452        assert!(serde_json::to_value(instance()).unwrap().get("agent_seats").is_none());
453        // A body from before seats gives none.
454        assert!(parse_agent_names_body(&serde_json::json!({"agents": ["Manoz"]})).seats.is_empty());
455    }
456
457    /// A limited peer agent's reset time (availability spec D5): kept for listed agents, a number only,
458    /// and forgotten with the states when a poll fails. An older peer sends none.
459    #[test]
460    fn agent_resets_are_kept_for_listed_agents_and_cleared_by_a_failed_poll() {
461        let body = serde_json::json!({
462            "agents": ["Manoz", "Opaz"],
463            "agent_resets": { "Manoz": 1_792_886_400_000u64, "Opaz": "soon", "Gone": 5 }
464        });
465        let peer = parse_agent_names_body(&body);
466        assert_eq!(peer.resets.iter().collect::<Vec<_>>(), vec![(&"manoz".to_string(), &1_792_886_400_000u64)]);
467        assert!(parse_agent_names_body(&serde_json::json!({"agents": ["Manoz"]})).resets.is_empty());
468
469        let mut inst = instance();
470        assert!(apply_agent_names_poll(&mut inst, Some(peer), 1));
471        assert_eq!(inst.agent_resets.get("manoz"), Some(&1_792_886_400_000u64));
472        assert!(apply_agent_names_poll(&mut inst, None, 2));
473        assert!(inst.agent_resets.is_empty());
474    }
475
476    /// An agent that is not limited has no reset to send, so the body has no field.
477    #[test]
478    fn the_agent_names_body_has_no_resets_when_no_agent_is_limited() {
479        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
480        let agents = [crate::backend::reactive::types::AgentRegistration {
481            agent_id: "Loap".into(),
482            block_id: "blk-Loap".into(),
483            tab_id: None,
484            uid: None,
485            registered_at: 0,
486            last_seen: 0,
487            registration_nonce: 0,
488        }];
489        let body = agent_names_body(&store, &Default::default(), &agents, |_| None);
490        assert!(body.get("agent_resets").is_none(), "{body}");
491    }
492
493    /// This machine's answer gives each registered agent with a seat its
494    /// seat, by its uid's definition, the lead named.
495    #[test]
496    fn the_agent_names_body_serves_seats() {
497        let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
498        let tmp = tempfile::tempdir().unwrap();
499        store.set_def_registry(std::sync::Arc::new(crate::registry::DefinitionStore::open(tmp.path().join("defs")).unwrap()));
500        for (id, name) in [("uid-l", "Camper"), ("uid-w", "Loap")] {
501            let mut def = crate::backend::storage::agents::test_agent_def(id, name, "claude", "host", 1, "");
502            store.agent_def_insert(&mut def).unwrap();
503        }
504        let seat = crate::registry::AgentSeat { role: "worker".into(), lead: Some("uid-l".into()), area: Some("panes".into()), ..Default::default() };
505        store.agent_seat_set("uid-w", Some(&seat)).unwrap();
506        let reg = |name: &str, uid: Option<&str>| crate::backend::reactive::types::AgentRegistration {
507            agent_id: name.into(),
508            block_id: format!("blk-{name}"),
509            tab_id: None,
510            uid: uid.map(str::to_string),
511            registered_at: 0,
512            last_seen: 0,
513            registration_nonce: 0,
514        };
515        let agents = [reg("Loap", Some("uid-w")), reg("Camper", Some("uid-l")), reg("shell", None)];
516        let body = agent_names_body(&store, &Default::default(), &agents, |_| None);
517        assert_eq!(
518            body["agent_seats"],
519            serde_json::json!({ "Loap": { "role": "worker", "qualifier": null, "lead": { "id": "uid-l", "name": "Camper" }, "area": "panes" } })
520        );
521        // And it reads back as it was sent.
522        let peer = parse_agent_names_body(&body);
523        assert_eq!(peer.seats["loap"].lead.as_ref().map(|l| l.id.as_str()), Some("uid-l"));
524    }
525
526    #[test]
527    fn a_body_from_before_agent_status_gives_names_only() {
528        let peer = parse_agent_names_body(&serde_json::json!({"agents": ["Manoz"]}));
529        assert_eq!(peer.names, ["Manoz"]);
530        assert!(peer.status.is_empty());
531        let peer = parse_agent_names_body(
532            &serde_json::json!({"agents": ["Manoz"], "agent_status": "bogus"}),
533        );
534        assert!(peer.status.is_empty());
535    }
536
537    /// The `laninstances` event carries the state to the frontend, and a record
538    /// from before the field reads as none.
539    #[test]
540    fn lan_instance_agent_status_round_trips_and_defaults_to_empty() {
541        let mut inst = instance();
542        inst.agent_status.insert("manoz".into(), AgentState::Idle);
543        let json = serde_json::to_value(&inst).unwrap();
544        assert_eq!(json["agent_status"], serde_json::json!({"manoz": "idle"}));
545        let mut old = json.clone();
546        old.as_object_mut().unwrap().remove("agent_status");
547        let back: LanInstance = serde_json::from_value(old).unwrap();
548        assert!(back.agent_status.is_empty());
549    }
550
551    /// The same JSON goes to the frontend, `/api/lan-instances` and
552    /// `/agentmux/discovery` (which container agents may call); a peer's
553    /// `lan_key` is in none of them.
554    #[test]
555    fn lan_instance_json_never_carries_the_peer_key() {
556        let json = serde_json::to_value(instance()).unwrap();
557        assert!(json.get("auth_key").is_none(), "{json}");
558        let back: LanInstance = serde_json::from_value(json).unwrap();
559        assert!(back.auth_key.is_empty());
560    }
561
562    #[test]
563    fn a_poll_that_answers_replaces_names_and_states() {
564        let mut inst = instance();
565        let peer = parse_agent_names_body(&serde_json::json!({
566            "agents": ["Manoz", "Opaz"],
567            "agent_status": {"Manoz": {"state": "working", "since_ms": 1}},
568        }));
569        assert!(apply_agent_names_poll(&mut inst, Some(peer.clone()), 77));
570        assert_eq!(inst.agents, ["Manoz", "Opaz"]);
571        assert_eq!(inst.agent_status.get("manoz"), Some(&AgentState::Working));
572        assert_eq!(inst.last_polled_ok, 77);
573        // The same answer again changes nothing the frontend shows.
574        assert!(!apply_agent_names_poll(&mut inst, Some(peer), 78));
575        // A new line alone is a change too.
576        let peer = parse_agent_names_body(&serde_json::json!({
577            "agents": ["Manoz", "Opaz"],
578            "agent_status": {"Manoz": {"state": "working", "since_ms": 1}},
579            "agent_lines": {"Manoz": "Fixing the login race"},
580        }));
581        assert!(apply_agent_names_poll(&mut inst, Some(peer), 79));
582        assert_eq!(inst.agent_lines.get("manoz").map(String::as_str), Some("Fixing the login race"));
583    }
584
585    /// A peer still advertising over mDNS but no longer answering polls must
586    /// not keep showing its last state (#4703).
587    #[test]
588    fn a_failed_poll_keeps_the_names_and_clears_the_states() {
589        let mut inst = instance();
590        inst.agent_status
591            .insert("manoz".into(), AgentState::Working);
592        inst.agent_lines.insert("manoz".into(), "Fixing the login race".into());
593        inst.last_polled_ok = 5;
594        assert!(apply_agent_names_poll(&mut inst, None, 99));
595        assert_eq!(inst.agents, ["Manoz"]);
596        assert!(inst.agent_status.is_empty());
597        assert!(inst.agent_lines.is_empty());
598        assert_eq!(
599            inst.last_polled_ok, 5,
600            "a failed poll is not a successful one"
601        );
602        // Failing again, with nothing left to clear, changes nothing.
603        assert!(!apply_agent_names_poll(&mut inst, None, 100));
604    }
605
606    fn instance() -> LanInstance {
607        LanInstance {
608            instance_id: "area54-29700".into(),
609            hostname: "Area54".into(),
610            version: "0".into(),
611            channel: "stable".into(),
612            os: String::new(),
613            install: String::new(),
614            build: String::new(),
615            address: "10.0.0.26".into(),
616            port: 29700,
617            auth_key: "k".into(),
618            agents: vec!["Manoz".into()],
619            agent_status: Default::default(),
620            agent_lines: Default::default(),
621            agent_providers: Default::default(),
622            agent_kinds: Default::default(),
623            agent_accounts: Default::default(),
624            agent_resets: Default::default(),
625            agent_seats: Default::default(),
626            first_seen: 0,
627            last_seen: 0,
628            last_polled_ok: 0,
629            install_id: String::new(),
630            other_ttl_secs: 4500,
631        }
632    }
633}