Skip to main content

agentmux_srv_core/muxbus/delivery_status/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Whether cloud (MuxBus) messages are reaching this channel's agents, made
5//! visible: a sign-in that stops working, or a relay that can't be reached,
6//! used to leave nothing but a log line while agents silently stopped getting
7//! review, CI and cross-machine messages.
8//!
9//! **State** (`muxbus.status`'s `delivery`, and the `muxbus:status` event on
10//! every change) is derived in [`machine::derive`] from two things only: what
11//! the cloud subscriber's loop last reported ([`set_link`], [`saw_session`])
12//! and the credential broker's state for the sign-in. It never reads the
13//! credential store itself.
14//!
15//! **What follows from it** ([`machine::Effect`]):
16//! - one OS notification when a needs-sign-in episode starts (the notify
17//!   Router's `CloudSignedOut` kind), taken down when it ends;
18//! - after [`machine::PAUSE_NOTICE_MS`] paused, one AgentMux system note for
19//!   every agent subscribed to the cloud, and one more when delivery resumes,
20//!   with what was delivered and what expired meanwhile ([`notes`]). Each
21//!   waits for the agent's next turn and never starts one
22//!   (`reactive::held_notes`); a pause that ends before that turn is one
23//!   note. The notes come from srv itself, never through the relay; see
24//!   [`notes::NOTE_MARKER`] for why one can't be forged.
25
26pub mod machine;
27pub mod notes;
28
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Arc, Mutex, OnceLock};
31use std::time::Duration;
32
33use agentmux_common::time::now_ms;
34pub use machine::Link;
35use machine::{Effect, Machine};
36use notes::{ExpiredItem, Note, NoteBook, NoteKind, RetryQueue, OUTAGE_KEY, PAUSED_KEY, RESUMED_KEY};
37
38use crate::backend::eventbus::EventBus;
39use crate::backend::mps::Broker;
40use crate::backend::rpc_types::MuxBusDeliveryStatus;
41use crate::broker::CredentialState;
42
43/// The WebSocket event carrying a changed [`MuxBusDeliveryStatus`].
44pub const EVENT_MUXBUS_STATUS: &str = "muxbus:status";
45
46/// How often the state is re-derived (the broker can move on its own) and
47/// the time-based notes are checked.
48const TICK: Duration = Duration::from_secs(15);
49
50struct Sinks {
51    event_bus: Arc<EventBus>,
52    broker: Arc<Broker>,
53}
54
55struct Runtime {
56    machine: Mutex<Machine>,
57    book: Mutex<NoteBook>,
58    retry: Mutex<RetryQueue>,
59    sinks: OnceLock<Sinks>,
60}
61
62static RUNTIME: OnceLock<Runtime> = OnceLock::new();
63
64fn rt() -> &'static Runtime {
65    RUNTIME.get_or_init(|| Runtime {
66        machine: Mutex::new(Machine::new(now_ms())),
67        book: Mutex::new(NoteBook::default()),
68        retry: Mutex::new(RetryQueue::default()),
69        sinks: OnceLock::new(),
70    })
71}
72
73fn broker_state() -> Option<CredentialState> {
74    crate::broker::get_global().and_then(|s| s.state(crate::muxbus::CREDENTIAL_ID))
75}
76
77fn subscribed_agents() -> Vec<String> {
78    crate::muxbus::cloud_subscriber::get_global_subscriber()
79        .map(|s| s.subscribed_agents())
80        .unwrap_or_default()
81}
82
83/// Where status changes and the notification go. Call once at startup;
84/// starts the tick. Before this, state is still tracked but nothing is sent.
85pub fn install(event_bus: Arc<EventBus>, broker: Arc<Broker>) {
86    if rt().sinks.set(Sinks { event_bus, broker }).is_err() {
87        return;
88    }
89    if tokio::runtime::Handle::try_current().is_err() {
90        return;
91    }
92    tokio::spawn(async {
93        let mut tick = tokio::time::interval(TICK);
94        tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
95        loop {
96            tick.tick().await;
97            run_tick();
98        }
99    });
100}
101
102fn run_tick() {
103    let broker = broker_state();
104    let now = now_ms();
105    let agents = subscribed_agents();
106    let effects = {
107        let mut machine = rt().machine.lock().unwrap_or_else(|e| e.into_inner());
108        machine.keep_pull_errors_of(&agents);
109        machine.tick(broker.as_ref(), now)
110    };
111    apply(effects);
112    send_owed_sign_in_notice();
113    let retries = rt().retry.lock().unwrap_or_else(|e| e.into_inner()).take();
114    for (note, attempts) in retries {
115        hold_one(note, attempts + 1);
116    }
117    let notes = {
118        let mut book = rt().book.lock().unwrap_or_else(|e| e.into_inner());
119        let mut notes = book.pause_late_joiners(&agents);
120        notes.extend(book.tick(now));
121        notes
122    };
123    hold(notes);
124}
125
126/// The current state, for `muxbus.status`.
127pub fn status() -> MuxBusDeliveryStatus {
128    rt().machine.lock().unwrap_or_else(|e| e.into_inner()).status().clone()
129}
130
131/// The subscriber found a stored sign-in, or a sign-in just succeeded.
132pub fn saw_session(email: Option<String>) {
133    let broker = broker_state();
134    let effects = rt().machine.lock().unwrap_or_else(|e| e.into_inner()).saw_session(email, broker.as_ref(), now_ms());
135    apply(effects);
136}
137
138/// The user just signed in (`muxbus.login`).
139pub fn fresh_sign_in(email: Option<String>) {
140    let effects = rt().machine.lock().unwrap_or_else(|e| e.into_inner()).fresh_sign_in(email, now_ms());
141    apply(effects);
142}
143
144/// The user signed out (`muxbus.disconnect`).
145pub fn signed_out() {
146    let effects = rt().machine.lock().unwrap_or_else(|e| e.into_inner()).signed_out(now_ms());
147    apply(effects);
148}
149
150/// What the subscriber's loop is doing now.
151pub fn set_link(link: Link) {
152    let broker = broker_state();
153    let effects = rt().machine.lock().unwrap_or_else(|e| e.into_inner()).set_link(link, broker.as_ref(), now_ms());
154    apply(effects);
155}
156
157/// One agent's pull answered: `delivered` messages reached it and the relay
158/// reported `expired`. Holds its resume or expiry note, if it has one; call
159/// after the pull's own messages are delivered, so the note comes last.
160pub fn fetched(agent: &str, delivered: usize, expired: &[ExpiredItem]) {
161    if !expired.is_empty() {
162        tracing::info!(agent, delivered, expired = expired.len(), "muxbus: the relay reports messages that expired undelivered for this agent");
163    }
164    crate::connectivity::report(crate::connectivity::Service::Muxbus, crate::connectivity::Outcome::Answered);
165    let broker = broker_state();
166    let effects = rt().machine.lock().unwrap_or_else(|e| e.into_inner()).relay_answered(agent, broker.as_ref(), now_ms());
167    apply(effects);
168    let note = rt().book.lock().unwrap_or_else(|e| e.into_inner()).fetched(agent, delivered, expired);
169    hold(note.into_iter().collect());
170}
171
172/// A relay message for `agent` was left at the relay, because the agent can't work now (out of quota, signed
173/// out). Remembered, so it is told once when it can.
174pub fn left_at_relay(agent: &str) {
175    rt().book.lock().unwrap_or_else(|e| e.into_inner()).left_at_relay(agent, now_ms());
176}
177
178/// Whether relay messages for `agent` were left at the relay and it has not been told.
179pub fn has_left_at_relay(agent: &str) -> bool {
180    rt().book.lock().unwrap_or_else(|e| e.into_inner()).has_left_at_relay(agent)
181}
182
183/// `agent` can work: holds its one note about relay messages left at the relay, if any were. Call after its
184/// pull's own messages are delivered, so the note comes last.
185pub fn can_work_again(agent: &str) {
186    let note = rt().book.lock().unwrap_or_else(|e| e.into_inner()).can_work_again(agent);
187    hold(note.into_iter().collect());
188}
189
190/// `agent`'s pull (fetch or claim) got no usable answer from the relay,
191/// though the WebSocket may be open: its messages aren't arriving.
192pub fn pull_failed(agent: &str, reason: impl Into<String>) {
193    let broker = broker_state();
194    let effects =
195        rt().machine.lock().unwrap_or_else(|e| e.into_inner()).pull_failed(agent, reason.into(), broker.as_ref(), now_ms());
196    apply(effects);
197}
198
199/// The episode's notification is owed but had no router to go to (no window
200/// had connected yet); [`run_tick`] sends it once one exists.
201static SIGN_IN_NOTICE_OWED: AtomicBool = AtomicBool::new(false);
202
203fn send_owed_sign_in_notice() {
204    if SIGN_IN_NOTICE_OWED.load(Ordering::SeqCst) {
205        if let Some(router) = router() {
206            if SIGN_IN_NOTICE_OWED.swap(false, Ordering::SeqCst) {
207                router.cloud_signed_out();
208            }
209        }
210    }
211}
212
213fn apply(effects: Vec<Effect>) {
214    for effect in effects {
215        match effect {
216            Effect::Changed(status) => {
217                tracing::info!(
218                    state = ?status.state,
219                    error = status.last_error.as_deref().unwrap_or(""),
220                    "muxbus delivery: state changed"
221                );
222                if let Some(sinks) = rt().sinks.get() {
223                    sinks.event_bus.broadcast_event(&crate::backend::eventbus::EventBus::typed_ws_event::<crate::backend::mps_events::MuxbusStatus>(&status, String::new()));
224                }
225            }
226            Effect::NotifySignInNeeded => {
227                SIGN_IN_NOTICE_OWED.store(true, Ordering::SeqCst);
228                send_owed_sign_in_notice();
229            }
230            Effect::RetractSignInNeeded => {
231                SIGN_IN_NOTICE_OWED.store(false, Ordering::SeqCst);
232                if let Some(router) = router() {
233                    router.resolve("", crate::backend::notify::policy::Family::Cloud);
234                }
235            }
236            Effect::PauseNote { since_ms, reason } => {
237                tracing::warn!(reason, "muxbus delivery: paused for two minutes, a note waits for each agent's next turn");
238                let notes = rt().book.lock().unwrap_or_else(|e| e.into_inner()).pause(since_ms, reason, &subscribed_agents());
239                hold(notes);
240            }
241            Effect::Resumed { at_ms } => {
242                rt().retry.lock().unwrap_or_else(|e| e.into_inner()).drop_pause_notes();
243                // Asked before the book is locked: the handler takes its own lock.
244                let told = rt().book.lock().unwrap_or_else(|e| e.into_inner()).told_paused();
245                let handler = crate::backend::reactive::handler::get_global_handler();
246                let waiting: std::collections::HashSet<(String, &str)> = told
247                    .iter()
248                    .flat_map(|agent| [PAUSED_KEY, OUTAGE_KEY].map(|key| (agent.clone(), key)))
249                    .filter(|(agent, key)| handler.holds_system_note(agent, key))
250                    .collect();
251                let notes = rt()
252                    .book
253                    .lock()
254                    .unwrap_or_else(|e| e.into_inner())
255                    .resumed(at_ms, |agent, key| waiting.contains(&(agent.to_string(), key)));
256                hold(notes);
257            }
258        }
259    }
260}
261
262fn router() -> Option<Arc<crate::backend::notify::router::Router>> {
263    let sinks = rt().sinks.get()?;
264    let router = crate::backend::notify::router::get(&sinks.broker);
265    if router.is_none() {
266        tracing::debug!("muxbus delivery: no notification router yet (no window connected)");
267    }
268    router
269}
270
271fn hold(notes: Vec<Note>) {
272    for note in notes {
273        hold_one(note, 1);
274    }
275}
276
277/// Hold `note` for its agent's next turn (its `attempt`-th try); a failure is
278/// retried on later ticks. An outage note takes the place of the agent's
279/// waiting pause note, or, if that went with a turn meanwhile, its `seen` note
280/// is held instead.
281fn hold_one(note: Note, attempt: u32) {
282    let handler = crate::backend::reactive::handler::get_global_handler();
283    let held = match &note.kind {
284        NoteKind::Outage { seen } => handler
285            .replace_held_system_note(&note.agent, PAUSED_KEY, OUTAGE_KEY, &note.text)
286            .and_then(|replaced| if replaced { Ok(()) } else { handler.hold_system_note(&note.agent, RESUMED_KEY, seen) }),
287        _ => handler.hold_system_note(&note.agent, &note.key(), &note.text),
288    };
289    if let Err(e) = held {
290        let agent = note.agent.clone();
291        if rt().retry.lock().unwrap_or_else(|e| e.into_inner()).failed(note, attempt) {
292            tracing::info!(agent = %agent, attempt, error = %e, "muxbus delivery: system note not held, will retry");
293        } else {
294            tracing::warn!(agent = %agent, error = %e, "muxbus delivery: system note not held, giving up");
295        }
296    }
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302    use crate::backend::reactive::held_notes;
303
304    fn note(agent: &str, text: &str, kind: NoteKind) -> Note {
305        Note { agent: agent.to_string(), text: text.to_string(), kind }
306    }
307
308    /// The notes are held, never sent: the global handler here has no sender
309    /// at all, so any attempt to send one would fail and be queued for retry.
310    #[test]
311    fn a_pause_note_waits_for_the_next_turn_and_its_end_replaces_it() {
312        let handler = crate::backend::reactive::handler::get_global_handler();
313        let (agent, block) = ("delivery-status-test-a", "delivery-status-test-block-a");
314        handler.register_agent(agent, block, None).unwrap();
315        hold(vec![note(agent, "[AgentMux] paused", NoteKind::Paused)]);
316        assert!(handler.holds_system_note(agent, PAUSED_KEY));
317        hold(vec![note(agent, "[AgentMux] were paused", NoteKind::Outage { seen: "[AgentMux] resumed".into() })]);
318        assert!(!handler.holds_system_note(agent, PAUSED_KEY));
319        let (message, notes) = held_notes::attach(block, "hi");
320        notes.delivered();
321        assert_eq!(message, "hi\n\n[AgentMux] were paused", "one note, not two");
322        assert!(rt().retry.lock().unwrap().take().iter().all(|(n, _)| n.agent != agent), "nothing failed");
323        handler.unregister_block(block);
324    }
325
326    #[test]
327    fn an_agent_that_saw_the_pause_gets_the_plain_resume_note() {
328        let handler = crate::backend::reactive::handler::get_global_handler();
329        let (agent, block) = ("delivery-status-test-b", "delivery-status-test-block-b");
330        handler.register_agent(agent, block, None).unwrap();
331        hold(vec![note(agent, "[AgentMux] paused", NoteKind::Paused)]);
332        let (_, notes) = held_notes::attach(block, "a turn during the pause");
333        notes.delivered();
334        hold(vec![note(agent, "[AgentMux] were paused", NoteKind::Outage { seen: "[AgentMux] resumed".into() })]);
335        let (message, notes) = held_notes::attach(block, "hi");
336        notes.delivered();
337        assert_eq!(message, "hi\n\n[AgentMux] resumed");
338        handler.unregister_block(block);
339    }
340}