Skip to main content

agentmux_srv/server/
person_hold.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The person's words to an agent that is out of quota.
5//!
6//! A Swarm broadcast to an agent marked `limited` used to be refused ("not sent") and nothing
7//! looked at whether the limit was still real; a quota refilled before the provider's reset left the
8//! agent limited for days. Now the words are kept, a check turn starts on the agent at once
9//! (`limit_probe::check_now`, no wait for the 15-minute slot a message between agents has), and the
10//! broadcast's answer waits [`CHECK_WAIT_MS`] for the result: delivered when the check cleared the
11//! limit, otherwise "held", with the reason. Kept words are sent as soon as the agent can work,
12//! whoever cleared it (the check, a clean turn of another agent on its account, the reset), and
13//! for at most [`KEEP_MS`]. The words never ride the check turn: a check that fails leaves the agent
14//! limited and the words kept.
15
16use std::collections::HashMap;
17use std::future::Future;
18use std::sync::{LazyLock, Mutex};
19use std::time::Duration;
20
21use tokio::sync::oneshot;
22
23use crate::backend::message_origin::MessageOrigin;
24use crate::backend::agent_state::{AgentState, Unavailable};
25use crate::server::agent_handlers::AgentTurnDeps;
26
27/// An answer that starts with this is "kept, not sent yet", not a failure.
28pub(crate) const HELD_PREFIX: &str = "held: ";
29/// How long a broadcast's answer waits for the check.
30const CHECK_WAIT_MS: u64 = 30_000;
31/// How often the watcher looks while the check is fresh, then after [`FAST_FOR_MS`].
32const POLL_FAST_MS: u64 = 1_000;
33const POLL_SLOW_MS: u64 = 5_000;
34const FAST_FOR_MS: u64 = 60_000;
35/// How long words are kept for an agent that stays out of quota (the held-message hold's 24 hours).
36const KEEP_MS: u64 = 24 * 60 * 60 * 1000;
37/// The most messages kept for one agent.
38const MAX_KEPT: usize = 20;
39
40struct Words {
41    text: String,
42    from: MessageOrigin,
43    kept_at_ms: u64,
44    /// Where the answer to the sender goes: delivered, or why it wasn't. Dropped when the sender stopped waiting.
45    answer: oneshot::Sender<Result<(), String>>,
46}
47
48/// The words kept per pane, oldest first.
49static KEPT: LazyLock<Mutex<HashMap<String, Vec<Words>>>> = LazyLock::new(Default::default);
50
51/// The reason in a broadcast answer that means "kept, not sent yet" ([`HELD_PREFIX`]); `None` for a failure.
52pub(crate) fn held_note(error: &str) -> Option<&str> {
53    error.strip_prefix(HELD_PREFIX)
54}
55
56/// Whether a message to an agent in this state is kept and checked, rather than refused: a plan's
57/// limit (not a route out of credits, and not a sign-in: neither ends by itself being asked).
58pub(crate) fn is_kept_for_check(unavailable: &Unavailable) -> bool {
59    unavailable.state == AgentState::Limited && unavailable.title != crate::agents::failure::ROUTE_CREDITS_TITLE
60}
61
62/// Keeps `words` for `block_id`; `true` when it is the first (the caller starts the watcher). `Err` when
63/// the agent already has [`MAX_KEPT`].
64fn keep(block_id: &str, words: Words) -> Result<bool, String> {
65    let mut kept = KEPT.lock().unwrap_or_else(|e| e.into_inner());
66    let list = kept.entry(block_id.to_string()).or_default();
67    if list.len() >= MAX_KEPT {
68        return Err(format!("{}too many messages are already kept for this agent: not sent", crate::backend::reactive::UNAVAILABLE_PREFIX));
69    }
70    list.push(words);
71    Ok(list.len() == 1)
72}
73
74/// Takes everything kept for `block_id`.
75fn take_all(block_id: &str) -> Vec<Words> {
76    KEPT.lock().unwrap_or_else(|e| e.into_inner()).remove(block_id).unwrap_or_default()
77}
78
79/// Drops what has been kept [`KEEP_MS`], answering each sender (if still waiting) with that.
80fn expire(block_id: &str, now_ms: u64) {
81    let mut kept = KEPT.lock().unwrap_or_else(|e| e.into_inner());
82    let Some(list) = kept.get_mut(block_id) else { return };
83    let (old, fresh): (Vec<Words>, Vec<Words>) = std::mem::take(list).into_iter().partition(|w| now_ms.saturating_sub(w.kept_at_ms) >= KEEP_MS);
84    *list = fresh;
85    for w in old {
86        let _ = w.answer.send(Err(format!("{}the agent stayed out of quota for 24 hours: not sent", crate::backend::reactive::UNAVAILABLE_PREFIX)));
87    }
88}
89
90/// How many are kept for `block_id`.
91pub(crate) fn kept_count(block_id: &str) -> usize {
92    KEPT.lock().unwrap_or_else(|e| e.into_inner()).get(block_id).map_or(0, Vec::len)
93}
94
95/// A broadcast's words kept for an agent out of quota, with its check started: what the answer waits for.
96pub(crate) struct Pending {
97    answered: oneshot::Receiver<Result<(), String>>,
98    reason: String,
99    started: std::time::Instant,
100}
101
102impl Pending {
103    /// The answer, waiting up to `wait` from when the check started: `Ok` when delivered; an `Err` that
104    /// starts with [`HELD_PREFIX`] when kept and not sent yet.
105    async fn answer(self, wait: Duration) -> Result<(), String> {
106        let left = wait.saturating_sub(self.started.elapsed());
107        match tokio::time::timeout(left, self.answered).await {
108            Ok(Ok(result)) => result,
109            Ok(Err(_)) => Err(format!("{}the message was dropped before it was sent", crate::backend::reactive::UNAVAILABLE_PREFIX)),
110            Err(_) => Err(format!(
111                "{HELD_PREFIX}{}; the check has not cleared it yet. Kept, and sent when it can work (up to 24 hours)",
112                self.reason
113            )),
114        }
115    }
116}
117
118/// Keeps `text` for `block_id`, an agent out of quota, and starts its check turn.
119fn keep_and_check(deps: &AgentTurnDeps, block_id: &str, text: String, from: MessageOrigin, reason: String) -> Result<Pending, String> {
120    let (answer, answered) = oneshot::channel();
121    let now_ms = agentmux_common::time::now_ms_u64();
122    let first = keep(block_id, Words { text, from, kept_at_ms: now_ms, answer })?;
123    if first {
124        spawn_watch(deps.clone(), block_id.to_string());
125    }
126    match super::limit_probe::check_now(block_id, now_ms) {
127        super::limit_probe::Check::Started => tracing::info!(block_id = %block_id, "person hold: started a check turn for the person's message"),
128        super::limit_probe::Check::Running => {}
129        super::limit_probe::Check::NotStarted(why) => tracing::info!(block_id = %block_id, why = %why, "person hold: no check turn started; the message waits"),
130    }
131    Ok(Pending { answered, reason, started: std::time::Instant::now() })
132}
133
134/// An answer that starts with this stands for a [`Pending`] to be waited for ([`resolve_pending`]).
135const PENDING_PREFIX: &str = "pending: ";
136static PARKED: LazyLock<Mutex<HashMap<u64, Pending>>> = LazyLock::new(Default::default);
137static NEXT_TICKET: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
138
139/// One target of a Swarm broadcast: the person's words. To an agent that can work they go as a turn; to
140/// one out of quota by its plan they are kept and its check starts at once, instead of being refused
141/// (`resolve_pending` then waits for the check, for every such target together); any other agent that
142/// cannot work refuses them as before. Only this path keeps: a task start or an agent's message to a
143/// limited agent (`deliver_broadcast_turn`) still refuses, since it undoes its work on a refusal.
144pub(crate) async fn deliver_person_broadcast(deps: &AgentTurnDeps, block_id: String, text: String, from: MessageOrigin) -> Result<(), String> {
145    let (mstore, id) = (deps.mstore.clone(), block_id.clone());
146    let unavailable = tokio::task::spawn_blocking(move || super::jekt_hold::holding_unavailable(&mstore, &id)).await.ok().flatten();
147    match unavailable {
148        Some(u) if is_kept_for_check(&u) => {
149            let pending = keep_and_check(deps, &block_id, text, from, u.reason())?;
150            let ticket = NEXT_TICKET.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
151            PARKED.lock().unwrap_or_else(|e| e.into_inner()).insert(ticket, pending);
152            Err(format!("{PENDING_PREFIX}{ticket}"))
153        }
154        _ => super::app_api::fleet::deliver_broadcast_turn(deps, block_id, text, from).await,
155    }
156}
157
158/// Waits for every target parked by [`deliver_person_broadcast`] together, up to [`CHECK_WAIT_MS`] from
159/// when its check started, and puts each one's answer in its outcome.
160pub(crate) async fn resolve_pending(outcomes: Vec<super::app_api::fleet::BroadcastOutcome>) -> Vec<super::app_api::fleet::BroadcastOutcome> {
161    resolve_pending_within(outcomes, Duration::from_millis(CHECK_WAIT_MS)).await
162}
163
164async fn resolve_pending_within(outcomes: Vec<super::app_api::fleet::BroadcastOutcome>, wait: Duration) -> Vec<super::app_api::fleet::BroadcastOutcome> {
165    use futures_util::future::join_all;
166    join_all(outcomes.into_iter().map(|mut outcome| async move {
167        let ticket = outcome.result.as_ref().err().and_then(|e| e.strip_prefix(PENDING_PREFIX)).and_then(|t| t.parse::<u64>().ok());
168        if let Some(pending) = ticket.and_then(|t| PARKED.lock().unwrap_or_else(|e| e.into_inner()).remove(&t)) {
169            outcome.result = pending.answer(wait).await;
170        }
171        outcome
172    }))
173    .await
174}
175
176/// [`deliver_person_broadcast`] for one agent, waiting `wait` for its check (the test's way in).
177#[cfg(test)]
178async fn hold_and_check_within(deps: &AgentTurnDeps, block_id: String, text: String, from: MessageOrigin, reason: &str, wait: Duration) -> Result<(), String> {
179    keep_and_check(deps, &block_id, text, from, reason.to_string())?.answer(wait).await
180}
181
182/// Watches `block_id` until it can work, then sends what is kept, oldest first.
183fn spawn_watch(deps: AgentTurnDeps, block_id: String) {
184    let Ok(runtime) = tokio::runtime::Handle::try_current() else { return };
185    runtime.spawn(async move {
186        let (mstore, id) = (deps.mstore.clone(), block_id.clone());
187        let holding = move || {
188            let (mstore, id) = (mstore.clone(), id.clone());
189            async move { tokio::task::spawn_blocking(move || super::jekt_hold::holding_unavailable(&mstore, &id).is_some()).await.unwrap_or(true) }
190        };
191        let deliver = {
192            let (deps, id) = (deps.clone(), block_id.clone());
193            move |text: String, from: MessageOrigin| {
194                let (deps, id) = (deps.clone(), id.clone());
195                async move { super::app_api::fleet::deliver_available(&deps, id, text, from).await }
196            }
197        };
198        watch(&block_id, holding, deliver, Duration::from_millis(POLL_FAST_MS), Duration::from_millis(POLL_SLOW_MS), Duration::from_millis(FAST_FOR_MS)).await;
199    });
200}
201
202/// The watcher: looks every `fast` for `fast_for`, then every `slow`, and when `holding` says the agent
203/// can work, sends what is kept through `deliver` and answers each sender still waiting. Ends when
204/// nothing is kept for `block_id`.
205async fn watch<H, HF, D, DF>(block_id: &str, holding: H, deliver: D, fast: Duration, slow: Duration, fast_for: Duration)
206where
207    H: Fn() -> HF,
208    HF: Future<Output = bool>,
209    D: Fn(String, MessageOrigin) -> DF,
210    DF: Future<Output = Result<(), String>>,
211{
212    let started = std::time::Instant::now();
213    loop {
214        tokio::time::sleep(if started.elapsed() < fast_for { fast } else { slow }).await;
215        if kept_count(block_id) == 0 {
216            return;
217        }
218        expire(block_id, agentmux_common::time::now_ms_u64());
219        if holding().await {
220            continue;
221        }
222        for words in take_all(block_id) {
223            let result = deliver(words.text, words.from).await;
224            if let Err(e) = &result {
225                tracing::info!(block_id = %block_id, error = %e, "person hold: the kept message was not delivered");
226            }
227            let _ = words.answer.send(result);
228        }
229        if kept_count(block_id) == 0 {
230            return;
231        }
232    }
233}
234
235#[cfg(test)]
236mod tests {
237    use super::*;
238    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
239    use std::sync::Arc;
240
241    fn words(text: &str, kept_at_ms: u64) -> (Words, oneshot::Receiver<Result<(), String>>) {
242        let (answer, rx) = oneshot::channel();
243        (Words { text: text.into(), from: MessageOrigin::broadcast(), kept_at_ms, answer }, rx)
244    }
245
246    fn limited(title: &str, state: AgentState) -> Unavailable {
247        Unavailable { state, code: crate::agents::failure::FailureClass::UsageLimit, title: title.into(), resets_at_ms: Some(5), since_ms: 0, account_id: None }
248    }
249
250    #[test]
251    fn only_a_plans_limit_is_kept_and_checked() {
252        assert!(is_kept_for_check(&limited("Usage limit reached", AgentState::Limited)));
253        assert!(!is_kept_for_check(&limited(crate::agents::failure::ROUTE_CREDITS_TITLE, AgentState::Limited)), "the route's own episode ends that");
254        assert!(!is_kept_for_check(&limited("Needs sign-in", AgentState::SignedOut)));
255    }
256
257    #[test]
258    fn at_most_the_cap_is_kept_per_agent_and_only_the_first_starts_a_watcher() {
259        let id = "person-hold-cap";
260        let mut firsts = 0;
261        for n in 0..MAX_KEPT {
262            if keep(id, words(&format!("m{n}"), 1).0).unwrap() {
263                firsts += 1;
264            }
265        }
266        assert_eq!((firsts, kept_count(id)), (1, MAX_KEPT));
267        let refused = keep(id, words("one more", 1).0).unwrap_err();
268        assert!(refused.starts_with(crate::backend::reactive::UNAVAILABLE_PREFIX), "{refused}");
269        assert_eq!(take_all(id).len(), MAX_KEPT);
270    }
271
272    #[test]
273    fn words_kept_for_a_day_are_dropped_with_that_answer() {
274        let id = "person-hold-expiry";
275        let (old, mut old_rx) = words("old", 1_000);
276        let (fresh, _fresh_rx) = words("fresh", KEEP_MS);
277        keep(id, old).unwrap();
278        keep(id, fresh).unwrap();
279        expire(id, 1_000 + KEEP_MS);
280        assert_eq!(take_all(id).iter().map(|w| w.text.as_str()).collect::<Vec<_>>(), vec!["fresh"]);
281        let answer = old_rx.try_recv().expect("answered").unwrap_err();
282        assert!(answer.contains("24 hours"), "{answer}");
283    }
284
285    #[test]
286    fn a_kept_answer_is_told_from_a_failure_by_its_prefix() {
287        assert_eq!(held_note("held: Out of quota; kept"), Some("Out of quota; kept"));
288        assert_eq!(held_note("agent unavailable: Out of quota: not sent"), None);
289        assert_eq!(held_note("no registered agent for this block"), None);
290    }
291
292    /// The whole of it on a real store: a person's words to a limited agent are kept and answered as kept
293    /// (the check cannot start: nothing is registered on the pane), and go the moment the limit is gone,
294    /// whoever cleared it.
295    #[tokio::test]
296    async fn a_broadcast_to_a_limited_agent_is_kept_and_leaves_once_the_limit_clears() {
297        let state = crate::server::tests::test_state();
298        let deps = AgentTurnDeps::from_state(&state);
299        let block_id = "person-hold-e2e-pane".to_string();
300        let mut block = crate::backend::obj::Block { oid: block_id.clone(), ..Default::default() };
301        let now = agentmux_common::time::now_ms_u64();
302        block.meta.insert(
303            crate::backend::blockcontroller::core::META_LAST_FAILURE.to_string(),
304            serde_json::json!({"code": "usage_limit", "title": "Usage limit reached", "detail": "", "retryable": false, "resetsAtMs": now + 86_400_000, "atMs": now - 1_000}),
305        );
306        state.mstore.insert(&mut block).unwrap();
307        // A pane with a running controller, as a limited agent has.
308        crate::backend::agent_state::test_support::register_stub(
309            &block_id,
310            crate::backend::blockcontroller::BLOCK_CONTROLLER_PERSISTENT,
311            crate::backend::blockcontroller::STATUS_RUNNING,
312            false,
313        );
314        let unavailable = crate::server::jekt_hold::holding_unavailable(&state.mstore, &block_id).expect("limited");
315        assert!(is_kept_for_check(&unavailable));
316
317        let answer = hold_and_check_within(&deps, block_id.clone(), "quota is back".into(), MessageOrigin::broadcast(), "Out of quota", Duration::from_millis(50)).await;
318        let note = answer.as_ref().err().and_then(|e| held_note(e)).expect("kept, not failed");
319        assert!(note.contains("Out of quota") && note.contains("sent when it can work"), "{note}");
320        assert_eq!(kept_count(&block_id), 1, "the words are kept, not lost");
321
322        // Another agent on the account worked: the stored limit is cleared.
323        let mut stored = state.mstore.get::<crate::backend::obj::Block>(&block_id).unwrap().unwrap();
324        stored.meta.remove(crate::backend::blockcontroller::core::META_LAST_FAILURE);
325        state.mstore.update(&mut stored).unwrap();
326        assert!(crate::server::jekt_hold::holding_unavailable(&state.mstore, &block_id).is_none(), "the limit is gone from the store");
327        let gone = async {
328            while kept_count(&block_id) > 0 {
329                tokio::time::sleep(Duration::from_millis(100)).await;
330            }
331        };
332        tokio::time::timeout(Duration::from_secs(5), gone).await.expect("the watcher sends what was kept once the agent can work");
333        crate::backend::blockcontroller::delete_controller(&block_id);
334    }
335
336    /// Review of #7797: a task start or an agent's message goes through `deliver_broadcast_turn`, which undoes
337    /// its work on a refusal; only the Swarm's person broadcast keeps words for a limited agent, and the waits
338    /// of all its kept targets run together after the delivery slots, not inside them.
339    #[tokio::test]
340    async fn only_a_swarm_broadcast_keeps_words_for_a_limited_agent() {
341        let state = crate::server::tests::test_state();
342        let deps = AgentTurnDeps::from_state(&state);
343        let block_id = "person-hold-callers-pane".to_string();
344        let mut block = crate::backend::obj::Block { oid: block_id.clone(), ..Default::default() };
345        let now = agentmux_common::time::now_ms_u64();
346        block.meta.insert(
347            crate::backend::blockcontroller::core::META_LAST_FAILURE.to_string(),
348            serde_json::json!({"code": "usage_limit", "title": "Usage limit reached", "detail": "", "retryable": false, "resetsAtMs": now + 86_400_000, "atMs": now - 1_000}),
349        );
350        state.mstore.insert(&mut block).unwrap();
351        crate::backend::agent_state::test_support::register_stub(
352            &block_id,
353            crate::backend::blockcontroller::BLOCK_CONTROLLER_PERSISTENT,
354            crate::backend::blockcontroller::STATUS_RUNNING,
355            false,
356        );
357
358        let refused = super::super::app_api::fleet::deliver_broadcast_turn(&deps, block_id.clone(), "start #1".into(), MessageOrigin::broadcast()).await.unwrap_err();
359        assert!(refused.starts_with(crate::backend::reactive::UNAVAILABLE_PREFIX), "{refused}");
360        assert_eq!(kept_count(&block_id), 0, "a task start or an agent's message keeps nothing");
361
362        let parked = deliver_person_broadcast(&deps, block_id.clone(), "quota is back".into(), MessageOrigin::broadcast()).await.unwrap_err();
363        assert!(parked.starts_with(PENDING_PREFIX), "{parked}");
364        assert_eq!(kept_count(&block_id), 1);
365        let outcome = super::super::app_api::fleet::BroadcastOutcome { block_id: block_id.clone(), agent_id: None, result: Err(parked) };
366        let resolved = resolve_pending_within(vec![outcome], Duration::from_millis(50)).await;
367        let note = resolved[0].result.as_ref().err().and_then(|e| held_note(e)).expect("answered as kept");
368        assert!(note.contains("sent when it can work"), "{note}");
369        assert_eq!(kept_count(&block_id), 1, "still kept after the answer");
370        take_all(&block_id);
371        crate::backend::blockcontroller::delete_controller(&block_id);
372    }
373
374    #[tokio::test]
375    async fn kept_words_go_in_order_once_the_agent_can_work_and_not_before() {
376        let id = "person-hold-watch";
377        let (a, a_rx) = words("first", agentmux_common::time::now_ms_u64());
378        let (b, b_rx) = words("second", agentmux_common::time::now_ms_u64());
379        keep(id, a).unwrap();
380        keep(id, b).unwrap();
381
382        let limited = Arc::new(AtomicBool::new(true));
383        let sent = Arc::new(Mutex::new(Vec::<String>::new()));
384        let looks = Arc::new(AtomicUsize::new(0));
385        let (l, s, n) = (limited.clone(), sent.clone(), looks.clone());
386        let watcher = tokio::spawn({
387            let (l2, s2) = (l.clone(), s.clone());
388            async move {
389                watch(
390                    id,
391                    move || {
392                        n.fetch_add(1, Ordering::SeqCst);
393                        let still = l2.load(Ordering::SeqCst);
394                        async move { still }
395                    },
396                    move |text, _from| {
397                        s2.lock().unwrap().push(text);
398                        async { Ok(()) }
399                    },
400                    Duration::from_millis(2),
401                    Duration::from_millis(2),
402                    Duration::from_millis(50),
403                )
404                .await
405            }
406        });
407        tokio::time::timeout(Duration::from_secs(5), async {
408            while looks.load(Ordering::SeqCst) < 3 {
409                tokio::time::sleep(Duration::from_millis(5)).await;
410            }
411        })
412        .await
413        .expect("it looks again and again while the agent is limited");
414        assert!(sent.lock().unwrap().is_empty(), "nothing is sent while it is limited");
415        assert_eq!(kept_count(id), 2, "and nothing is lost");
416
417        limited.store(false, Ordering::SeqCst);
418        watcher.await.unwrap();
419        assert_eq!(*sent.lock().unwrap(), vec!["first".to_string(), "second".to_string()]);
420        assert_eq!((a_rx.await.unwrap(), b_rx.await.unwrap()), (Ok(()), Ok(())), "each sender still waiting is answered");
421        assert_eq!(kept_count(id), 0);
422    }
423
424    #[tokio::test]
425    async fn a_failed_delivery_is_the_senders_answer_and_does_not_stop_the_rest() {
426        let id = "person-hold-fail";
427        let now = agentmux_common::time::now_ms_u64();
428        let (a, a_rx) = words("bad", now);
429        let (b, b_rx) = words("good", now);
430        keep(id, a).unwrap();
431        keep(id, b).unwrap();
432        watch(
433            id,
434            || async { false },
435            |text, _| async move { if text == "bad" { Err("no controller".to_string()) } else { Ok(()) } },
436            Duration::from_millis(1),
437            Duration::from_millis(1),
438            Duration::from_millis(10),
439        )
440        .await;
441        assert_eq!((a_rx.await.unwrap(), b_rx.await.unwrap()), (Err("no controller".to_string()), Ok(())));
442    }
443}