Skip to main content

agentmux_srv/server/service/
stop_requests.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the service route's `QuitAgent` and `ShutdownAgent` may ask of the person: the same who-may-stop-whom as
5//! `Stop agents` (asked by an agent the token names, of an agent's pane that is not the caller's own), one countdown
6//! per agent, and a limit on the countdowns one caller opens.
7
8use std::collections::{HashMap, VecDeque};
9use std::sync::{LazyLock, Mutex};
10
11use crate::backend::obj::Block;
12use crate::backend::service::WebReturnType;
13use crate::server::AppState;
14use agentmux_common::time::now_ms;
15
16/// The countdowns an agent may open in `WINDOW_MS`.
17const WINDOW_MS: i64 = 60_000;
18const AGENT_OPENS: usize = 10;
19
20/// When each caller opened its countdowns inside the window, oldest first.
21#[derive(Default)]
22struct Limiter(Mutex<HashMap<String, VecDeque<i64>>>);
23
24impl Limiter {
25    /// Whether `key` may open another countdown, or how many ms until its oldest one leaves the window. Counts nothing.
26    fn room(&self, key: &str, limit: usize, now: i64) -> Result<(), i64> {
27        let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner());
28        Self::forget_old(&mut map, now);
29        match map.get(key) {
30            Some(opened) if opened.len() >= limit => Err(WINDOW_MS - (now - opened[0])),
31            _ => Ok(()),
32        }
33    }
34
35    /// Counts a countdown `key` opened.
36    fn charge(&self, key: &str, now: i64) {
37        let mut map = self.0.lock().unwrap_or_else(|e| e.into_inner());
38        Self::forget_old(&mut map, now);
39        map.entry(key.to_string()).or_default().push_back(now);
40    }
41
42    fn forget_old(map: &mut HashMap<String, VecDeque<i64>>, now: i64) {
43        map.retain(|_, opened| {
44            while opened.front().is_some_and(|t| now - t >= WINDOW_MS) {
45                opened.pop_front();
46            }
47            !opened.is_empty()
48        });
49    }
50}
51
52static LIMITER: LazyLock<Limiter> = LazyLock::new(Default::default);
53
54fn refused(text: String) -> WebReturnType {
55    WebReturnType::error(text)
56}
57
58/// The agent a pane belongs to.
59fn agent_of(state: &AppState, block_id: &str) -> Option<String> {
60    let from_meta = || {
61        let block = state.mstore.get::<Block>(block_id).ok().flatten()?;
62        Some(crate::backend::obj::meta_get_string(&block.meta, "agentId", "")).filter(|id| !id.is_empty())
63    };
64    state.reactive_handler.get_agent_by_block(block_id).map(|a| a.agent_id).or_else(from_meta)
65}
66
67/// A request carrying an agent's token may read only its own pane's state; one with no token (the window's own) is not
68/// asked. The token must name an agent srv knows.
69pub(super) fn own_pane_only(state: &AppState, block_id: &str, caller_uid: Option<&str>, method: &str) -> Result<(), WebReturnType> {
70    let Some(uid) = caller_uid else { return Ok(()) };
71    let Some(slug) = state.mstore.agent_names_by_id(uid).ok().flatten().map(|row| row.slug).filter(|slug| !slug.is_empty()) else {
72        return Err(refused(format!("{method}: FORBIDDEN: the token's agent is unknown")));
73    };
74    if agent_of(state, block_id).is_some_and(|owner| owner == uid || owner == slug) {
75        return Ok(());
76    }
77    Err(refused(format!("{method}: FORBIDDEN: an agent may read only its own pane; to see another agent's work use Agents list")))
78}
79
80/// Opens the person's countdown for the agent in `block_id`, in the name of the agent the request's token names, or
81/// says why not.
82pub(super) fn ask_the_person_to_stop(state: &AppState, block_id: &str, caller_uid: Option<&str>, method: &str) -> Result<WebReturnType, WebReturnType> {
83    let Some(uid) = caller_uid else {
84        return Err(refused(format!(
85            "{method}: FORBIDDEN: the request must carry an agent's token (AGENTMUX_AGENT_TOKEN), as Stop agents does; or the person stops the agent from the window"
86        )));
87    };
88    if crate::backend::blockcontroller::get_controller(block_id).is_none() {
89        return Err(refused(format!("{method}: no running agent in block {block_id}")));
90    }
91    if !crate::sagas::orphan_reaper::is_agent_block(state, block_id) {
92        return Err(refused(format!("{method}: not an agent pane: close it with Stop with action \"pane\"")));
93    }
94    let Some(by) = state.mstore.agent_names_by_id(uid).ok().flatten().map(|row| row.slug).filter(|slug| !slug.is_empty()) else {
95        return Err(refused(format!("{method}: FORBIDDEN: the token's agent is unknown")));
96    };
97    if agent_of(state, block_id).is_some_and(|target| target == uid || target == by) {
98        return Err(refused(format!("{method}: your own block: to end your own session use Stop with action \"self\"")));
99    }
100    // A request for an agent that already has a countdown joins it and opens nothing, so it needs no room; only a
101    // countdown that is opened is counted.
102    if crate::sagas::pending_shutdown::active_for(block_id).is_none() {
103        if let Err(wait_ms) = LIMITER.room(uid, AGENT_OPENS, now_ms()) {
104            return Err(refused(format!(
105                "{method}: RATE_LIMITED: {by} has opened {AGENT_OPENS} stop countdowns in the last minute; wait {} s, or leave it to the person",
106                wait_ms / 1000 + 1
107            )));
108        }
109    }
110    let action = crate::sagas::pending_shutdown::Action::CloseTab { detail: format!("asked by {by} ({method}, on the service route)") };
111    let pending = crate::sagas::pending_shutdown::request(state, block_id, &by, "Service", "", action);
112    if !pending.joined {
113        LIMITER.charge(uid, now_ms());
114    }
115    // The call does not wait for the person: the answer says so, and the caller is told how the request ended, as any
116    // other requester is (a note when the person keeps the agent running or the close fails).
117    crate::sagas::pending_shutdown::tell_when_settled(state, &pending.request_id, &by, method);
118    let note = answer_note(block_id, pending.joined);
119    Ok(WebReturnType::success(serde_json::json!({ "status": "pending_user_override", "note": note, "pending": pending })))
120}
121
122/// What the answer says: the countdown is open, nothing is stopped yet, and where the outcome shows.
123fn answer_note(block_id: &str, joined: bool) -> String {
124    let open = if joined { "A countdown was already open for the agent in this block, and this request joined it" } else { "A countdown is open for the agent in this block" };
125    format!(
126        "{open} ({block_id}): nothing is stopped yet, and the person can keep it running. See Agents list for the outcome; if the person keeps it running or the close fails, one [AgentMux] note tells you."
127    )
128}
129
130#[cfg(test)]
131mod tests {
132    use super::*;
133
134    #[test]
135    fn a_caller_may_open_its_limit_in_a_minute_and_a_slot_frees_as_the_oldest_leaves() {
136        let limiter = Limiter::default();
137        for t in 0..3 {
138            assert!(limiter.room("a", 3, t * 1_000).is_ok());
139            limiter.charge("a", t * 1_000);
140        }
141        assert_eq!(limiter.room("a", 3, 10_000), Err(WINDOW_MS - 10_000), "the fourth waits for the first to leave the minute");
142        assert!(limiter.room("b", 3, 10_000).is_ok(), "another caller has its own count");
143        assert!(limiter.room("a", 3, WINDOW_MS).is_ok(), "the first has left the window");
144        limiter.charge("a", WINDOW_MS);
145        assert!(limiter.room("a", 3, WINDOW_MS + 500).is_err(), "and the one that took its place counts");
146    }
147
148    #[test]
149    fn asking_for_room_counts_nothing() {
150        let limiter = Limiter::default();
151        for _ in 0..10 {
152            assert!(limiter.room("a", 1, 0).is_ok());
153        }
154    }
155}