Skip to main content

agentmux_mcp/tools/
fleet.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Agent-to-agent messaging and fleet operations. Not advertised: `Agents`
5//! (agents_tool.rs), `Message` (message_tool.rs) and `Stop` (stop_tool.rs)
6//! call these by their old names.
7
8use super::*;
9
10/// `urgent: true` on a send or broadcast: deliver now, even to a session that
11/// has been idle for about an hour (srv holds a routine message for such a
12/// session until it is next active).
13fn urgent_priority(arguments: &Value) -> Option<String> {
14    arguments.get("urgent").and_then(|v| v.as_bool()).unwrap_or(false).then(|| "urgent".to_string())
15}
16
17/// `reply: "none"` on a send: the message asks for no reply (the marker says `REPLY=none`, and
18/// srv refuses an answer to it). Any other value is an ordinary message.
19fn reply_arg(arguments: &Value) -> Option<String> {
20    (arguments.get("reply").and_then(|v| v.as_str()) == Some("none")).then(|| "none".to_string())
21}
22
23/// `in_reply_to` on a send: the MSGID of the message this one answers.
24fn in_reply_to_arg(arguments: &Value) -> Option<String> {
25    arguments
26        .get("in_reply_to")
27        .and_then(|v| v.as_str())
28        .map(str::trim)
29        .filter(|id| !id.is_empty() && id.len() <= 128)
30        .map(str::to_string)
31}
32
33pub(super) async fn call(name: &str, arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
34    match name {
35        "SendMessage" => run_send_message(arguments, cx).await,
36        "DiscoverAgents" | "FleetList" => run_discover_agents(arguments, false, cx).await,
37        "FleetBroadcast" => run_fleet_broadcast(arguments, cx).await,
38        "FleetBulkStop" => run_fleet_bulk_stop(arguments, cx).await,
39        _ => Err(not_in_family()),
40    }
41}
42
43async fn run_send_message(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
44    let ToolCtx { local_url, auth_key, client, .. } = *cx;
45    let to = arguments
46        .get("to")
47        .and_then(|v| v.as_str())
48        .filter(|s| !s.is_empty())
49        .ok_or_else(|| anyhow::anyhow!("missing required parameter: to"))?;
50    let message = arguments
51        .get("message")
52        .and_then(|v| v.as_str())
53        .filter(|s| !s.is_empty())
54        .ok_or_else(|| anyhow::anyhow!("missing required parameter: message"))?;
55
56    if local_url.is_empty() || auth_key.is_empty() {
57        anyhow::bail!(
58            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
59             Is this agent pane opened via AgentMux?"
60        );
61    }
62
63    let source_agent = std::env::var("AGENTMUX_AGENT_ID")
64        .ok()
65        .filter(|s| !s.is_empty());
66
67    let url = format!(
68        "{}/agentmux/reactive/inject",
69        local_url.trim_end_matches('/')
70    );
71    // Files go into this agent's attachment store first; the jekt
72    // names them (SPEC_JEKT_FILE_TRANSFER_2026_10_05.md §3.1).
73    let files = match super::send_files::files_arg(arguments)? {
74        Some(paths) => {
75            let local = super::send_files::check(&paths)?;
76            Some(super::send_files::upload(local, cx).await?)
77        }
78        None => None,
79    };
80    let sent_names: Vec<String> = files.iter().flatten().map(|f| f.name.clone()).collect();
81    let mut req = signed_jekt_with_files(source_agent, to, message, files);
82    req.priority = urgent_priority(arguments);
83    req.reply = reply_arg(arguments);
84    req.in_reply_to = in_reply_to_arg(arguments);
85
86    let resp = client
87        .post(&url)
88        .header(AUTH_KEY_HEADER, auth_key)
89        .json(&req)
90        .timeout(crate::tool_helpers::INJECT_TIMEOUT)
91        .send()
92        .await
93        .map_err(|e| anyhow::anyhow!("{}", crate::tool_helpers::inject_transport_error(&e)))?;
94
95    if !resp.status().is_success() {
96        let status = resp.status();
97        let text = resp.text().await.unwrap_or_default();
98        anyhow::bail!("inject failed: HTTP {status} — {text}");
99    }
100
101    let result: Value = resp
102        .json()
103        .await
104        .map_err(|e| anyhow::anyhow!("response parse failed: {e}"))?;
105
106    let outcome = send_message_outcome(to, &result)?;
107    Ok(if sent_names.is_empty() {
108        outcome
109    } else {
110        // Fewer arrive when a file fails its hash on the way or the
111        // receiver withholds them; its message says which.
112        let arrived = result.get("files_delivered").and_then(Value::as_u64);
113        match arrived.filter(|n| (*n as usize) < sent_names.len()) {
114            Some(n) => format!("{outcome}\nFiles: {} ({n} of {} arrived)", sent_names.join(", "), sent_names.len()),
115            None => format!("{outcome}\nFiles: {}", sent_names.join(", ")),
116        }
117    })
118}
119
120/// What narrows or shapes the answer (spec SPEC_MUXAPI_AGENT_LIVE_FACTS §5): passed to srv as the query string.
121const DISCOVERY_PARAMS: &[&str] = &["fields", "detail", "state", "model", "provider", "runtime", "account", "seat", "limit", "offset", "group_by"];
122
123/// The query for the discovery endpoint from a call's arguments: only the parameters it knows, each as text.
124pub(super) fn discovery_query(arguments: &Value, status: bool) -> Vec<(&'static str, String)> {
125    let mut query: Vec<(&'static str, String)> = DISCOVERY_PARAMS
126        .iter()
127        .filter_map(|key| {
128            let text = match arguments.get(*key)? {
129                Value::String(s) => s.trim().to_string(),
130                Value::Number(n) => n.to_string(),
131                _ => return None,
132            };
133            (!text.is_empty()).then_some((*key, text))
134        })
135        .collect();
136    if status {
137        query.push(("view", "status".to_string()));
138    }
139    query
140}
141
142/// DiscoverAgents, its fleet-framed alias FleetList and `Agents status`: one call to the discovery endpoint, returned as it came.
143pub(super) async fn run_discover_agents(arguments: &Value, status: bool, cx: &ToolCtx<'_>) -> Result<String> {
144    let result = discover_value(arguments, status, false, cx).await?;
145    Ok(serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string()))
146}
147
148/// This machine's discovery answer as a value; with `all_hosts` it also names the LAN peers (`Agents` with `host: all`).
149pub(super) async fn discover_value(arguments: &Value, status: bool, all_hosts: bool, cx: &ToolCtx<'_>) -> Result<Value> {
150    let ToolCtx { local_url, auth_key, .. } = *cx;
151    if local_url.is_empty() || auth_key.is_empty() {
152        anyhow::bail!(
153            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
154             Is this agent pane opened via AgentMux?"
155        );
156    }
157
158    let mut query = discovery_query(arguments, status);
159    if all_hosts {
160        query.push(("host", "all".to_string()));
161    }
162    let query: Vec<(&str, &str)> = query.iter().map(|(k, v)| (*k, v.as_str())).collect();
163    cx.get_json("/agentmux/discovery", &query, "discovery").await
164}
165
166async fn run_fleet_broadcast(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
167    let ToolCtx { local_url, auth_key, client, .. } = *cx;
168    let (targets, message) = broadcast_args(arguments)?;
169
170    if local_url.is_empty() || auth_key.is_empty() {
171        anyhow::bail!(
172            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
173             Is this agent pane opened via AgentMux?"
174        );
175    }
176    let source_agent = std::env::var("AGENTMUX_AGENT_ID")
177        .ok()
178        .filter(|s| !s.is_empty());
179
180    // Files go into this agent's attachment store once; each target's
181    // jekt names them, signed for that target, exactly as `send` does
182    // (SPEC_JEKT_FILE_TRANSFER_2026_10_05.md §3.1). srv then applies
183    // the per-tier rules to each one: a verified sender, the LAN size
184    // limits.
185    let files = match super::send_files::files_arg(arguments)? {
186        Some(paths) => {
187            let local = super::send_files::check(&paths)?;
188            Some(super::send_files::upload(local, cx).await?)
189        }
190        None => None,
191    };
192    let sent_names: Vec<String> = files.iter().flatten().map(|f| f.name.clone()).collect();
193
194    let block_to_agent = discovered_block_to_agent(cx).await?;
195
196    // Same signed single-target delivery `Message` send uses, looped
197    // once per target — this process signs with its copy of the
198    // agent's keys (srv mints, stores and serves them), so signing
199    // happens here (see this tool's doc comment). Never a single
200    // aggregate result: per-target success/failure is collected below regardless of
201    // how many targets fail. Sent in chunks with a pause between
202    // them — `/agentmux/reactive/inject` shares ReactiveHandler's
203    // global rate limiter (10/sec, hard reset per second, not a
204    // smooth refill — crates/srv-core/src/backend/reactive/mod.rs's
205    // RATE_LIMIT_MAX), and a tight loop past ~10 targets would
206    // otherwise deterministically fail the tail of any larger
207    // broadcast with "rate limit exceeded" (Codex P1, same review).
208    // Mirrors `fleet_broadcast_impl`'s own chunking constants —
209    // kept in sync by hand since this is a separate process/crate
210    // with no dependency on agentmux-srv internals.
211    const BROADCAST_CHUNK_SIZE: usize = 10;
212    const BROADCAST_CHUNK_PAUSE: std::time::Duration = std::time::Duration::from_millis(1100);
213
214    let url = format!("{}/agentmux/reactive/inject", local_url.trim_end_matches('/'));
215    let priority = urgent_priority(arguments);
216    let mut succeeded: Vec<String> = Vec::new();
217    let mut held: Vec<serde_json::Value> = Vec::new();
218    let mut queued: Vec<serde_json::Value> = Vec::new();
219    let mut failed: Vec<serde_json::Value> = Vec::new();
220    // Delivered targets that got fewer files than were sent.
221    let mut files_short: Vec<serde_json::Value> = Vec::new();
222    for (chunk_idx, chunk) in targets.chunks(BROADCAST_CHUNK_SIZE).enumerate() {
223        if chunk_idx > 0 {
224            tokio::time::sleep(BROADCAST_CHUNK_PAUSE).await;
225        }
226        for target in chunk {
227            let target = target.clone();
228            // LAN/WAN discovery entries carry no block_id at all
229            // (they're not local blocks) — a target that doesn't
230            // match any known block_id is used AS the agent name
231            // directly, letting `/agentmux/reactive/inject`'s own
232            // cross-tier cascade attempt it. This can never make a
233            // genuinely-wrong block_id succeed silently: it still
234            // fails, just via the inject endpoint's own "agent not
235            // found" rather than this pre-check.
236            let target_agent = block_to_agent.get(&target).cloned().unwrap_or_else(|| target.clone());
237            let mut req = signed_jekt_with_files(source_agent.clone(), &target_agent, message, files.clone());
238            req.priority = priority.clone();
239            req.reply = reply_arg(arguments);
240            let outcome = post_jekt(client, &url, auth_key, &req).await;
241            match outcome {
242                Ok(Sent::Delivered(arrived)) => {
243                    // Fewer arrive when a file fails its hash on the
244                    // way or the receiver withholds them, as in `send`.
245                    if let Some(n) = arrived.filter(|n| (*n as usize) < sent_names.len()) {
246                        files_short.push(json!({ "id": target, "arrived": n }));
247                    }
248                    succeeded.push(target);
249                }
250                Ok(Sent::Held(reason)) => held.push(json!({ "id": target, "held": reason })),
251                Ok(Sent::Queued(request_id)) => queued.push(json!({ "id": target, "request_id": request_id })),
252                Err(error) => failed.push(json!({ "id": target, "error": error })),
253            }
254        }
255    }
256
257    Ok(broadcast_report(succeeded, failed, held, queued, &sent_names, files_short))
258}
259
260/// The targets and message a broadcast was given, refused when either is missing.
261fn broadcast_args(arguments: &Value) -> Result<(Vec<String>, &str)> {
262    let targets = arguments
263        .get("targets")
264        .and_then(|v| v.as_array())
265        .ok_or_else(|| anyhow::anyhow!("missing required parameter: targets"))?
266        .iter()
267        .filter_map(|v| v.as_str().map(str::to_string))
268        .collect::<Vec<_>>();
269    if targets.is_empty() {
270        anyhow::bail!("targets must be a non-empty array of block_id (host/cross-channel) or agent name (LAN/WAN) strings");
271    }
272    let message = arguments
273        .get("message")
274        .and_then(|v| v.as_str())
275        .filter(|s| !s.is_empty())
276        .ok_or_else(|| anyhow::anyhow!("missing required parameter: message"))?;
277    Ok((targets, message))
278}
279
280/// Each local and cross-channel agent's block id mapped to its name, from discovery.
281///
282/// `/agentmux/reactive/inject`'s `target_agent` resolves by
283/// agent UID or registered AGENT NAME only (`resolve_target`,
284/// crates/srv-core/src/backend/reactive/handler.rs) — never by
285/// block_id, even though this tool's own advertised contract
286/// (MESSAGE_TOOL, broadcast) is block_id values from Agents list, to
287/// stay consistent with Stop agents' targeting scheme. The
288/// WS-RPC path (`fleet_broadcast_impl`, agentmux-srv) already
289/// resolves block_id -> agent_id via `get_agent_by_block` before
290/// injecting; this MCP path talks to srv over plain HTTP with no
291/// access to that in-process registry, so it resolves the same
292/// way DiscoverAgents/FleetList already do: read
293/// `/agentmux/discovery`'s `host.addressable` (each entry already
294/// carries both `agent_id` and a live `block_id`) and map through
295/// it before signing/injecting (Codex P1 + reagent P0, PR #2687
296/// review — every advertised call failed "agent not found"
297/// without this).
298///
299/// REPORT_CROSS_INSTANCE_CONTROL_ROBUSTNESS_AUDIT_2026_08_22.md:
300/// `host.addressable` alone missed `host.cross_channel` entries
301/// (a different channel on this SAME host — those genuinely have
302/// a `block_id` in this host's namespace, discovery just wasn't
303/// being read for it) and LAN/WAN entries (which have NO
304/// `block_id` at all — only an agent name, since they're not
305/// local blocks). Both are folded in below: `cross_channel`
306/// extends the same block_id->name map (identical shape), and
307/// any target string that doesn't match ANY known block_id falls
308/// through to being used AS a literal agent name — safe because
309/// `/agentmux/reactive/inject`'s own cross-tier cascade
310/// (cross-channel -> LAN -> WAN muxbus relay,
311/// `server/reactive.rs`) already resolves by name across every
312/// tier; an invalid name just fails the same "not found" way it
313/// always did.
314async fn discovered_block_to_agent(cx: &ToolCtx<'_>) -> Result<std::collections::HashMap<String, String>> {
315    let ToolCtx { local_url, auth_key, client, .. } = *cx;
316    let discovery_url = format!("{}/agentmux/discovery", local_url.trim_end_matches('/'));
317    let discovery_resp = client
318        .get(&discovery_url)
319        .header(AUTH_KEY_HEADER, auth_key)
320        .send()
321        .await
322        .map_err(|e| anyhow::anyhow!("discovery request failed: {e}"))?;
323    if !discovery_resp.status().is_success() {
324        let status = discovery_resp.status();
325        let text = discovery_resp.text().await.unwrap_or_default();
326        anyhow::bail!("discovery failed: HTTP {status} — {text}");
327    }
328    let discovery: Value = discovery_resp
329        .json()
330        .await
331        .map_err(|e| anyhow::anyhow!("discovery response parse failed: {e}"))?;
332    Ok(build_block_to_agent_map(&discovery))
333}
334
335/// One signed jekt posted to inject: delivered, held until the agent is next active, or why not.
336async fn post_jekt(client: &reqwest::Client, url: &str, auth_key: &str, req: &InjectRequest) -> std::result::Result<Sent, String> {
337    let resp = client
338        .post(url)
339        .header(AUTH_KEY_HEADER, auth_key)
340        .json(req)
341        .timeout(crate::tool_helpers::INJECT_TIMEOUT)
342        .send()
343        .await
344        .map_err(|e| crate::tool_helpers::inject_transport_error(&e))?;
345    if !resp.status().is_success() {
346        let status = resp.status();
347        let text = resp.text().await.unwrap_or_default();
348        return Err(format!("HTTP {status} — {text}"));
349    }
350    let result: Value = resp
351        .json()
352        .await
353        .map_err(|e| format!("response parse failed: {e}"))?;
354    if result.get("success").and_then(|v| v.as_bool()) == Some(true) {
355        // Same test as `send`: srv names the receiving block only when a pane took it; the relay
356        // leaves it out because "queued is not delivered".
357        if result.get("block_id").and_then(|v| v.as_str()).is_none() {
358            let id = result.get("request_id").and_then(|v| v.as_str()).unwrap_or_default();
359            return Ok(Sent::Queued(id.to_string()));
360        }
361        Ok(Sent::Delivered(result.get("files_delivered").and_then(Value::as_u64)))
362    } else if let Some(reason) = crate::tool_helpers::held_until_active(&result) {
363        // Kept until the agent is next active, not lost: say so apart from the failures.
364        Ok(Sent::Held(reason))
365    } else {
366        Err(result
367            .get("error")
368            .and_then(|v| v.as_str())
369            .unwrap_or("unknown error")
370            .to_string())
371    }
372}
373
374/// What a broadcast tells the agent: who it reached, who held it, who failed, and the files it carried.
375fn broadcast_report(succeeded: Vec<String>, failed: Vec<Value>, held: Vec<Value>, queued: Vec<Value>, sent_names: &[String], files_short: Vec<Value>) -> String {
376    let mut result = json!({ "succeeded": succeeded, "failed": failed });
377    if !queued.is_empty() {
378        result["queued_unconfirmed"] = json!(queued);
379        result["queued_unconfirmed_note"] = json!(
380            "queued_unconfirmed: only queued at the cloud relay, NOT delivered: no pane has received it, and the relay drops it after 30 minutes; check the target is running and addressable (Agents list), or send it again later"
381        );
382    }
383    if !held.is_empty() {
384        result["held"] = json!(held);
385        result["held_note"] = json!(
386            "held: the message waits until the agent is next active (\"idle\": its session has been idle; \"quota\": quota mode is tight and it has no turn in flight, and the mode ending releases it too); send it again with urgent: true to deliver it now"
387        );
388    }
389    if !sent_names.is_empty() {
390        result["files"] = json!(sent_names);
391        result["files_short"] = json!(files_short);
392    }
393    serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string())
394}
395
396async fn run_fleet_bulk_stop(arguments: &Value, cx: &ToolCtx<'_>) -> Result<String> {
397    let ToolCtx { local_url, auth_key, .. } = *cx;
398    let targets = arguments
399        .get("targets")
400        .and_then(|v| v.as_array())
401        .ok_or_else(|| anyhow::anyhow!("missing required parameter: targets"))?
402        .iter()
403        .filter_map(|v| v.as_str().map(str::to_string))
404        .collect::<Vec<_>>();
405    if targets.is_empty() {
406        anyhow::bail!("targets must be a non-empty array of block_id strings");
407    }
408    let signal = arguments.get("signal").and_then(|v| v.as_str()).map(str::to_string);
409    let staged = arguments.get("staged").cloned();
410
411    if local_url.is_empty() || auth_key.is_empty() {
412        anyhow::bail!(
413            "AGENTMUX_LOCAL_URL and AGENTMUX_AUTH_KEY must be set. \
414             Is this agent pane opened via AgentMux?"
415        );
416    }
417
418    let mut body = json!({ "targets": targets, "signal": signal });
419    if let Some(staged) = staged {
420        body["staged"] = staged;
421    }
422    // Names this agent on the user's banner and in the audit log.
423    if let Ok(auth) = sign_ui_automation_auth() {
424        body["auth"] = serde_json::to_value(auth).unwrap_or(Value::Null);
425    }
426    let mut result = cx.post_json("/api/v1/fleet/bulk-stop", &body, "fleet bulk-stop").await?;
427    if result["status"] == "pending_user_override" {
428        // The user's 30 s window runs in srv, which tells this agent by note if it is kept or fails:
429        // answer now with what was opened. Several targets share one window.
430        let pending = result["pending"].as_array().cloned().unwrap_or_default();
431        let windows = pending_windows(&pending, result["deadline_ms"].as_i64(), agentmux_common::time::now_ms());
432        let note = result["note"].as_str().map(str::to_string);
433        result = json!({ "succeeded": result["succeeded"], "failed": result["failed"], "pending": windows });
434        add_stop_notes(&mut result, note, &pending);
435        let said = result["note"].as_str().map_or_else(|| pending_note(30), |n| format!("{n}; {}", pending_note(30)));
436        result["note"] = json!(said);
437    } else if result.get("kept_by_user").is_none() {
438        // Nothing waited (all refused or already gone): the same shape.
439        result["kept_by_user"] = json!([]);
440    }
441
442    Ok(serde_json::to_string_pretty(&result).unwrap_or_else(|_| result.to_string()))
443}
444
445/// How one broadcast target took its jekt.
446enum Sent {
447    /// Delivered; carries how many of its files arrived, when srv said.
448    Delivered(Option<u64>),
449    /// Kept until the agent is next active (`idle` or `quota`), not lost.
450    Held(&'static str),
451    /// Only queued at the cloud relay: no receiver has seen it, and it is dropped after 30 minutes.
452    Queued(String),
453}
454
455#[cfg(test)]
456mod call_tests;
457
458#[cfg(test)]
459mod broadcast_files_tests {
460    use super::*;
461    use std::io::{Read, Write};
462    use std::sync::{Arc, Mutex};
463
464    /// A stand-in for srv: discovery knows no one, the attachment store keeps
465    /// whatever it is given, and inject records each request and says
466    /// `delivered` files arrived.
467    struct StubSrv {
468        url: String,
469        injected: Arc<Mutex<Vec<Value>>>,
470    }
471
472    fn read_request(conn: &mut std::net::TcpStream) -> (String, Vec<u8>) {
473        let mut raw = Vec::new();
474        let mut buf = [0u8; 4096];
475        let head_end = loop {
476            if let Some(i) = raw.windows(4).position(|w| w == b"\r\n\r\n") {
477                break i + 4;
478            }
479            let n = conn.read(&mut buf).unwrap();
480            assert!(n > 0, "connection closed before the headers ended");
481            raw.extend_from_slice(&buf[..n]);
482        };
483        let head = String::from_utf8_lossy(&raw[..head_end]).to_ascii_lowercase();
484        let request_line = head.lines().next().unwrap_or_default().to_string();
485        let length = head
486            .lines()
487            .find_map(|l| l.strip_prefix("content-length:"))
488            .and_then(|v| v.trim().parse::<usize>().ok());
489        let chunked = head.contains("transfer-encoding: chunked");
490        // An upload is streamed, so it arrives chunked.
491        while match length {
492            Some(n) => raw.len() < head_end + n,
493            None => chunked && !raw.ends_with(b"0\r\n\r\n"),
494        } {
495            let n = conn.read(&mut buf).unwrap();
496            assert!(n > 0, "connection closed before the body ended");
497            raw.extend_from_slice(&buf[..n]);
498        }
499        (request_line, raw[head_end..].to_vec())
500    }
501
502    fn stub_srv(delivered: u64) -> StubSrv {
503        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
504        let url = format!("http://{}", listener.local_addr().unwrap());
505        let injected = Arc::new(Mutex::new(Vec::new()));
506        let seen = injected.clone();
507        std::thread::spawn(move || {
508            for conn in listener.incoming() {
509                let mut conn = conn.unwrap();
510                let seen = seen.clone();
511                std::thread::spawn(move || {
512                    let (line, body) = read_request(&mut conn);
513                    let answer = if line.contains("/agentmux/discovery") {
514                        json!({ "host": { "addressable": [] } })
515                    } else if line.contains("/attachments/upload") {
516                        json!({ "id": "ab".repeat(32), "bytes": 5 })
517                    } else {
518                        let req: Value = serde_json::from_slice(&body).unwrap();
519                        let relay_only = req["target_agent"].as_str().is_some_and(|t| t.starts_with("relay-"));
520                        seen.lock().unwrap().push(req);
521                        if relay_only {
522                            // No receiving block: the relay took it, no pane has.
523                            json!({ "success": true, "request_id": "inj-7" })
524                        } else {
525                            json!({ "success": true, "block_id": "b1", "files_delivered": delivered })
526                        }
527                    }
528                    .to_string();
529                    let _ = write!(
530                        conn,
531                        "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{answer}",
532                        answer.len()
533                    );
534                });
535            }
536        });
537        StubSrv { url, injected }
538    }
539
540    async fn broadcast(srv: &StubSrv, args: Value) -> Result<Value> {
541        let client = reqwest::Client::new();
542        let loops = LoopRegistry::default();
543        let counter = std::sync::atomic::AtomicU64::new(0);
544        let cx = ToolCtx { local_url: &srv.url, auth_key: "key", block_id: "", client: &client, loops: &loops, loop_counter: &counter };
545        let out = call("FleetBroadcast", &args, &cx).await?;
546        Ok(serde_json::from_str(&out)?)
547    }
548
549    fn file_in(dir: &tempfile::TempDir) -> String {
550        let path = dir.path().join("report.txt");
551        std::fs::write(&path, b"hello").unwrap();
552        path.to_string_lossy().into_owned()
553    }
554
555    /// Every target's jekt names the files, under a msgid that binds them, so
556    /// a LAN recipient gets what a direct send gives it.
557    #[tokio::test]
558    async fn each_target_gets_the_files_signed_into_its_jekt() {
559        use agentmux_common::jekt_files::{msgid_binds, JektFile};
560        let (srv, dir) = (stub_srv(1), tempfile::tempdir().unwrap());
561        let out = broadcast(&srv, json!({ "targets": ["lan-a", "lan-b"], "message": "look", "files": [file_in(&dir)] })).await.unwrap();
562
563        assert_eq!(out["succeeded"], json!(["lan-a", "lan-b"]));
564        assert_eq!(out["failed"], json!([]));
565        assert_eq!(out["files"], json!(["report.txt"]));
566        assert_eq!(out["files_short"], json!([]));
567        let sent = srv.injected.lock().unwrap();
568        assert_eq!(sent.len(), 2);
569        for (req, target) in sent.iter().zip(["lan-a", "lan-b"]) {
570            assert_eq!(req["target_agent"], target);
571            let files: Vec<JektFile> = serde_json::from_value(req["files"].clone()).expect("the jekt carries its files");
572            assert_eq!(files.len(), 1);
573            assert_eq!(files[0].name, "report.txt");
574            assert!(msgid_binds(req["request_id"].as_str().unwrap(), &files));
575        }
576        assert_ne!(sent[0]["request_id"], sent[1]["request_id"], "each target is signed on its own");
577    }
578
579    /// A target that took the message but not every file is named, not
580    /// counted as a plain success.
581    #[tokio::test]
582    async fn a_target_that_got_fewer_files_is_named() {
583        let (srv, dir) = (stub_srv(0), tempfile::tempdir().unwrap());
584        let out = broadcast(&srv, json!({ "targets": ["lan-a"], "message": "look", "files": [file_in(&dir)] })).await.unwrap();
585        assert_eq!(out["succeeded"], json!(["lan-a"]));
586        assert_eq!(out["files_short"], json!([{ "id": "lan-a", "arrived": 0 }]));
587    }
588
589    /// A file that can't be sent stops the broadcast before any target is
590    /// messaged.
591    #[tokio::test]
592    async fn a_missing_file_sends_nothing() {
593        let (srv, dir) = (stub_srv(1), tempfile::tempdir().unwrap());
594        let missing = dir.path().join("nope.txt").to_string_lossy().into_owned();
595        let err = broadcast(&srv, json!({ "targets": ["lan-a"], "message": "look", "files": [missing] })).await.unwrap_err().to_string();
596        assert!(err.contains("nope.txt"), "{err}");
597        assert!(srv.injected.lock().unwrap().is_empty());
598    }
599
600    /// A copy only the relay took is not a delivery: it is named apart, with its id, and not counted as succeeded.
601    #[tokio::test]
602    async fn a_relay_only_copy_is_not_reported_as_delivered() {
603        let srv = stub_srv(0);
604        let out = broadcast(&srv, json!({ "targets": ["lan-a", "relay-masty"], "message": "hi" })).await.unwrap();
605        assert_eq!(out["succeeded"], json!(["lan-a"]));
606        assert_eq!(out["queued_unconfirmed"], json!([{ "id": "relay-masty", "request_id": "inj-7" }]));
607        assert!(out["queued_unconfirmed_note"].as_str().unwrap().contains("NOT delivered"));
608        assert_eq!(out["failed"], json!([]));
609    }
610
611    /// Without files a broadcast is what it was.
612    #[tokio::test]
613    async fn a_broadcast_without_files_carries_none() {
614        let srv = stub_srv(0);
615        let out = broadcast(&srv, json!({ "targets": ["lan-a"], "message": "hi" })).await.unwrap();
616        assert_eq!(out, json!({ "succeeded": ["lan-a"], "failed": [] }));
617        let sent = srv.injected.lock().unwrap();
618        assert!(sent[0].get("files").is_none_or(Value::is_null));
619    }
620}
621
622#[cfg(test)]
623mod urgent_tests {
624    #[test]
625    fn reply_none_and_in_reply_to_are_read_from_the_arguments() {
626        use super::{in_reply_to_arg, reply_arg};
627        use serde_json::json;
628        assert_eq!(reply_arg(&json!({ "reply": "none" })), Some("none".to_string()));
629        assert_eq!(reply_arg(&json!({ "reply": "ok" })), None);
630        assert_eq!(reply_arg(&json!({})), None);
631        assert_eq!(in_reply_to_arg(&json!({ "in_reply_to": " m-1 " })), Some("m-1".to_string()));
632        assert_eq!(in_reply_to_arg(&json!({ "in_reply_to": "" })), None);
633        assert_eq!(in_reply_to_arg(&json!({ "in_reply_to": "x".repeat(200) })), None);
634    }
635
636    use super::*;
637    use serde_json::json;
638
639    #[test]
640    fn urgent_true_is_the_only_thing_that_sets_a_priority() {
641        assert_eq!(urgent_priority(&json!({ "urgent": true })), Some("urgent".to_string()));
642        assert_eq!(urgent_priority(&json!({ "urgent": false })), None);
643        assert_eq!(urgent_priority(&json!({})), None);
644        assert_eq!(urgent_priority(&json!({ "urgent": "yes" })), None, "not a boolean");
645    }
646}