Skip to main content

agentmux_srv/server/app_api/
fleet.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Fleet control — select, broadcast, and bulk-act on many agents at once.
5//! See docs/specs/SPEC_MULTI_AGENT_FLEET_CONTROL_2026_08_20.md.
6//!
7//! `fleet.broadcast`/`fleet.bulk-stop` are thin server-side loops over the
8//! EXISTING single-target primitives (`ReactiveHandler::inject_message`,
9//! `agent_io::stop_one_agent_block`) — no new transport is invented, and
10//! every action returns `FleetActionResult` (succeeded/failed per target),
11//! never a single bool, per the spec's §3 finding that silent partial
12//! failure is the single most commonly-cited fleet-ops UX failure mode.
13//!
14//! `fleet.broadcast` is deliberately WS-RPC-only (the human/Swarm-UI path),
15//! not exposed over HTTP to agentmux-mcp. It is NOT a jekt: a broadcast is the
16//! human typing once to several panes, so each target gets a message routed the
17//! way an inter-agent message is (`bootstrap::route_agent_message`: persistent, ACP
18//! and App Server on their own channel, a subprocess or unspawned agent via
19//! `run_agent_turn`) with a one-line `[BROADCAST:FROM=user VIA=swarm ...]` header
20//! from `reactive::broadcast_turn_message`, instead of a `self-declared` jekt from
21//! `unknown`. See `docs/specs/SPEC_SWARM_BROADCAST_AS_USER_MESSAGE_2026_10_01.md`.
22//! The turn is `MessageOrigin::broadcast()` (a `User` turn): a broadcast is the human's own
23//! message, with the same powers as typing it into each pane, including
24//! authorizing an agent's self-quit (owner decision 2026-10-06, spec §6 q2).
25//! The one exception is `App` `upgrade`: it is once per machine, so a broadcast
26//! doesn't count and the user is asked (`self_quit::gate_upgrade`, owner decision
27//! 2026-10-23).
28//! That adds no power to anything holding the pane key, which could already send
29//! any pane a plain `User` turn through `agent.input` (spec §2 finding 7, §4.2).
30//! srv, not the text, still decides: the label comes from this module only.
31//! A target running on another channel on this machine is reached over loopback,
32//! the way a stop is (`forward_broadcast_to_channel`): the sender passes only the
33//! target block, the body, the `MSGID` and the `RECIPIENTS` count, and the
34//! receiving instance builds the header and starts the turn itself
35//! (`deliver_forwarded_broadcast`). An agent on a LAN peer can't get a user
36//! turn: nothing on the LAN proves who is asking
37//! (docs/specs/SPEC_SWARM_REMOTE_AGENTS_PLATFORM_TAG_AND_SELECTION_2026_10_03.md §6).
38//! It gets a jekt from this instance instead, signed with this instance's own
39//! LAN key, which its instance verifies as it does any agent's
40//! (`backend::lan::swarm_broadcast`, SPEC_SWARM_REFINEMENTS_2026_10_17.md §4.2).
41//! The forward uses the same loopback auth as the stop forward, and reaches only
42//! what that channel's own `fleet.broadcast` already does.
43//! An AGENT-initiated broadcast instead loops the EXISTING signed single-target
44//! `Message` send path client-side (`Message` broadcast in `agentmux-mcp`) —
45//! srv mints, stores and serves each agent's keys and the agent's MCP signs
46//! with its copy, so per-message signing happens there, never in a
47//! server-side batch RPC.
48//! `fleet.bulk-stop` has no such constraint (a controller stop involves no
49//! jekt signing at all, same as `agent.stop` today) and IS exposed over
50//! HTTP (`POST /api/v1/fleet/bulk-stop`) for `FleetBulkStop`.
51
52use agentmux_common::AUTH_KEY_HEADER;
53use std::sync::Arc;
54
55use crate::backend::blockcontroller::health::TurnOrigin;
56use crate::backend::message_origin::MessageOrigin;
57use crate::backend::reactive::broadcast_turn_message;
58use crate::backend::rpc::engine::WshRpcEngine;
59use crate::backend::rpc_types::*;
60
61use super::AppState;
62use super::agent_io::stop_one_agent_block;
63use crate::server::agent_handlers::{run_agent_turn, AgentTurnDeps, TurnRegistration};
64
65pub(super) const FLEET_BROADCAST_AUDIT_ACTION: &str = "fleet.broadcast";
66
67pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
68    register_fleet_broadcast(engine, state);
69    register_fleet_bulk_stop(engine, state);
70    super::fleet_check_limits::register(engine, state);
71    register_fleet_group_create(engine, state);
72    register_fleet_group_list(engine, state);
73    register_fleet_group_update(engine, state);
74    register_fleet_group_delete(engine, state);
75}
76
77fn register_fleet_broadcast(engine: &Arc<WshRpcEngine>, state: &AppState) {
78    let state = state.clone();
79    engine.register_typed(
80        COMMAND_FLEET_BROADCAST,
81        move |cmd: CommandFleetBroadcastData, ctx| {
82            let state = state.clone();
83            async move {
84                // A broadcast arrives as the user's own turn, so only the operator's window sends one.
85                ctx.operator_only("a Swarm broadcast arrives as the operator's own words, so only the AgentMux window sends one; an agent broadcasts as itself with the Message tool")?;
86                let result = fleet_broadcast_impl(&state, cmd.targets, cmd.message, cmd.progress_id).await;
87                Ok(result)
88            }
89        },
90    );
91}
92
93/// What happened to one target of a broadcast.
94pub(crate) struct BroadcastOutcome {
95    pub block_id: String,
96    /// The agent the block resolved to; `None` when nothing is registered for it.
97    pub agent_id: Option<String>,
98    pub result: Result<(), String>,
99}
100
101pub(super) const NO_REGISTERED_AGENT: &str =
102    "no registered agent for this block (not a live agent pane, or not yet registered)";
103
104/// The broadcast logic, with srv's two touch points passed in so it can be tested
105/// without an `AppState`: `resolve` maps a block id to its agent id, and `deliver`
106/// starts one turn (block id, full text, origin).
107///
108/// Targets are resolved first so `RECIPIENTS` in every header counts the agents
109/// actually addressed; the same `msg_id` ties the copies together in the audit
110/// log. Each delivery starts at its own time in `pace` (`fleet_pacing`), so a
111/// slow or failed one holds up no other, and results come back in the order of
112/// `targets`.
113pub(crate) async fn run_broadcast<R, D, Fut>(
114    targets: Vec<String>,
115    body: &str,
116    msg_id: &str,
117    pace: super::fleet_pacing::Pace,
118    resolve: R,
119    deliver: D,
120) -> Vec<BroadcastOutcome>
121where
122    R: Fn(&str) -> Option<String>,
123    D: Fn(String, String, MessageOrigin) -> Fut,
124    Fut: std::future::Future<Output = Result<(), String>>,
125{
126    use futures_util::StreamExt;
127
128    let resolved: Vec<(String, Option<String>)> = targets
129        .into_iter()
130        .map(|block_id| {
131            let agent = resolve(&block_id);
132            (block_id, agent)
133        })
134        .collect();
135    let recipients = resolved.iter().filter(|(_, agent)| agent.is_some()).count();
136    let (total, ended) = (resolved.len(), std::sync::atomic::AtomicUsize::new(0));
137
138    let mut outcomes: Vec<(usize, BroadcastOutcome)> = futures_util::stream::iter(resolved.into_iter().enumerate())
139        .map(|(index, (block_id, agent_id))| {
140            let (deliver, pace, ended) = (&deliver, &pace, &ended);
141            async move {
142                pace.until_start(index).await;
143                let result = match &agent_id {
144                    None => Err(NO_REGISTERED_AGENT.to_string()),
145                    Some(agent) => {
146                        let text = broadcast_turn_message(agent, recipients, msg_id, body);
147                        deliver(block_id.clone(), text, MessageOrigin::broadcast()).await
148                    }
149                };
150                pace.ended(ended.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1, total);
151                (index, BroadcastOutcome { block_id, agent_id, result })
152            }
153        })
154        .buffer_unordered(total.max(1))
155        .collect()
156        .await;
157    outcomes.sort_by_key(|(index, _)| *index);
158    outcomes.into_iter().map(|(_, outcome)| outcome).collect()
159}
160
161/// What to do with one target, given how its controller routes a message.
162#[derive(Debug, PartialEq, Eq)]
163pub(crate) enum BroadcastAction {
164    /// Taken on a structured channel (now or queued).
165    Done,
166    /// Start a turn.
167    StartTurn,
168    Fail(String),
169}
170
171/// Maps `route_agent_message`'s answer to an action. A PTY-based target is
172/// refused rather than typed into: a broadcast is prose, and keystrokes into a
173/// shell prompt would run it as a command.
174pub(crate) fn broadcast_action(route: Result<crate::bootstrap::AgentRoute, String>) -> BroadcastAction {
175    use crate::backend::reactive::SenderDelivery;
176    use crate::bootstrap::AgentRoute;
177    match route {
178        Ok(AgentRoute::Sent(SenderDelivery::Delivered | SenderDelivery::Deferred)) => BroadcastAction::Done,
179        Ok(AgentRoute::Sent(SenderDelivery::Pty)) => BroadcastAction::Fail(
180            "this pane is a terminal, not an agent session; a broadcast is not typed into a shell".to_string(),
181        ),
182        Ok(AgentRoute::StartTurn { .. }) => BroadcastAction::StartTurn,
183        Err(e) => BroadcastAction::Fail(e),
184    }
185}
186
187/// Delivers one broadcast text to one block the way an inter-agent message reaches
188/// it (`route_agent_message_from`): structured controllers (persistent, ACP, App
189/// Server) take it on their own channel, which also steers a turn already running;
190/// a subprocess or not-yet-spawned persistent agent gets a turn started with
191/// `origin`. Either way the turn is labelled with `origin` where the controller
192/// tracks provenance at all (persistent and subprocess, the same agents a typed
193/// message can authorize a self-quit on).
194pub(crate) async fn deliver_broadcast_turn(
195    deps: &AgentTurnDeps,
196    block_id: String,
197    text: String,
198    from: MessageOrigin,
199) -> Result<(), String> {
200    // An agent out of quota or signed out would fail the turn at once: say so
201    // in the broadcast's result, where the operator sees it, rather than lose
202    // their words in a failed turn (SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md §5).
203    let mstore = deps.mstore.clone();
204    let id = block_id.clone();
205    let unavailable = tokio::task::spawn_blocking(move || {
206        crate::server::jekt_hold::holding_unavailable(&mstore, &id)
207    })
208    .await
209    .ok()
210    .flatten();
211    if let Some(u) = unavailable {
212        return Err(format!("{}{}: not sent", crate::backend::reactive::UNAVAILABLE_PREFIX, u.reason()));
213    }
214    deliver_available(deps, block_id, text, from).await
215}
216
217/// [`deliver_broadcast_turn`] for an agent that can work: the words go as a turn of the person's.
218pub(crate) async fn deliver_available(
219    deps: &AgentTurnDeps,
220    block_id: String,
221    text: String,
222    from: MessageOrigin,
223) -> Result<(), String> {
224    let input = crate::backend::blockcontroller::health::TurnInput { from: from.clone(), text: text.clone(), joins_turn: None };
225    match broadcast_action(crate::bootstrap::route_agent_message_from(&block_id, &text, Some(input), from.clone(), &[], None)) {
226        BroadcastAction::Done => Ok(()),
227        BroadcastAction::Fail(e) => Err(e),
228        // The block was resolved through the reactive handler's own agent map, so
229        // it is already registered: skip re-registering, as the reactive-delivery
230        // caller does.
231        BroadcastAction::StartTurn => {
232            run_agent_turn(deps, block_id, text, None, TurnRegistration::Skip, from, Vec::new()).await
233        }
234    }
235}
236
237/// How one broadcast target is reached.
238enum BroadcastRoute {
239    /// An agent pane of this instance.
240    Local(String),
241    /// An agent on another channel on this machine, via its own srv.
242    Channel(crate::backend::reactive::registry::AgentEntry),
243    /// An agent on a LAN peer: a signed jekt from this instance, not a user
244    /// turn (`backend::lan::swarm_broadcast`).
245    Lan { route: crate::backend::swarm_remote::PeerRoute, agent: String },
246}
247
248impl BroadcastRoute {
249    fn agent_id(&self) -> &str {
250        match self {
251            BroadcastRoute::Local(agent) => agent,
252            BroadcastRoute::Channel(entry) => &entry.agent_id,
253            BroadcastRoute::Lan { agent, .. } => agent,
254        }
255    }
256}
257
258/// What every LAN delivery of one broadcast shares: this instance's sender name
259/// and key, or why it can't sign.
260struct LanSender {
261    sender_id: String,
262    private_key: Result<String, String>,
263    hostname: String,
264}
265
266impl LanSender {
267    fn for_state(state: &AppState) -> Self {
268        let sender_id = crate::backend::lan::swarm_broadcast::this_sender_id(&state.hostname);
269        let private_key = state
270            .mstore
271            .agent_lan_key_ensure(&sender_id)
272            .map(|k| k.private_key)
273            .map_err(|e| format!("can't sign for this AgentMux: {e}"));
274        Self { sender_id, private_key, hostname: state.hostname.clone() }
275    }
276
277    async fn deliver(&self, client: &reqwest::Client, route: &crate::backend::swarm_remote::PeerRoute, agent: &str, body: &str, recipients: usize) -> Result<(), String> {
278        use crate::backend::lan::swarm_broadcast as lan;
279        let key = self.private_key.as_ref().map_err(Clone::clone)?;
280        let text = lan::broadcast_text(&self.hostname, recipients, body);
281        let msg_id = uuid::Uuid::new_v4().to_string();
282        let req = lan::signed_request(&self.sender_id, key, agent, &text, &msg_id, agentmux_common::time::now_secs())
283            .ok_or_else(|| "can't sign for this AgentMux: its LAN key is unreadable".to_string())?;
284        lan::send(client, route, &req).await
285    }
286}
287
288/// What a forwarded broadcast carries. No header text: the receiving instance
289/// writes the header, so a caller on loopback cannot supply its own.
290pub(crate) struct BroadcastForward<'a> {
291    pub block_id: &'a str,
292    pub body: &'a str,
293    pub msg_id: &'a str,
294    /// Agents addressed on every machine and channel, for the header.
295    pub recipients: usize,
296}
297
298// The receiving end, and the confirmation that decides how a forward is delivered (fleet_forward.rs).
299use super::fleet_forward::vouch_for_forward;
300pub(crate) use super::fleet_forward::{body_digest, confirm_forward, deliver_forwarded_broadcast};
301
302/// Asks the instance at `local_url` (another channel on this machine, its
303/// `auth_key` from the shared registry, same user) to deliver one broadcast.
304/// A channel from before the route answers 404 and is named as such, for that
305/// target only.
306pub(crate) async fn forward_broadcast_to_channel(
307    client: &reqwest::Client,
308    local_url: &str,
309    auth_key: &str,
310    req: &BroadcastForward<'_>,
311) -> Result<(), String> {
312    let mut http = client
313        .post(format!("{local_url}/agentmux/agent/broadcast"))
314        .json(&serde_json::json!({
315            "block_id": req.block_id,
316            "body": req.body,
317            "msg_id": req.msg_id,
318            "recipients": req.recipients,
319        }));
320    if !auth_key.is_empty() {
321        http = http.header(AUTH_KEY_HEADER, auth_key);
322    }
323    let resp = http.send().await.map_err(|e| format!("cross-channel forward failed: {e}"))?;
324    if resp.status() == reqwest::StatusCode::NOT_FOUND {
325        return Err("that channel is on an older build and can't receive a broadcast from here".to_string());
326    }
327    if !resp.status().is_success() {
328        return Err(format!("cross-channel forward: HTTP {}", resp.status()));
329    }
330    let body: serde_json::Value = resp
331        .json()
332        .await
333        .map_err(|e| format!("cross-channel forward: response parse failed: {e}"))?;
334    if body.get("success").and_then(|v| v.as_bool()) == Some(true) {
335        Ok(())
336    } else {
337        Err(body.get("error").and_then(|v| v.as_str()).unwrap_or("cross-channel forward failed").to_string())
338    }
339}
340
341pub(crate) async fn fleet_broadcast_impl(
342    state: &AppState,
343    targets: Vec<String>,
344    message: String,
345    progress_id: Option<String>,
346) -> FleetActionResult {
347    let deps = AgentTurnDeps::from_state(state);
348    let msg_id = uuid::Uuid::new_v4().to_string();
349    // This instance's own panes first, then the machine's other channels, then
350    // an agent on a LAN peer by its Swarm key, resolved through the same hosts
351    // the Swarm lists. A target known to none has no route and fails, as before.
352    use crate::backend::lan::swarm_broadcast::{parse_remote_key, route_for};
353    let lan_hosts = if targets.iter().any(|t| parse_remote_key(t).is_some()) {
354        crate::backend::swarm_remote::lan_hosts(
355            &state.lan_discovery.get_instances(),
356            &crate::backend::lan::listeners::cached_local_addresses(),
357            &[],
358            agentmux_common::time::now_ms_u64(),
359        )
360    } else {
361        Vec::new()
362    };
363    let routes: std::collections::HashMap<String, BroadcastRoute> = targets
364        .iter()
365        .filter_map(|key| {
366            let route = if let Some((section, name)) = parse_remote_key(key) {
367                BroadcastRoute::Lan { route: route_for(&lan_hosts, section)?, agent: name.to_string() }
368            } else {
369                match state.reactive_handler.get_agent_by_block(key) {
370                    Some(agent) => BroadcastRoute::Local(agent.agent_id),
371                    None => BroadcastRoute::Channel(shared_channel_for(state, key)?),
372                }
373            };
374            Some((key.clone(), route))
375        })
376        .collect();
377    // Only a broadcast that reaches a LAN peer mints this instance's key.
378    let any_lan = routes.values().any(|r| matches!(r, BroadcastRoute::Lan { .. }));
379    let lan_sender = Arc::new(any_lan.then(|| LanSender::for_state(state)));
380    let routes = Arc::new(routes);
381    // The same count `run_broadcast` puts in the local headers: every target
382    // that resolved, here or on another channel.
383    let recipients = targets.iter().filter(|b| routes.contains_key(*b)).count();
384    // Only a turn that starts on this AgentMux is paced; a target handed on to another channel or machine is not.
385    let local = routes.iter().filter(|(_, r)| matches!(r, BroadcastRoute::Local(_))).map(|(key, _)| key.clone()).collect();
386    let pace = super::fleet_pacing::pace_for(state, &targets, local, &msg_id, progress_id).await;
387    let outcomes = run_broadcast(
388        targets,
389        &message,
390        &msg_id,
391        pace,
392        |block_id| routes.get(block_id).map(|r| r.agent_id().to_string()),
393        |block_id, text, origin| {
394            let deps = deps.clone();
395            let routes = routes.clone();
396            let lan_sender = lan_sender.clone();
397            let client = state.http_client.clone();
398            let (body, msg_id) = (message.clone(), msg_id.clone());
399            async move {
400                match routes.get(&block_id) {
401                    Some(BroadcastRoute::Channel(entry)) => {
402                        let forward = BroadcastForward { block_id: &block_id, body: &body, msg_id: &msg_id, recipients };
403                        vouch_for_forward(&forward);
404                        forward_broadcast_to_channel(&client, &entry.local_url, &entry.auth_key, &forward).await
405                    }
406                    Some(BroadcastRoute::Lan { route, agent }) => match lan_sender.as_ref() {
407                        Some(sender) => sender.deliver(&client, route, agent, &body, recipients).await,
408                        None => Err("no LAN sender".to_string()),
409                    },
410                    _ => crate::server::person_hold::deliver_person_broadcast(&deps, block_id, text, origin).await,
411                }
412            }
413        },
414    )
415    .await;
416    // The agents kept for a check are waited for together, outside the delivery slots above.
417    let outcomes = crate::server::person_hold::resolve_pending(outcomes).await;
418
419    super::fleet_result::settle_broadcast(
420        state,
421        outcomes,
422        |block_id| matches!(routes.get(block_id), Some(BroadcastRoute::Local(_))),
423        &msg_id,
424        &message,
425    )
426}
427
428
429fn register_fleet_bulk_stop(engine: &Arc<WshRpcEngine>, state: &AppState) {
430    let state = state.clone();
431    engine.register_typed(
432        COMMAND_FLEET_BULK_STOP,
433        move |cmd: CommandFleetBulkStopData, ctx| {
434            let state = state.clone();
435            async move {
436                // A connection registered as an agent waits for the person's override window on every
437                // target that is another agent's; the window's own connection stops at once.
438                if !ctx.agent_id.trim().is_empty() {
439                    return super::agent_io::agent_bulk_stop(&state, &ctx.agent_id, cmd.targets, cmd.signal.as_deref(), cmd.staged).await;
440                }
441                let result = fleet_bulk_stop_impl(&state, cmd.targets, cmd.signal.as_deref(), cmd.staged).await;
442                Ok(result)
443            }
444        },
445    );
446}
447
448const FLEET_BULK_STOP_AUDIT_ACTION: &str = "fleet.bulk-stop";
449
450/// Stops `targets` (block ids) via the existing single-target
451/// `stop_one_agent_block`, one call per target, and — unlike that
452/// single-target primitive, which involves no jekt signing and so was
453/// never audited — records one `AuditLogEntry` per target via
454/// `ReactiveHandler::log_fleet_action_audit`, so the Audit pane sees
455/// every fleet-initiated stop (`SPEC_MULTI_AGENT_FLEET_CONTROL_2026_08_20.md`
456/// §6; reagent/Codex P2, PR #2687 review — this was missing entirely).
457/// Without `staged`, runs every target as a single batch (still returns
458/// full per-target detail, never a bool). With `staged`, targets are
459/// stopped `batch_size` at a time; if the failure rate WITHIN a completed
460/// batch exceeds `max_fail_percentage`, remaining targets are recorded as
461/// failed (untried) and `aborted_early` is set — caps blast radius on a
462/// bad selection rather than plowing through every remaining target.
463/// `aborted_early` is only ever set when targets were genuinely left
464/// unattempted — tripping the threshold on the LAST batch (nothing left to
465/// skip) must not report "aborted early" when the full list actually ran
466/// (reagent P2, same review).
467/// Look up `block_id` in the shared cross-channel registry (this host,
468/// other channels — same registry `server/reactive.rs`'s inject cascade
469/// tier-2b already reads) and forward a stop request over loopback HTTP to
470/// that channel's own srv (`/agentmux/agent/stop`), using its own
471/// `auth_key` from the registry entry — identical trust model to the
472/// inject cascade's own cross-channel forward (same host, same user).
473///
474/// Returns `None` when `block_id` isn't in the shared registry at all, or
475/// every matching entry is filtered out (not loopback, or a stale
476/// self-entry pointing at THIS instance) — the caller falls through to the
477/// normal local "not running" error in that case, same message as before
478/// this feature existed. `Some((agent_name, outcome))` otherwise.
479pub(crate) async fn forward_stop_to_shared_channel(
480    state: &AppState,
481    block_id: &str,
482    signal: Option<&str>,
483    by: &str,
484) -> Option<(String, Result<(), String>)> {
485    let entry = shared_channel_for(state, block_id)?;
486
487    let url = format!("{}/agentmux/agent/stop", entry.local_url);
488    let mut req = state.http_client.post(&url).json(&serde_json::json!({
489        "block_id": block_id,
490        "signal": signal,
491        "by": by,
492    }));
493    if !entry.auth_key.is_empty() {
494        req = req.header(AUTH_KEY_HEADER, &entry.auth_key);
495    }
496    let outcome = async {
497        let resp = req
498            .send()
499            .await
500            .map_err(|e| format!("cross-channel forward failed: {e}"))?;
501        if !resp.status().is_success() {
502            return Err(format!("cross-channel forward: HTTP {}", resp.status()));
503        }
504        let body: serde_json::Value = resp
505            .json()
506            .await
507            .map_err(|e| format!("cross-channel forward: response parse failed: {e}"))?;
508        if body.get("success").and_then(|v| v.as_bool()) == Some(true) {
509            // An instance with the keep-running window opened one: the stop is done when its user lets it run out.
510            match body["pending"]["request_id"].as_str() {
511                Some(request_id) => wait_for_remote_window(state, &entry.local_url, &entry.auth_key, request_id).await,
512                None => Ok(()),
513            }
514        } else {
515            Err(body
516                .get("error")
517                .and_then(|v| v.as_str())
518                .unwrap_or("cross-channel forward failed")
519                .to_string())
520        }
521    }
522    .await;
523
524    Some((entry.agent_id, outcome))
525}
526
527/// Wait for the other instance's user to let its keep-running window run out (or keep the agent running).
528pub(crate) async fn wait_for_remote_window(state: &AppState, local_url: &str, auth_key: &str, request_id: &str) -> Result<(), String> {
529    let url = format!("{}/api/v1/agent/shutdown/{request_id}", local_url.trim_end_matches('/'));
530    let give_up = std::time::Instant::now() + crate::sagas::pending_shutdown::OVERRIDE_WINDOW + std::time::Duration::from_secs(15);
531    loop {
532        let mut req = state.http_client.get(&url);
533        if !auth_key.is_empty() {
534            req = req.header(AUTH_KEY_HEADER, auth_key);
535        }
536        let body: serde_json::Value = match req.send().await {
537            Ok(r) => r.json().await.unwrap_or_default(),
538            Err(e) => return Err(format!("cross-channel forward: lost the other AgentMux while it waited for its user: {e}")),
539        };
540        match body["status"].as_str() {
541            Some("shut_down") | Some("superseded") => return Ok(()),
542            Some("kept_by_user") => return Err("kept running by the user of the AgentMux running it".to_string()),
543            Some("failed") => return Err(body["error"].as_str().unwrap_or("the stop failed there").to_string()),
544            _ => {}
545        }
546        if std::time::Instant::now() >= give_up {
547            return Err("cross-channel forward: the other AgentMux's user did not answer in time".to_string());
548        }
549        tokio::time::sleep(std::time::Duration::from_millis(300)).await;
550    }
551}
552
553pub(crate) async fn fleet_bulk_stop_impl(
554    state: &AppState,
555    targets: Vec<String>,
556    signal: Option<&str>,
557    staged: Option<StagePlanInput>,
558) -> FleetActionResult {
559    let mut result = FleetActionResult::default();
560    let batch_size = staged.as_ref().map(|s| s.batch_size.max(1)).unwrap_or(targets.len().max(1));
561    let max_fail_percentage = staged.as_ref().map(|s| s.max_fail_percentage);
562
563    let mut iter = targets.into_iter().peekable();
564    'batches: while iter.peek().is_some() {
565        let batch: Vec<String> = (&mut iter).take(batch_size).collect();
566        let batch_len = batch.len();
567        let mut batch_failures = 0usize;
568        // All of the batch at once: a target on another instance waits for that instance's user, and the
569        // windows must run side by side rather than one after another.
570        let stops = batch.into_iter().map(|block_id| async move {
571            // Local (this instance's own in-process controller registry)
572            // first — unchanged, fast path. Only reach for the shared
573            // cross-channel registry when nothing local matches
574            // (REPORT_CROSS_INSTANCE_CONTROL_ROBUSTNESS_AUDIT_2026_08_22.md
575            // §3.2 — this was host-tier-only before).
576            let (target_agent, outcome) = match state.reactive_handler.get_agent_by_block(&block_id) {
577                Some(agent) => (agent.agent_id, stop_one_agent_block(state, &block_id, signal, None).await.map(|_| ())),
578                None => match forward_stop_to_shared_channel(state, &block_id, signal, "").await {
579                    Some((agent_name, outcome)) => (agent_name, outcome),
580                    None => (block_id.clone(), stop_one_agent_block(state, &block_id, signal, None).await.map(|_| ())),
581                },
582            };
583            (block_id, target_agent, outcome)
584        });
585        for (block_id, target_agent, outcome) in futures_util::future::join_all(stops).await {
586            let request_id = uuid::Uuid::new_v4().to_string();
587            match outcome {
588                Ok(()) => {
589                    state.reactive_handler.log_fleet_action_audit(
590                        None, &target_agent, &block_id, FLEET_BULK_STOP_AUDIT_ACTION,
591                        true, None, &request_id, None,
592                    );
593                    result.succeeded.push(block_id);
594                }
595                Err(e) => {
596                    state.reactive_handler.log_fleet_action_audit(
597                        None, &target_agent, &block_id, FLEET_BULK_STOP_AUDIT_ACTION,
598                        false, Some(&e), &request_id, None,
599                    );
600                    batch_failures += 1;
601                    result.failed.push(FleetActionFailure { id: block_id, error: e });
602                }
603            }
604        }
605        if let Some(max_pct) = max_fail_percentage {
606            if exceeds_fail_threshold(batch_failures, batch_len, max_pct) {
607                // Remaining, untried targets are recorded as failed so the
608                // caller's succeeded+failed count always equals the
609                // original target count — never a silently-dropped subset.
610                let mut skipped_any = false;
611                for remaining in iter {
612                    skipped_any = true;
613                    result.failed.push(FleetActionFailure {
614                        id: remaining,
615                        error: "skipped: staged rollout aborted after a prior batch's failure rate exceeded max_fail_percentage".to_string(),
616                    });
617                }
618                // Only a genuine early abort if something was actually left
619                // unattempted — tripping the threshold on the final batch
620                // ran the whole list, so it isn't "early" at all.
621                result.aborted_early = skipped_any;
622                break 'batches;
623            }
624        }
625    }
626    result
627}
628
629/// The shared cross-channel registry entry for `block_id` on ANOTHER
630/// instance on this machine: loopback only, never this instance itself.
631pub(crate) fn shared_channel_for(state: &AppState, block_id: &str) -> Option<crate::backend::reactive::registry::AgentEntry> {
632    let shared_dir = crate::registry::resolve_shared_reactive_dir()?;
633    let entry = crate::backend::reactive::registry::list_all_shared(&shared_dir)
634        .into_iter()
635        .find(|e| e.block_id == block_id)?;
636    let is_loopback = entry.local_url.starts_with("http://127.0.0.1")
637        || entry.local_url.starts_with("http://localhost")
638        || entry.local_url.starts_with("http://[::1]");
639    if !is_loopback || entry.local_url == state.local_web_url {
640        return None;
641    }
642    Some(entry)
643}
644
645/// What asking another instance's user came to.
646enum Forwarded {
647    /// That instance opened (or joined) its own override window.
648    Pending(crate::sagas::pending_shutdown::PendingView),
649    /// That instance predates the window: stopped at once, as before.
650    Immediate(Result<(), String>),
651    /// It answered, but couldn't take the request (e.g. not running there).
652    Refused(String),
653}
654
655/// A cross-channel `FleetBulkStop` target: ask ITS instance's user
656/// (`/agentmux/agent/stop-pending`), whose banner, chime and Keep running
657/// are the ones that user sees. The request's status is served from there;
658/// `pending_shutdown::remember_remote` lets this instance proxy it. An
659/// instance without that route (404) gets the plain forward it always did.
660async fn forward_stop_pending(
661    state: &AppState,
662    entry: &crate::backend::reactive::registry::AgentEntry,
663    block_id: &str,
664    by: &str,
665    signal: Option<&str>,
666    close: bool,
667) -> Forwarded {
668    let url = format!("{}/agentmux/agent/stop-pending", entry.local_url);
669    // `mode` is new: an instance that predates it ignores it and only stops,
670    // which its answer shows (no `effect`).
671    let mut req = state.http_client.post(&url).json(&serde_json::json!({
672        "block_id": block_id,
673        "signal": signal,
674        "by": by,
675        "mode": if close { "close" } else { "stop" },
676    }));
677    if !entry.auth_key.is_empty() {
678        req = req.header(AUTH_KEY_HEADER, &entry.auth_key);
679    }
680    let resp = match req.send().await {
681        Ok(r) => r,
682        Err(e) => return Forwarded::Refused(format!("cross-channel forward failed: {e}")),
683    };
684    if resp.status() == reqwest::StatusCode::NOT_FOUND {
685        let outcome = forward_stop_to_shared_channel(state, block_id, signal, by)
686            .await
687            .map(|(_, o)| o)
688            .unwrap_or_else(|| Err("cross-channel forward: target vanished".to_string()));
689        return Forwarded::Immediate(outcome);
690    }
691    if !resp.status().is_success() {
692        return Forwarded::Refused(format!("cross-channel forward: HTTP {}", resp.status()));
693    }
694    let body: serde_json::Value = match resp.json().await {
695        Ok(b) => b,
696        Err(e) => return Forwarded::Refused(format!("cross-channel forward: response parse failed: {e}")),
697    };
698    if body["success"] != true {
699        return Forwarded::Refused(body["error"].as_str().unwrap_or("cross-channel forward failed").to_string());
700    }
701    let p = &body["pending"];
702    let Some(request_id) = p["request_id"].as_str() else {
703        return Forwarded::Refused("cross-channel forward: no request id".to_string());
704    };
705    crate::sagas::pending_shutdown::remember_remote(request_id, &entry.local_url, &entry.auth_key);
706    Forwarded::Pending(crate::sagas::pending_shutdown::PendingView {
707        request_id: request_id.to_string(),
708        block_id: block_id.to_string(),
709        by: p["by"].as_str().unwrap_or(by).to_string(),
710        target: entry.agent_id.clone(),
711        via: p["via"].as_str().unwrap_or("FleetBulkStop").to_string(),
712        reason: String::new(),
713        effect: match p["effect"].as_str() {
714            Some("close_tab") => "close_tab",
715            Some("close_pane") => "close_pane",
716            _ => "stop",
717        },
718        deadline_ms: p["deadline_ms"].as_i64().unwrap_or_default(),
719        status: "pending",
720        error: None,
721        blocks: None,
722        outcomes: None,
723        joined: p["joined"].as_bool().unwrap_or(false),
724    })
725}
726
727/// Stop agents and KEEP their panes, behind the user's 30 s override. Internal
728/// only, since `Stop agents` closes the tab (`fleet_close_agents_with_override`):
729/// the fork slug migration, which restarts the agents in the same panes, and
730/// `Agents stop` of another agent are its callers. Every target running on
731/// this instance waits for its user's 30 s override, all windows in parallel
732/// (docs/specs/SPEC_AGENT_SELF_QUIT_2026_09_24.md §6.5). A target running on
733/// another instance on this machine is asked there, in that instance's own
734/// window (`forward_stop_pending`). Targets running nowhere go through
735/// `fleet_bulk_stop_impl` as before, `staged` included.
736pub(crate) async fn fleet_stop_keep_pane_with_override(
737    state: &AppState,
738    by: &str,
739    targets: Vec<String>,
740    signal: Option<&str>,
741    staged: Option<StagePlanInput>,
742) -> (FleetActionResult, Vec<crate::sagas::pending_shutdown::PendingView>) {
743    fleet_stop_keep_pane_with_override_opts(state, by, targets, signal, None, staged).await
744}
745
746/// [`fleet_stop_keep_pane_with_override`] with the caller's explicit `stop_background`
747/// (`None`: the user's setting), carried through the window to the stop.
748pub(crate) async fn fleet_stop_keep_pane_with_override_opts(
749    state: &AppState,
750    by: &str,
751    targets: Vec<String>,
752    signal: Option<&str>,
753    stop_background: Option<bool>,
754    staged: Option<StagePlanInput>,
755) -> (FleetActionResult, Vec<crate::sagas::pending_shutdown::PendingView>) {
756    let (local, other): (Vec<String>, Vec<String>) = targets
757        .into_iter()
758        .partition(|b| crate::backend::blockcontroller::get_controller(b).is_some());
759    let mut pending: Vec<crate::sagas::pending_shutdown::PendingView> = local
760        .iter()
761        .map(|block_id| {
762            let mut v = crate::sagas::pending_shutdown::request(
763                state,
764                block_id,
765                by,
766                "FleetBulkStop",
767                "",
768                crate::sagas::pending_shutdown::Action::Stop { signal: signal.map(str::to_string), stop_background },
769            );
770            // A target can join a request opened for another block (its
771            // pane's close, via a sibling tab): audit and report it under the
772            // block this caller named (ReAgent P1 on #3798), with that
773            // request's id.
774            let target = state
775                .reactive_handler
776                .get_agent_by_block(block_id)
777                .map(|a| a.agent_id)
778                .unwrap_or_else(|| block_id.clone());
779            state.reactive_handler.log_fleet_action_audit(
780                Some(by), &target, block_id, FLEET_BULK_STOP_AUDIT_ACTION,
781                true, None, &v.request_id, Some(&crate::sagas::pending_shutdown::audit_note(state, &v, by, "FleetBulkStop")),
782            );
783            v.block_id = block_id.clone();
784            v.target = target;
785            v
786        })
787        .collect();
788    let mut nowhere = Vec::new();
789    // Local windows are open (above); now ask the other instances, all at
790    // once, so one slow peer delays neither the rest nor any countdown
791    // (ReAgent P1 on #3824).
792    let mut forwards = Vec::new();
793    for block_id in other {
794        match shared_channel_for(state, &block_id) {
795            Some(entry) => forwards.push((block_id, entry)),
796            None => nowhere.push(block_id),
797        }
798    }
799    let (mut now, remote_pending, _) = ask_other_instances(state, by, signal, false, forwards).await;
800    pending.extend(remote_pending);
801    if !nowhere.is_empty() {
802        let rest = fleet_bulk_stop_impl(state, nowhere, signal, staged).await;
803        now.succeeded.extend(rest.succeeded);
804        now.failed.extend(rest.failed);
805        now.aborted_early = rest.aborted_early;
806    }
807    (now, pending)
808}
809
810/// Ask each target's own instance (a target running on another AgentMux on
811/// this machine) to open its override window, all at once. `close`: ask for
812/// the tab to close (`Stop agents`) rather than only stop (the migration).
813/// The third answer lists the targets of a `close` that an instance predating
814/// the override only stopped at once, leaving the pane open.
815async fn ask_other_instances(
816    state: &AppState,
817    by: &str,
818    signal: Option<&str>,
819    close: bool,
820    forwards: Vec<(String, crate::backend::reactive::registry::AgentEntry)>,
821) -> (FleetActionResult, Vec<crate::sagas::pending_shutdown::PendingView>, Vec<String>) {
822    let mut now = FleetActionResult::default();
823    let mut remote_pending = Vec::new();
824    let mut left_open = Vec::new();
825    let answers = futures_util::future::join_all(
826        forwards.iter().map(|(block_id, entry)| forward_stop_pending(state, entry, block_id, by, signal, close)),
827    )
828    .await;
829    for ((block_id, entry), answer) in forwards.into_iter().zip(answers) {
830        let request_id = uuid::Uuid::new_v4().to_string();
831        match answer {
832            Forwarded::Pending(v) => {
833                state.reactive_handler.log_fleet_action_audit(
834                    Some(by), &entry.agent_id, &block_id, FLEET_BULK_STOP_AUDIT_ACTION,
835                    true, None, &v.request_id,
836                    Some(&format!("pending user override on channel {}", entry.channel)),
837                );
838                remote_pending.push(v);
839            }
840            Forwarded::Immediate(outcome) => {
841                let left = if close { "; its pane was left open" } else { "" };
842                let note = format!("channel {} predates the user override: stopped at once{left}", entry.channel);
843                state.reactive_handler.log_fleet_action_audit(
844                    Some(by), &entry.agent_id, &block_id, FLEET_BULK_STOP_AUDIT_ACTION,
845                    outcome.is_ok(), outcome.as_ref().err().map(String::as_str), &request_id, Some(&note),
846                );
847                match outcome {
848                    Ok(()) => {
849                        if close {
850                            left_open.push(block_id.clone());
851                        }
852                        now.succeeded.push(block_id)
853                    }
854                    Err(error) => now.failed.push(FleetActionFailure { id: block_id, error }),
855                }
856            }
857            Forwarded::Refused(error) => {
858                state.reactive_handler.log_fleet_action_audit(
859                    Some(by), &entry.agent_id, &block_id, FLEET_BULK_STOP_AUDIT_ACTION,
860                    false, Some(&error), &request_id, None,
861                );
862                now.failed.push(FleetActionFailure { id: block_id, error });
863            }
864        }
865    }
866    (now, remote_pending, left_open)
867}
868
869/// `Stop agents`, from an agent: close each target agent's tab, as the user's
870/// tab × does, after the same 30 s override window as any other shutdown the
871/// user didn't ask for (docs/specs/SPEC_STOP_AN_AGENT_ONE_WAY_AND_SHUTDOWN_TOAST_2026_10_23.md
872/// §3.1). The targets no request covers yet share one window, with one notification and one audit
873/// entry (`request_batch`), and the user can keep any one of them; a target that already has a window
874/// joins it. Only that agent's tab closes, so an agent stacked in the same pane keeps running.
875///
876/// Refused up front, as `failed` with a pointer: the caller's own block (that
877/// is `Stop self`), and a block that is not an agent's (that is `Stop pane`).
878/// A target on another AgentMux instance on this machine is asked there. The
879/// third answer lists targets that an older instance only stopped at once, so
880/// the caller can say their panes were left open.
881pub(crate) async fn fleet_close_agents_with_override(
882    state: &AppState,
883    by: &str,
884    caller_block: Option<&str>,
885    targets: Vec<String>,
886) -> (FleetActionResult, Vec<crate::sagas::pending_shutdown::PendingView>, Vec<String>) {
887    let mut now = FleetActionResult::default();
888    let mut pending: Vec<crate::sagas::pending_shutdown::PendingView> = Vec::new();
889    let mut forwards = Vec::new();
890    let mut agents: Vec<String> = Vec::new();
891    let mut seen = std::collections::HashSet::new();
892    for block_id in targets {
893        if !seen.insert(block_id.clone()) {
894            continue;
895        }
896        if caller_block == Some(block_id.as_str()) {
897            now.failed.push(FleetActionFailure {
898                id: block_id,
899                error: "your own block: Stop agents closes other agents; to end your own session use Stop with action \"self\"".to_string(),
900            });
901            continue;
902        }
903        let here = state.srv_state.lock().await.blocks.contains_key(&block_id);
904        if !here {
905            match shared_channel_for(state, &block_id) {
906                Some(entry) => forwards.push((block_id, entry)),
907                None => now.failed.push(FleetActionFailure { id: block_id.clone(), error: format!("block not found: {block_id}") }),
908            }
909            continue;
910        }
911        if !crate::sagas::orphan_reaper::is_agent_block(state, &block_id) {
912            now.failed.push(FleetActionFailure {
913                id: block_id,
914                error: "not an agent pane: close it with Stop with action \"pane\"".to_string(),
915            });
916            continue;
917        }
918        agents.push(block_id);
919    }
920    // One window for the agents no request covers yet (a batch); a target that has one joins it.
921    let detail = format!("asked by {by} (Stop agents)");
922    let mut audited = std::collections::HashSet::new();
923    for (block_id, mut v) in agents.clone().into_iter().zip(crate::sagas::pending_shutdown::request_batch(state, &agents, by, "", &detail)) {
924        let target = state.reactive_handler.get_agent_by_block(&block_id).map(|a| a.agent_id).unwrap_or_else(|| block_id.clone());
925        // One entry per window: a batch is one `FleetBulkStop` naming every agent in it.
926        if v.blocks.is_none() || audited.insert(v.request_id.clone()) {
927            let (named, note) = match v.blocks.as_ref() {
928                Some(blocks) => (
929                    v.target.clone(),
930                    format!(
931                        "{} | closing {} agents: {}",
932                        crate::sagas::pending_shutdown::audit_note(state, &v, by, "FleetBulkStop"),
933                        blocks.len(),
934                        blocks.iter().map(|b| b.block_id.as_str()).collect::<Vec<_>>().join(", ")
935                    ),
936                ),
937                None => (target.clone(), crate::sagas::pending_shutdown::audit_note(state, &v, by, "FleetBulkStop")),
938            };
939            state.reactive_handler.log_fleet_action_audit(Some(by), &named, &block_id, FLEET_BULK_STOP_AUDIT_ACTION, true, None, &v.request_id, Some(&note));
940        }
941        // A target can join a request opened for another block (its pane's
942        // close, via a sibling tab): report it under the block named.
943        v.block_id = block_id;
944        v.target = target;
945        pending.push(v);
946    }
947    let (asked, remote_pending, left_open) = ask_other_instances(state, by, None, true, forwards).await;
948    now.succeeded.extend(asked.succeeded);
949    now.failed.extend(asked.failed);
950    // `Stop agents` doesn't wait for the windows: the caller is told by a note if the user keeps an
951    // agent or a close fails. One note per window, however many of its agents are in the request.
952    for v in &pending {
953        crate::sagas::pending_shutdown::tell_when_settled(state, &v.request_id, by, "FleetBulkStop");
954    }
955    for v in &remote_pending {
956        watch_remote_window(state, by, v);
957    }
958    pending.extend(remote_pending);
959    (now, pending, left_open)
960}
961
962/// A close asked of another AgentMux on this machine: its user's window runs there, so this instance
963/// watches it and tells `by` by note if that user keeps the agent or the close fails.
964fn watch_remote_window(state: &AppState, by: &str, v: &crate::sagas::pending_shutdown::PendingView) {
965    let Some(remote) = crate::sagas::pending_shutdown::remote_for(&v.request_id) else { return };
966    let (state, by, request_id, target) = (state.clone(), by.to_string(), v.request_id.clone(), v.target.clone());
967    tokio::spawn(async move {
968        let Err(why) = wait_for_remote_window(&state, &remote.local_url, &remote.auth_key, &request_id).await else { return };
969        let text = format!("[AgentMux] Your Stop agents (request {request_id}): {target} was not closed: {why}.");
970        if let Err(e) = state.reactive_handler.hold_system_note(&by, &format!("shutdown:{request_id}"), &text) {
971            tracing::debug!(by, request_id, "shutdown note not held: {e}");
972        }
973    });
974}
975
976/// `batch_failures / batch_len` (as a percentage) exceeds `max_pct`.
977/// Cross-multiplies instead of computing a truncated integer percentage
978/// first — `batch_failures * 100 / batch_len` rounds DOWN before
979/// comparing, so e.g. 1 failure in a batch of 3 (33.3%) reads as 33 and
980/// never exceeds `max_pct = 33`, silently missing the threshold it was
981/// meant to catch (Codex P2, PR #2687 review). `batch_failures * 100 >
982/// max_pct * batch_len` is the same inequality with no rounding.
983fn exceeds_fail_threshold(batch_failures: usize, batch_len: usize, max_pct: u8) -> bool {
984    batch_failures * 100 > max_pct as usize * batch_len
985}
986
987#[cfg(test)]
988mod threshold_tests {
989    use super::exceeds_fail_threshold;
990
991    #[test]
992    fn one_in_three_at_33_percent_threshold_now_trips() {
993        // 1/3 = 33.33...% — the old truncated-integer comparison rounded
994        // this down to exactly 33 and never exceeded max_pct=33. The real
995        // rate DOES exceed 33%, so this must trip.
996        assert!(exceeds_fail_threshold(1, 3, 33));
997    }
998
999    #[test]
1000    fn one_in_three_at_34_percent_threshold_does_not_trip() {
1001        // 33.33% does not exceed a 34% threshold.
1002        assert!(!exceeds_fail_threshold(1, 3, 34));
1003    }
1004
1005    #[test]
1006    fn zero_failures_never_trips() {
1007        assert!(!exceeds_fail_threshold(0, 10, 0));
1008    }
1009
1010    #[test]
1011    fn all_failures_trips_any_threshold_below_100() {
1012        assert!(exceeds_fail_threshold(5, 5, 99));
1013        assert!(!exceeds_fail_threshold(5, 5, 100));
1014    }
1015
1016    #[test]
1017    fn two_in_seven_at_28_percent_threshold() {
1018        // 2/7 = 28.57...% — exceeds a 28% threshold, does not exceed 29%.
1019        assert!(exceeds_fail_threshold(2, 7, 28));
1020        assert!(!exceeds_fail_threshold(2, 7, 29));
1021    }
1022}
1023
1024use agentmux_common::time::now_ms;
1025
1026fn register_fleet_group_create(engine: &Arc<WshRpcEngine>, state: &AppState) {
1027    let mstore = state.mstore.clone();
1028    engine.register_typed(
1029        COMMAND_FLEET_GROUP_CREATE,
1030        move |cmd: CommandFleetGroupCreateData, _ctx| {
1031            let mstore = mstore.clone();
1032            async move {
1033                if cmd.name.trim().is_empty() {
1034                    return Err("fleet.group.create: name is required".to_string());
1035                }
1036                let id = uuid::Uuid::new_v4().to_string();
1037                let created_at = now_ms();
1038                mstore
1039                    .agent_group_create(&id, cmd.name.trim(), &cmd.member_ids, created_at)
1040                    .map_err(|e| format!("fleet.group.create: {e}"))?;
1041                Ok(FleetGroup {
1042                    id,
1043                    name: cmd.name.trim().to_string(),
1044                    member_ids: cmd.member_ids,
1045                    created_at,
1046                })
1047            }
1048        },
1049    );
1050}
1051
1052fn register_fleet_group_list(engine: &Arc<WshRpcEngine>, state: &AppState) {
1053    let mstore = state.mstore.clone();
1054    engine.register_typed(
1055        COMMAND_FLEET_GROUP_LIST,
1056        move |_req: CommandFleetGroupListData, _ctx| {
1057            let mstore = mstore.clone();
1058            async move {
1059                let groups = mstore.agent_group_list().map_err(|e| format!("fleet.group.list: {e}"))?;
1060                let groups = groups
1061                    .into_iter()
1062                    .map(|g| FleetGroup { id: g.id, name: g.name, member_ids: g.member_ids, created_at: g.created_at })
1063                    .collect();
1064                Ok(FleetGroupListResult { groups })
1065            }
1066        },
1067    );
1068}
1069
1070fn register_fleet_group_update(engine: &Arc<WshRpcEngine>, state: &AppState) {
1071    let mstore = state.mstore.clone();
1072    engine.register_typed(
1073        COMMAND_FLEET_GROUP_UPDATE,
1074        move |cmd: CommandFleetGroupUpdateData, _ctx| {
1075            let mstore = mstore.clone();
1076            async move {
1077                let name = cmd.name.as_deref().map(|n| n.trim());
1078                if matches!(name, Some("")) {
1079                    return Err("fleet.group.update: name cannot be blank".to_string());
1080                }
1081                let updated = mstore
1082                    .agent_group_update(&cmd.id, name, cmd.member_ids.as_deref())
1083                    .map_err(|e| format!("fleet.group.update: {e}"))?;
1084                if !updated {
1085                    return Err(format!("fleet.group.update: no group with id {}", cmd.id));
1086                }
1087                let group = mstore
1088                    .agent_group_get(&cmd.id)
1089                    .map_err(|e| format!("fleet.group.update: {e}"))?
1090                    .ok_or_else(|| format!("fleet.group.update: group {} vanished after update", cmd.id))?;
1091                Ok(FleetGroup {
1092                    id: group.id,
1093                    name: group.name,
1094                    member_ids: group.member_ids,
1095                    created_at: group.created_at,
1096                })
1097            }
1098        },
1099    );
1100}
1101
1102fn register_fleet_group_delete(engine: &Arc<WshRpcEngine>, state: &AppState) {
1103    let mstore = state.mstore.clone();
1104    engine.register_typed(
1105        COMMAND_FLEET_GROUP_DELETE,
1106        move |cmd: CommandFleetGroupDeleteData, _ctx| {
1107            let mstore = mstore.clone();
1108            async move {
1109                let deleted = mstore.agent_group_delete(&cmd.id).map_err(|e| format!("fleet.group.delete: {e}"))?;
1110                Ok(FleetGroupDeleteResult { ok: deleted })
1111            }
1112        },
1113    );
1114}
1115
1116#[cfg(test)]
1117mod override_tests {
1118    use super::*;
1119    use std::sync::atomic::{AtomicBool, Ordering};
1120
1121    /// A running agent that records whether it was stopped.
1122    struct Stoppable {
1123        block_id: String,
1124        stopped: Arc<AtomicBool>,
1125    }
1126
1127    impl crate::backend::blockcontroller::Controller for Stoppable {
1128        fn start(&self, _: crate::backend::obj::MetaMapType, _: Option<serde_json::Value>, _: bool) -> Result<(), String> {
1129            Ok(())
1130        }
1131        fn stop(&self, _: bool, _: &str) -> Result<(), String> {
1132            self.stopped.store(true, Ordering::SeqCst);
1133            Ok(())
1134        }
1135        fn get_runtime_status(&self) -> crate::backend::blockcontroller::BlockControllerRuntimeStatus {
1136            crate::backend::blockcontroller::BlockControllerRuntimeStatus { blockid: self.block_id.clone(), ..Default::default() }
1137        }
1138        fn send_input(&self, _: crate::backend::blockcontroller::BlockInputUnion, _: Option<u64>) -> Result<(), String> {
1139            Ok(())
1140        }
1141        fn controller_type(&self) -> &str {
1142            "stub"
1143        }
1144        fn block_id(&self) -> &str {
1145            &self.block_id
1146        }
1147        fn as_any(&self) -> &dyn std::any::Any {
1148            self
1149        }
1150    }
1151
1152    fn running(prefix: &str) -> (String, Arc<AtomicBool>) {
1153        let block_id = format!("{prefix}-{}", uuid::Uuid::new_v4());
1154        let stopped = Arc::new(AtomicBool::new(false));
1155        crate::backend::blockcontroller::register_controller(
1156            &block_id,
1157            Arc::new(Stoppable { block_id: block_id.clone(), stopped: stopped.clone() }),
1158        );
1159        (block_id, stopped)
1160    }
1161
1162    #[tokio::test]
1163    async fn an_agent_s_bulk_stop_waits_for_each_user_and_stops_when_nobody_keeps_it() {
1164        let state = crate::server::tests::test_state();
1165        let (a, a_stopped) = running("bulk-override-a");
1166        let (b, b_stopped) = running("bulk-override-b");
1167        let gone = format!("bulk-override-gone-{}", uuid::Uuid::new_v4());
1168
1169        let (now, pending) =
1170            fleet_stop_keep_pane_with_override(&state, "Korp", vec![a.clone(), b.clone(), gone.clone()], None, None).await;
1171        assert_eq!(now.failed.iter().map(|f| f.id.clone()).collect::<Vec<_>>(), vec![gone], "not running: fails at once");
1172        assert_eq!(pending.iter().map(|p| p.block_id.clone()).collect::<Vec<_>>(), vec![a.clone(), b.clone()]);
1173        assert!(pending.iter().all(|p| p.by == "Korp" && p.via == "FleetBulkStop"));
1174        assert!(!a_stopped.load(Ordering::SeqCst) && !b_stopped.load(Ordering::SeqCst), "nothing stops during the window");
1175
1176        // The user keeps b; a's window runs out.
1177        assert_eq!(crate::sagas::pending_shutdown::keep(&state, &b, &pending[1].request_id), "kept_by_user");
1178        crate::sagas::pending_shutdown::expire_now(&pending[0].request_id);
1179        assert_eq!(crate::sagas::pending_shutdown::settled(&pending[0].request_id).await.status, "shut_down");
1180        assert_eq!(crate::sagas::pending_shutdown::settled(&pending[1].request_id).await.status, "kept_by_user");
1181        assert!(a_stopped.load(Ordering::SeqCst));
1182        assert!(!b_stopped.load(Ordering::SeqCst), "the user kept it");
1183        crate::backend::blockcontroller::delete_controller(&a);
1184        crate::backend::blockcontroller::delete_controller(&b);
1185    }
1186
1187    #[tokio::test]
1188    async fn a_target_that_joins_its_pane_s_pending_close_is_reported_under_its_own_block() {
1189        let state = crate::server::tests::test_state();
1190        let (tab, _) = running("bulk-join-tab");
1191        let sibling = format!("bulk-join-sibling-{}", uuid::Uuid::new_v4());
1192        let close = crate::sagas::pending_shutdown::request(
1193            &state,
1194            &sibling,
1195            "Korp",
1196            "ClosePane",
1197            "",
1198            crate::sagas::pending_shutdown::Action::ClosePane { block_ids: vec![sibling.clone(), tab.clone()] },
1199        );
1200
1201        let (_, pending) = fleet_stop_keep_pane_with_override(&state, "Posa", vec![tab.clone()], None, None).await;
1202        assert_eq!(pending.len(), 1);
1203        assert_eq!(pending[0].block_id, tab, "the block the caller named, not the sibling");
1204        assert_eq!(pending[0].request_id, close.request_id, "the pane's one window");
1205        assert!(pending[0].joined);
1206        crate::sagas::pending_shutdown::keep(&state, &sibling, &close.request_id);
1207        crate::backend::blockcontroller::delete_controller(&tab);
1208    }
1209}
1210
1211#[cfg(test)]
1212mod broadcast_core_tests {
1213    use super::*;
1214    use crate::server::app_api::fleet_pacing::Pace;
1215    use std::sync::{Arc, Mutex};
1216
1217    fn ids(n: usize) -> Vec<String> {
1218        (0..n).map(|i| format!("blk-{i}")).collect()
1219    }
1220
1221    fn agent_for(block: &str) -> Option<String> {
1222        block.strip_prefix("blk-").map(|n| format!("agent-{n}"))
1223    }
1224
1225    /// Owner decision 2026-10-06 (spec §6 q2): a broadcast is the user's own
1226    /// message, with the user's powers.
1227    #[test]
1228    fn broadcast_turns_are_attributed_to_the_user() {
1229        assert_eq!(MessageOrigin::broadcast().turn_origin(), TurnOrigin::User);
1230    }
1231
1232    #[tokio::test]
1233    async fn every_target_is_delivered_with_the_broadcast_origin() {
1234        let seen: Arc<Mutex<Vec<MessageOrigin>>> = Arc::default();
1235        let seen2 = seen.clone();
1236        let out = run_broadcast(ids(3), "hi", "m1", Pace::at_once(), agent_for, move |_b, _t, origin| {
1237            seen2.lock().unwrap().push(origin);
1238            async { Ok(()) }
1239        })
1240        .await;
1241        assert_eq!(out.len(), 3);
1242        assert!(seen.lock().unwrap().iter().all(|o| *o == MessageOrigin::broadcast() && o.turn_origin() == TurnOrigin::User));
1243    }
1244
1245    /// The self-quit gate passes an untainted broadcast turn whose text has the
1246    /// quoted instruction, exactly as it does a typed one; the quote check and
1247    /// the taint rule still apply.
1248    #[tokio::test]
1249    async fn the_self_quit_gate_accepts_a_broadcast_turn_like_a_typed_one() {
1250        use crate::backend::blockcontroller::health::TurnProvenance;
1251        use crate::sagas::self_quit::{gate, GateRefusal};
1252        let text = broadcast_turn_message("agent-1", 3, "m1", "finish the PR then quit");
1253        let p = |tainted| TurnProvenance { origin: MessageOrigin::broadcast().turn_origin(), tainted, user_text: Some(text.clone()), broadcast: true };
1254        assert_eq!(gate(Some(&p(false)), "then quit"), Ok(()));
1255        assert_eq!(gate(Some(&p(false)), "delete everything"), Err(GateRefusal::InstructionMismatch));
1256        assert_eq!(gate(Some(&p(true)), "then quit"), Err(GateRefusal::Tainted));
1257    }
1258
1259    #[tokio::test]
1260    async fn each_target_gets_its_own_header_with_a_shared_id_and_the_resolved_count() {
1261        let texts: Arc<Mutex<Vec<(String, String)>>> = Arc::default();
1262        let texts2 = texts.clone();
1263        // blk-1 resolves to nothing: three targets, two recipients.
1264        let resolve = |b: &str| if b == "blk-1" { None } else { agent_for(b) };
1265        let out = run_broadcast(ids(3), "great, merge on approval", "bcast-42", Pace::at_once(), resolve, move |b, t, _| {
1266            texts2.lock().unwrap().push((b, t));
1267            async { Ok(()) }
1268        })
1269        .await;
1270        assert_eq!(out.len(), 3);
1271        let texts = texts.lock().unwrap();
1272        assert_eq!(texts.len(), 2, "the unresolved target is not delivered to");
1273        for (block, text) in texts.iter() {
1274            let agent = agent_for(block).unwrap();
1275            let header = text.lines().next().unwrap();
1276            assert!(header.starts_with(&format!("[BROADCAST:FROM=user VIA=swarm TO={agent} RECIPIENTS=2 MSGID=bcast-42 TS=")), "{header}");
1277            assert_eq!(text.lines().nth(1), Some("great, merge on approval"));
1278        }
1279    }
1280
1281    #[tokio::test]
1282    async fn outcomes_are_per_target_in_order_and_an_unresolved_target_says_why() {
1283        let out = run_broadcast(
1284            vec!["blk-0".into(), "nope".into(), "blk-2".into()],
1285            "x",
1286            "m",
1287            Pace::at_once(),
1288            agent_for,
1289            |b, _t, _| async move { if b == "blk-2" { Err("no controller".to_string()) } else { Ok(()) } },
1290        )
1291        .await;
1292        let blocks: Vec<&str> = out.iter().map(|o| o.block_id.as_str()).collect();
1293        assert_eq!(blocks, vec!["blk-0", "nope", "blk-2"]);
1294        assert!(out[0].result.is_ok());
1295        assert!(out[1].result.as_ref().unwrap_err().contains("no registered agent"));
1296        assert!(out[1].agent_id.is_none());
1297        assert_eq!(out[2].result.as_ref().unwrap_err(), "no controller");
1298        assert_eq!(out[2].agent_id.as_deref(), Some("agent-2"));
1299    }
1300
1301    // Targets that cost this AgentMux nothing are not paced, however many (pacing itself: `fleet_pacing`'s tests).
1302    #[tokio::test]
1303    async fn a_large_broadcast_with_nothing_to_pace_goes_out_at_once() {
1304        let started = std::time::Instant::now();
1305        let out = run_broadcast(ids(25), "x", "m", Pace::at_once(), agent_for, |_b, _t, _| async { Ok(()) }).await;
1306        assert_eq!(out.iter().filter(|o| o.result.is_ok()).count(), 25);
1307        assert!(started.elapsed() < std::time::Duration::from_millis(900), "{:?}", started.elapsed());
1308    }
1309
1310    #[tokio::test]
1311    async fn no_targets_is_a_no_op() {
1312        let out = run_broadcast(vec![], "x", "m", Pace::at_once(), agent_for, |_b, _t, _| async { Ok(()) }).await;
1313        assert!(out.is_empty());
1314    }
1315}
1316
1317#[cfg(test)]
1318mod broadcast_action_tests {
1319    use super::*;
1320    use crate::backend::reactive::SenderDelivery;
1321    use crate::bootstrap::AgentRoute;
1322
1323    #[test]
1324    fn structured_channels_take_the_broadcast_without_a_new_turn() {
1325        // ACP, App Server and a running persistent agent all land here: the
1326        // regression ReAgent found on #4176 was that ACP had no branch at all.
1327        assert_eq!(broadcast_action(Ok(AgentRoute::Sent(SenderDelivery::Delivered))), BroadcastAction::Done);
1328        assert_eq!(broadcast_action(Ok(AgentRoute::Sent(SenderDelivery::Deferred))), BroadcastAction::Done);
1329    }
1330
1331    #[test]
1332    fn a_subprocess_or_unspawned_persistent_agent_gets_a_turn() {
1333        assert_eq!(broadcast_action(Ok(AgentRoute::StartTurn { subprocess: true })), BroadcastAction::StartTurn);
1334        assert_eq!(broadcast_action(Ok(AgentRoute::StartTurn { subprocess: false })), BroadcastAction::StartTurn);
1335    }
1336
1337    #[test]
1338    fn a_terminal_pane_is_refused_not_typed_into() {
1339        let BroadcastAction::Fail(e) = broadcast_action(Ok(AgentRoute::Sent(SenderDelivery::Pty))) else {
1340            panic!("a PTY target must fail");
1341        };
1342        assert!(e.contains("not typed into a shell"), "{e}");
1343    }
1344
1345    #[test]
1346    fn a_structured_controller_failure_is_reported_per_target() {
1347        assert_eq!(
1348            broadcast_action(Err("persistent process not running".into())),
1349            BroadcastAction::Fail("persistent process not running".into())
1350        );
1351    }
1352}
1353
1354#[cfg(test)]
1355mod forward_broadcast_tests {
1356    use super::*;
1357    use axum::routing::post;
1358    use std::sync::{Arc, Mutex};
1359
1360    type Seen = Arc<Mutex<Vec<(Option<String>, serde_json::Value)>>>;
1361
1362    /// A fake other channel: records each request's `X-AuthKey` and body, and
1363    /// answers with `status` and `reply`.
1364    async fn peer(status: axum::http::StatusCode, reply: serde_json::Value) -> (String, Seen) {
1365        let seen: Seen = Default::default();
1366        let s = seen.clone();
1367        let app = axum::Router::new().route(
1368            "/agentmux/agent/broadcast",
1369            post(move |headers: axum::http::HeaderMap, axum::Json(body): axum::Json<serde_json::Value>| {
1370                let (s, reply) = (s.clone(), reply.clone());
1371                async move {
1372                    let key = headers.get("X-AuthKey").and_then(|v| v.to_str().ok()).map(str::to_string);
1373                    s.lock().unwrap().push((key, body));
1374                    (status, axum::Json(reply))
1375                }
1376            }),
1377        );
1378        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1379        let url = format!("http://127.0.0.1:{}", listener.local_addr().unwrap().port());
1380        tokio::spawn(async move {
1381            let _ = axum::serve(listener, app).await;
1382        });
1383        (url, seen)
1384    }
1385
1386    fn forward<'a>() -> BroadcastForward<'a> {
1387        BroadcastForward { block_id: "blk-loap", body: "merge on approval", msg_id: "m-1", recipients: 3 }
1388    }
1389
1390    #[tokio::test]
1391    async fn the_caller_sends_the_body_and_counts_and_never_a_header() {
1392        let (url, seen) = peer(axum::http::StatusCode::OK, serde_json::json!({ "success": true })).await;
1393        let out = forward_broadcast_to_channel(&reqwest::Client::new(), &url, "chan-key", &forward()).await;
1394        assert_eq!(out, Ok(()));
1395        let seen = seen.lock().unwrap();
1396        assert_eq!(seen[0].0.as_deref(), Some("chan-key"), "that channel's own key");
1397        let mut keys: Vec<&str> = seen[0].1.as_object().unwrap().keys().map(String::as_str).collect();
1398        keys.sort_unstable();
1399        assert_eq!(keys, ["block_id", "body", "msg_id", "recipients"], "no header field for a caller to forge");
1400        assert_eq!(seen[0].1["body"], "merge on approval");
1401        assert_eq!(seen[0].1["recipients"], 3);
1402    }
1403
1404    #[tokio::test]
1405    async fn a_channel_that_cannot_take_it_says_why_for_that_target_only() {
1406        let (url, _) = peer(axum::http::StatusCode::OK, serde_json::json!({ "success": false, "error": "no registered agent" })).await;
1407        assert_eq!(
1408            forward_broadcast_to_channel(&reqwest::Client::new(), &url, "", &forward()).await,
1409            Err("no registered agent".to_string())
1410        );
1411    }
1412
1413    #[tokio::test]
1414    async fn a_channel_from_before_the_route_is_named_as_an_older_build() {
1415        let (url, _) = peer(axum::http::StatusCode::NOT_FOUND, serde_json::json!({})).await;
1416        let Err(e) = forward_broadcast_to_channel(&reqwest::Client::new(), &url, "", &forward()).await else {
1417            panic!("a 404 must fail the target");
1418        };
1419        assert!(e.contains("older build"), "{e}");
1420    }
1421
1422    #[tokio::test]
1423    async fn a_missing_key_sends_no_key_header() {
1424        let (url, seen) = peer(axum::http::StatusCode::OK, serde_json::json!({ "success": true })).await;
1425        forward_broadcast_to_channel(&reqwest::Client::new(), &url, "", &forward()).await.unwrap();
1426        assert_eq!(seen.lock().unwrap()[0].0, None);
1427    }
1428
1429    #[tokio::test]
1430    async fn an_unreachable_channel_fails_the_target() {
1431        let Err(e) = forward_broadcast_to_channel(&reqwest::Client::new(), "http://127.0.0.1:9", "", &forward()).await else {
1432            panic!("nothing listens there");
1433        };
1434        assert!(e.starts_with("cross-channel forward failed"), "{e}");
1435    }
1436
1437    #[tokio::test]
1438    async fn the_receiver_refuses_a_block_it_has_no_agent_for() {
1439        let state = crate::server::tests::test_state();
1440        assert_eq!(
1441            deliver_forwarded_broadcast(&state, "no-such-block", "hi", "m-1", 1).await,
1442            Err(NO_REGISTERED_AGENT.to_string())
1443        );
1444    }
1445}