Skip to main content

agentmux_srv/server/reactive/
registration_flags.rs

1//! `reactive.registration_flags`: which registered agents have a registration problem, for the
2//! Swarm's row badge. Shares its two lookups with `reactive.registrations`.
3
4use super::{is_self_registration, AppState, MismatchAuditSummary, RemoteRegistrationEntry};
5use crate::backend::reactive::registry as agent_registry;
6
7/// Every OTHER live instance/channel on this host claiming `agent_id`, freshest first.
8///
9/// Every agent (this instance's own included) writes itself into the same host-global shared
10/// registry, so this instance's own entry is filtered out or the "registered elsewhere too" badge
11/// would fire on every healthy agent. A crashed sibling's entry lingers until the next
12/// startup-only `cleanup_stale_shared` sweep, so the pid is checked live here (same-host by
13/// construction, per `pid_alive`).
14fn remote_claims(state: &AppState, agent_id: &str) -> Vec<RemoteRegistrationEntry> {
15    crate::registry::resolve_shared_reactive_dir()
16        .map(|shared_dir| {
17            agent_registry::lookup_all_shared(&shared_dir, agent_id)
18                .into_iter()
19                .filter(|e| !is_self_registration(&e.local_url, &state.local_web_url))
20                .filter(|e| agent_registry::pid_alive(e.pid))
21                .map(|e| RemoteRegistrationEntry {
22                    channel: e.channel,
23                    pid: e.pid,
24                    updated_at: e.updated_at,
25                })
26                .collect::<Vec<_>>()
27        })
28        .unwrap_or_default()
29}
30
31/// The newest refusal by the recipient identity guard in `audit` (newest first). A refusal is
32/// logged with the block the message resolved to, but under the address it used (uid, alias or
33/// name), so with a `block_id` it matches on the block alone: a name reused by a newer block must
34/// not inherit the old block's refusal. Without one it falls back to the name.
35pub(super) fn recent_mismatch_for(
36    audit: &[crate::backend::reactive::AuditLogEntry],
37    agent_id: &str,
38    block_id: Option<&str>,
39) -> Option<MismatchAuditSummary> {
40    let target_lower = agent_id.to_lowercase();
41    audit
42        .iter()
43        .find(|e| {
44            e.outcome.as_deref() == Some("identity-mismatch")
45                && match block_id {
46                    Some(b) => e.block_id == b,
47                    None => e.target_agent.to_lowercase() == target_lower,
48                }
49        })
50        .map(|e| MismatchAuditSummary {
51            timestamp: e.timestamp,
52            block_id: e.block_id.clone(),
53            error_message: e.error_message.clone(),
54        })
55}
56
57/// One registered agent that has a registration problem: another instance claims its id, or a
58/// message to it was recently refused by the identity guard.
59#[derive(serde::Serialize, serde::Deserialize, ts_rs::TS)]
60#[ts(export, export_to = "../../../frontend/types/rpc/")]
61pub(super) struct RegistrationFlag {
62    agent_id: String,
63    block_id: String,
64    remote: Vec<RemoteRegistrationEntry>,
65    recent_mismatch: Option<MismatchAuditSummary>,
66}
67
68/// `reactive.registration_flags`: the agents with a registration problem, for the Swarm's row badge.
69/// A healthy agent is not listed, so one call every few seconds covers every row.
70#[derive(serde::Serialize, serde::Deserialize, ts_rs::TS)]
71#[ts(export, export_to = "../../../frontend/types/rpc/")]
72pub(super) struct ReactiveRegistrationFlagsResult {
73    flags: Vec<RegistrationFlag>,
74}
75
76#[derive(serde::Serialize, serde::Deserialize, ts_rs::TS)]
77#[ts(export, export_to = "../../../frontend/types/rpc/")]
78pub(super) struct ReactiveRegistrationFlagsParams {}
79
80fn flags(state: &AppState) -> ReactiveRegistrationFlagsResult {
81    let audit = state.reactive_handler.get_audit_log(100);
82    let flags = state
83        .reactive_handler
84        .list_agents()
85        .into_iter()
86        .filter_map(|a| {
87            let remote = remote_claims(state, &a.agent_id);
88            let recent_mismatch = recent_mismatch_for(&audit, &a.agent_id, Some(&a.block_id));
89            (!remote.is_empty() || recent_mismatch.is_some()).then(|| RegistrationFlag {
90                agent_id: a.agent_id,
91                block_id: a.block_id,
92                remote,
93                recent_mismatch,
94            })
95        })
96        .collect();
97    ReactiveRegistrationFlagsResult { flags }
98}
99
100pub(super) fn register(
101    engine: &std::sync::Arc<crate::backend::rpc::engine::WshRpcEngine>,
102    state: AppState,
103) {
104    engine.register_typed(
105        "reactive.registration_flags",
106        move |_: ReactiveRegistrationFlagsParams, _ctx| {
107            let state = state.clone();
108            async move { Ok(flags(&state)) }
109        },
110    );
111}
112
113/// The other instances claiming `agent_id` and its newest identity refusal, for the registration
114/// tab of one agent. `local` is the registration this instance holds for it, if any.
115pub(super) fn problems_of(
116    state: &AppState,
117    local: &Option<crate::backend::reactive::AgentRegistration>,
118    agent_id: &str,
119) -> (Vec<RemoteRegistrationEntry>, Option<MismatchAuditSummary>) {
120    let audit = state.reactive_handler.get_audit_log(100);
121    let block_id = local.as_ref().map(|l| l.block_id.as_str());
122    (
123        remote_claims(state, agent_id),
124        recent_mismatch_for(&audit, agent_id, block_id),
125    )
126}