Skip to main content

agentmux_srv_core/muxbus/
relay_watch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A message handed to the cloud relay is queued, not delivered: the relay keeps it for a short
5//! window and drops it if nobody picks it up, and the sender never heard. This tells the sender,
6//! with one AgentMux system note for its next turn, when a message it queued is still unconfirmed
7//! after that window, naming the target and the message id, so it can ask again or reach the
8//! target another way instead of waiting on a message that went nowhere.
9//!
10//! Nothing here learns whether a message was picked up: the one thing srv can see is the target
11//! writing to the sender, which shows the target is reachable and so cancels the note. Every other
12//! queued message is reported as unconfirmed, in those words, never as lost.
13
14use std::collections::VecDeque;
15use std::sync::Mutex;
16use std::time::Duration;
17
18use serde_json::{json, Value};
19
20use crate::backend::reactive::handler::ReactiveHandler;
21use crate::backend::reactive::types::InjectionResponse;
22use crate::muxbus::delivery_status::notes::NOTE_MARKER;
23
24/// How long the relay keeps a message nobody picked up; what the send answer tells the sender.
25pub const RELAY_HOLD_MS: u64 = 30 * 60 * 1000;
26
27/// Waited past the window before the note, so a message picked up at the last moment and a reply
28/// to it are not reported as unconfirmed.
29const SLACK_MS: u64 = 60 * 1000;
30
31/// The most queued messages watched at once; past it the oldest is dropped from the book.
32const MAX_WATCHED: usize = 256;
33
34#[derive(Debug, Clone, PartialEq, Eq)]
35struct Watched {
36    id: String,
37    /// The agent that sent it, and gets the note.
38    from: String,
39    /// The agent it was addressed to.
40    to: String,
41    queued_ms: u64,
42}
43
44#[derive(Debug, Default)]
45struct Book {
46    entries: VecDeque<Watched>,
47}
48
49impl Book {
50    fn add(&mut self, w: Watched) {
51        if self.entries.len() >= MAX_WATCHED {
52            self.entries.pop_front();
53        }
54        self.entries.push_back(w);
55    }
56
57    /// The target wrote to the sender: it is reachable, so nothing it was sent is reported.
58    fn heard_from(&mut self, sender: &str, receiver: &str) -> usize {
59        let before = self.entries.len();
60        self.entries.retain(|w| !(w.to.eq_ignore_ascii_case(sender) && w.from.eq_ignore_ascii_case(receiver)));
61        before - self.entries.len()
62    }
63
64    fn take(&mut self, id: &str) -> Option<Watched> {
65        let i = self.entries.iter().position(|w| w.id == id)?;
66        self.entries.remove(i)
67    }
68}
69
70static BOOK: Mutex<Book> = Mutex::new(Book { entries: VecDeque::new() });
71
72fn book() -> std::sync::MutexGuard<'static, Book> {
73    BOOK.lock().unwrap_or_else(|e| e.into_inner())
74}
75
76/// The note for a message still unconfirmed after the relay's window.
77fn unconfirmed_note(w: &Watched) -> String {
78    format!(
79        "{NOTE_MARKER} Your message {id} to {to} went to the cloud relay {mins} minutes ago and was never confirmed \
80         delivered. The relay drops a message nobody has picked up after {mins} minutes, and {to} has not written to \
81         you since, so treat it as not received: send it again once {to} is running, or reach {to} another way \
82         (Agents list shows who is running).",
83        id = w.id,
84        to = w.to,
85        mins = RELAY_HOLD_MS / 60_000,
86    )
87}
88
89/// Watch a message just queued at the relay for `to` by `from`: once the window has passed with no
90/// word from `to`, `from` gets the note at its next turn.
91pub fn watch(handler: &'static ReactiveHandler, from: &str, to: &str, id: &str) {
92    if from.is_empty() || to.is_empty() || id.is_empty() {
93        return;
94    }
95    let w = Watched { id: id.to_string(), from: from.to_string(), to: to.to_string(), queued_ms: agentmux_common::time::now_ms_u64() };
96    book().add(w.clone());
97    tokio::spawn(async move {
98        tokio::time::sleep(Duration::from_millis(RELAY_HOLD_MS + SLACK_MS)).await;
99        let Some(due) = book().take(&w.id) else { return };
100        if let Err(e) = handler.hold_system_note(&due.from, &format!("relay-unconfirmed:{}", due.id), &unconfirmed_note(&due)) {
101            tracing::debug!(error = %e, id = %due.id, queued_ms = due.queued_ms, "relay unconfirmed note not held");
102        }
103    });
104}
105
106/// A message from `sender` to `receiver` arrived: if `receiver` had queued one for `sender`, `sender`
107/// is reachable and that one is no longer watched.
108pub fn heard_from(sender: Option<&str>, receiver: &str) {
109    if let Some(sender) = sender.filter(|s| !s.is_empty()) {
110        book().heard_from(sender, receiver);
111    }
112}
113
114/// The answer to a send that the relay queued: the usual response, plus what srv knows that the
115/// sender can act on at once. `target_in_account` is the relay's word on whether the name is one of
116/// the sender's own account's agents; `lan_peers` are the LAN peers this machine can see, in words
117/// (`peer_words::describe_peer`), because the message got this far only because the target is not
118/// running here or on any of them.
119pub fn queued_answer(request_id: String, target_in_account: Option<bool>, lan_peers: Vec<String>, timestamp: u64) -> Value {
120    let body = InjectionResponse {
121        deferred: None,
122        success: true,
123        request_id,
124        block_id: None,
125        error: None,
126        timestamp,
127        // No receiver has seen the message yet, so there is no applied
128        // tier or STOP decision to report — deliberately left unset
129        // rather than guessed at.
130        effective_tier: None,
131        requires_stop: None,
132        channel_verified: None,
133    };
134    let mut body = serde_json::to_value(&body).unwrap_or_default();
135    if let Some(obj) = body.as_object_mut() {
136        // Passed through for the `Message` tool, which warns of a likely typo
137        // on `false` (PLAN_JEKT_LOCAL_FIRST_ROUTING_2026_10_02.md R-3).
138        if let Some(in_account) = target_in_account {
139            obj.insert("target_in_account".to_string(), Value::Bool(in_account));
140        }
141        obj.insert("lan_peers".to_string(), json!(lan_peers));
142    }
143    body
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    fn w(id: &str, from: &str, to: &str) -> Watched {
151        Watched { id: id.into(), from: from.into(), to: to.into(), queued_ms: 1 }
152    }
153
154    #[test]
155    fn a_reply_from_the_target_stops_the_note_and_nothing_else_does() {
156        let mut b = Book::default();
157        b.add(w("inj-1", "agent2-5", "lazo"));
158        b.add(w("inj-2", "agent2-5", "posa"));
159        // Someone else writing to the sender, or the sender writing, says nothing about the target.
160        assert_eq!(b.heard_from("manoz", "agent2-5"), 0);
161        assert_eq!(b.heard_from("agent2-5", "lazo"), 0);
162        // The target writing back, in any case, drops only what was queued for it.
163        assert_eq!(b.heard_from("Lazo", "AGENT2-5"), 1);
164        assert!(b.take("inj-1").is_none());
165        assert_eq!(b.take("inj-2").map(|x| x.to), Some("posa".to_string()));
166        assert!(b.take("inj-2").is_none(), "a message is reported once");
167    }
168
169    #[test]
170    fn the_book_is_bounded_and_forgets_the_oldest() {
171        let mut b = Book::default();
172        for i in 0..(MAX_WATCHED + 5) {
173            b.add(w(&format!("inj-{i}"), "a", "b"));
174        }
175        assert_eq!(b.entries.len(), MAX_WATCHED);
176        assert!(b.take("inj-0").is_none());
177        assert!(b.take(&format!("inj-{}", MAX_WATCHED + 4)).is_some());
178    }
179
180    #[test]
181    fn the_note_names_the_target_and_the_message_and_never_says_lost() {
182        let note = unconfirmed_note(&w("inj-w-ab84", "agent2-5", "lazo"));
183        assert!(note.starts_with(NOTE_MARKER), "{note}");
184        assert!(note.contains("inj-w-ab84") && note.contains("lazo") && note.contains("30 minutes"), "{note}");
185        assert!(note.contains("never confirmed delivered"), "{note}");
186    }
187
188    #[test]
189    fn the_window_is_what_the_send_answer_promises() {
190        assert_eq!(RELAY_HOLD_MS, 30 * 60 * 1000);
191    }
192
193    #[test]
194    fn the_queued_answer_carries_the_hint_fields() {
195        let v = queued_answer("inj-w-1".into(), Some(false), vec!["Area54/stable (Microsoft Store, no agents)".into()], 7);
196        assert_eq!(v["success"], true);
197        assert_eq!(v["request_id"], "inj-w-1");
198        assert_eq!(v["target_in_account"], false);
199        assert_eq!(v["lan_peers"][0], "Area54/stable (Microsoft Store, no agents)");
200        // An older relay that doesn't say leaves the field out; the peers list is always there.
201        let v = queued_answer("inj-w-2".into(), None, vec![], 7);
202        assert!(v.get("target_in_account").is_none());
203        assert_eq!(v["lan_peers"], json!([]));
204    }
205}