Skip to main content

agentmux_srv/server/reactive/
detached.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A delivery that finishes whether or not the request that asked for it is still waiting (task #2485).
5//!
6//! `deliver` can take longer than a sender waits: each tier for an agent this instance does not run is a
7//! network call with its own timeout (a LAN peer, the cloud relay's token, lease and publish), and the last
8//! step of the chain is the one that holds the message for an agent that is stopped. The MCP client gave up
9//! after 10 s, hyper dropped the handler's future with the connection, and the message was neither delivered
10//! nor held: the sender saw only "error sending request", three times, for a stopped agent.
11
12use super::*;
13
14/// [`deliver`], run as a task of its own: the answer is awaited here, but a caller that stops waiting does
15/// not cancel the delivery halfway through its tiers. A delivery that panics answers with a failure.
16pub(super) async fn deliver_to_completion(
17    state: &AppState,
18    auth_via: crate::server::ReactiveAuthVia,
19    caller_uid: &str,
20    req: InjectionRequest,
21) -> serde_json::Value {
22    let (state, caller_uid, target) = (state.clone(), caller_uid.to_string(), req.target_agent.clone());
23    // Carried into the task, so the stages it passes are seen by the request's watch (`lan_watch`).
24    match tokio::spawn(crate::server::lan_watch::carry(async move { deliver(&state, auth_via, &caller_uid, req).await })).await {
25        Ok(answer) => answer,
26        Err(e) => {
27            tracing::error!(target = %target, error = %e, "reactive inject: the delivery task failed");
28            serde_json::json!({ "success": false, "error": format!("delivery to {target} failed inside srv: {e}") })
29        }
30    }
31}
32
33#[cfg(test)]
34mod tests {
35    use super::*;
36    use crate::backend::storage::agents::test_agent_def;
37    use crate::server::tests::test_state;
38
39    /// A message to a known agent that is stopped (no pane, no controller) is held for it, even when the
40    /// sender stops waiting right after sending (task #2485): the wait is dropped after its first poll.
41    #[tokio::test]
42    async fn a_message_the_sender_stopped_waiting_for_is_still_held_for_a_stopped_agent() {
43        let state = test_state();
44        let slug = format!("stopped-{}", &uuid::Uuid::new_v4().to_string()[..8]);
45        let uid = format!("uid-{slug}");
46        let mut def = test_agent_def(&uid, "Stopped Agent", "claude", "agent", 1, "");
47        def.slug = slug.clone();
48        state.mstore.agent_def_insert(&mut def).unwrap();
49        let request_id = format!("req-{slug}");
50
51        let mut held = Vec::new();
52        // The global handler's rate limiter is shared by every test (10/s): an attempt it refused is sent again.
53        for _ in 0..25 {
54            let req: InjectionRequest = serde_json::from_value(
55                serde_json::json!({ "target_agent": slug, "message": "hi", "source_agent": "sender", "request_id": request_id }),
56            )
57            .unwrap();
58            let _ = tokio::time::timeout(std::time::Duration::ZERO, deliver_to_completion(&state, crate::server::ReactiveAuthVia::FullAuthKey, "", req)).await;
59            for _ in 0..20 {
60                held = state.mstore.jekt_held_for_target(&uid, 10).unwrap();
61                if !held.is_empty() {
62                    break;
63                }
64                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
65            }
66            if !held.is_empty() {
67                break;
68            }
69        }
70        assert_eq!(held.len(), 1, "the message is held, not lost with the dropped wait");
71        assert_eq!(held[0].request_id, request_id);
72    }
73}