Skip to main content

agentmux_srv_core/backend/
folder_overlap_asks.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's ask for the person's go-ahead with a host agent that shares a folder with a container agent
5//! (`backend::folder_overlap`), waiting for the person.
6//!
7//! The agent names the pair and srv keeps the ask here; the window shows it as a card in the asking agent's pane. The
8//! person's answer reaches srv only through the window (`folderoverlapaccept`, `folderoverlapdecline`), which ends
9//! the ask. An agent can ask and look again; it can never answer. A declined pair is not asked about again for a
10//! while, and the pair stays unchosen: every other refusal for it stands.
11//!
12//! An ask with no asking agent (`agent` empty) is one AgentMux made itself: restart resume left the host agent stopped
13//! for want of the person's go-ahead. It waits in the host agent's own block until the person answers, and neither
14//! ends with the hour nor takes the room of the agents' asks.
15
16use std::sync::{Mutex, OnceLock};
17
18use serde::{Deserialize, Serialize};
19
20/// A host agent and a container agent, and the agent that asked the person to go ahead with them.
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, ts_rs::TS)]
22#[ts(export, export_to = "../../../frontend/types/rpc/")]
23pub struct FolderAsk {
24    pub host_id: String,
25    pub host_name: String,
26    pub container_id: String,
27    pub container_name: String,
28    /// The agent that asked, by its name; empty for the ask restart resume makes.
29    pub agent: String,
30    /// The asking agent's pane, where the card shows.
31    pub block_id: String,
32    #[ts(type = "number")]
33    pub requested_ms: u64,
34}
35
36/// What an ask comes to.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum Asked {
39    /// The person is asked: the card is shown. `new` when this ask made it, not one already waiting.
40    Waiting { ask: FolderAsk, new: bool },
41    /// The person said no to this pair a short while ago; it is not asked again until then.
42    Declined { retry_after_ms: u64 },
43}
44
45/// At most this many asks wait at once; the oldest goes first.
46const MAX_OPEN: usize = 16;
47/// An ask nobody answers ends after this long.
48const OPEN_MS: u64 = 60 * 60 * 1000;
49/// After the person says no, the pair is not asked about again for this long.
50pub const QUIET_MS: u64 = 10 * 60 * 1000;
51
52#[derive(Default)]
53struct State {
54    open: Vec<FolderAsk>,
55    /// The pairs the person said no to, and when.
56    declined: Vec<(String, String, u64)>,
57}
58
59#[derive(Default)]
60pub struct Asks {
61    state: Mutex<State>,
62}
63
64pub fn asks() -> &'static Asks {
65    static ASKS: OnceLock<Asks> = OnceLock::new();
66    ASKS.get_or_init(Asks::default)
67}
68
69fn same_pair(ask: &FolderAsk, host_id: &str, container_id: &str) -> bool {
70    ask.host_id == host_id && ask.container_id == container_id
71}
72
73impl Asks {
74    fn lock(&self, now_ms: u64) -> std::sync::MutexGuard<'_, State> {
75        let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
76        state.open.retain(|ask| ask.agent.is_empty() || now_ms.saturating_sub(ask.requested_ms) < OPEN_MS);
77        state.declined.retain(|(_, _, at)| now_ms.saturating_sub(*at) < QUIET_MS);
78        state
79    }
80
81    /// Asks the person. A pair that is already waiting is asked once: the newest asker's pane shows the card. A pair
82    /// the person said no to a short while ago is not asked again.
83    pub fn ask(&self, ask: FolderAsk, now_ms: u64) -> Asked {
84        let mut state = self.lock(now_ms);
85        if let Some((_, _, at)) = state.declined.iter().find(|(h, c, _)| *h == ask.host_id && *c == ask.container_id) {
86            return Asked::Declined { retry_after_ms: QUIET_MS.saturating_sub(now_ms.saturating_sub(*at)) };
87        }
88        if let Some(kept) = state.open.iter_mut().find(|k| same_pair(k, &ask.host_id, &ask.container_id)) {
89            // An ask restart resume made stays where it is, in the stopped agent's block, until the person answers, and an
90            // agent's ask that is waiting becomes it when restart resume leaves the host agent stopped; the asks of
91            // agents move to the newest asker's pane.
92            if ask.agent.is_empty() || !kept.agent.is_empty() {
93                kept.agent = ask.agent;
94                kept.block_id = ask.block_id;
95            }
96            return Asked::Waiting { ask: kept.clone(), new: false };
97        }
98        if !ask.agent.is_empty() && state.open.iter().filter(|kept| !kept.agent.is_empty()).count() >= MAX_OPEN {
99            if let Some(oldest) = state.open.iter().position(|kept| !kept.agent.is_empty()) {
100                state.open.remove(oldest);
101            }
102        }
103        state.open.push(ask.clone());
104        Asked::Waiting { ask, new: true }
105    }
106
107    /// The asks waiting for the person.
108    pub fn list(&self, now_ms: u64) -> Vec<FolderAsk> {
109        self.lock(now_ms).open.clone()
110    }
111
112    /// The person's answer for the pair: ends its ask, and a no is remembered for a while. Returns whether an ask
113    /// waited.
114    pub fn answer(&self, host_id: &str, container_id: &str, go_ahead: bool, now_ms: u64) -> bool {
115        let mut state = self.lock(now_ms);
116        let before = state.open.len();
117        state.open.retain(|ask| !same_pair(ask, host_id, container_id));
118        state.declined.retain(|(h, c, _)| h != host_id || c != container_id);
119        if !go_ahead {
120            state.declined.push((host_id.to_string(), container_id.to_string(), now_ms));
121        }
122        state.open.len() != before
123    }
124
125    /// Ends every ask and every no that names agent `id`: the agent is deleted.
126    pub fn forget_agent(&self, id: &str) {
127        let mut state = self.state.lock().unwrap_or_else(|p| p.into_inner());
128        state.open.retain(|ask| ask.host_id != id && ask.container_id != id);
129        state.declined.retain(|(h, c, _)| h != id && c != id);
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    fn ask(host: &str, container: &str, agent: &str, block: &str, at: u64) -> FolderAsk {
138        FolderAsk {
139            host_id: host.into(),
140            host_name: format!("{host}-name"),
141            container_id: container.into(),
142            container_name: format!("{container}-name"),
143            agent: agent.into(),
144            block_id: block.into(),
145            requested_ms: at,
146        }
147    }
148
149    #[test]
150    fn a_pair_is_asked_once_and_the_newest_asker_shows_the_card() {
151        let asks = Asks::default();
152        assert!(matches!(asks.ask(ask("h", "c", "Lead", "b1", 10), 10), Asked::Waiting { new: true, .. }));
153        let Asked::Waiting { ask: kept, new } = asks.ask(ask("h", "c", "Other", "b2", 20), 20) else { panic!("asked") };
154        assert!(!new);
155        assert_eq!((kept.agent.as_str(), kept.block_id.as_str(), kept.requested_ms), ("Other", "b2", 10));
156        assert_eq!(asks.list(20).len(), 1);
157    }
158
159    #[test]
160    fn an_answer_ends_the_ask_and_a_no_is_remembered_for_a_while() {
161        let asks = Asks::default();
162        asks.ask(ask("h", "c", "Lead", "b1", 0), 0);
163        assert!(asks.answer("h", "c", false, 100));
164        assert!(asks.list(100).is_empty());
165        assert_eq!(asks.ask(ask("h", "c", "Lead", "b1", 200), 200), Asked::Declined { retry_after_ms: QUIET_MS - 100 });
166        assert!(matches!(asks.ask(ask("h", "c", "Lead", "b1", 100 + QUIET_MS), 100 + QUIET_MS), Asked::Waiting { .. }));
167    }
168
169    #[test]
170    fn an_agents_ask_for_a_pair_restart_resume_is_waiting_on_leaves_that_ask_where_it_is() {
171        let asks = Asks::default();
172        asks.ask(ask("h", "c", "", "parked-block", 0), 0);
173        let Asked::Waiting { ask: kept, new } = asks.ask(ask("h", "c", "Lead", "lead-pane", 10), 10) else { panic!("asked") };
174        assert!(!new);
175        assert_eq!((kept.agent.as_str(), kept.block_id.as_str(), kept.requested_ms), ("", "parked-block", 0));
176        assert_eq!(asks.list(OPEN_MS + 1_000).len(), 1, "and it still does not end with the hour");
177    }
178
179    #[test]
180    fn an_agents_ask_that_waits_becomes_restart_resumes_when_the_host_agent_is_left_stopped() {
181        let asks = Asks::default();
182        asks.ask(ask("h", "c", "Lead", "lead-pane", 0), 0);
183        let Asked::Waiting { ask: kept, new } = asks.ask(ask("h", "c", "", "parked-block", 10), 10) else { panic!("asked") };
184        assert!(!new);
185        assert_eq!((kept.agent.as_str(), kept.block_id.as_str()), ("", "parked-block"));
186        assert_eq!(asks.list(OPEN_MS + 1_000).len(), 1, "and it no longer ends with the hour");
187    }
188
189    #[test]
190    fn restart_resumes_asks_do_not_push_an_agents_ask_out_when_the_agents_asks_are_full() {
191        let asks = Asks::default();
192        for i in 0..MAX_OPEN {
193            asks.ask(ask(&format!("h{i}"), "c", "Lead", "b", i as u64), i as u64);
194        }
195        asks.ask(ask("resumed-1", "c", "", "p1", 50), 50);
196        asks.ask(ask("resumed-2", "c", "", "p2", 51), 51);
197        let all = asks.list(60);
198        assert_eq!(all.len(), MAX_OPEN + 2, "every agent's ask is still there");
199        assert!(all.iter().any(|a| a.host_id == "h0"));
200    }
201
202    #[test]
203    fn an_ask_restart_resume_makes_waits_for_the_person_and_takes_no_room_from_the_agents_asks() {
204        let asks = Asks::default();
205        asks.ask(ask("resumed", "c", "", "parked-block", 0), 0);
206        for i in 0..MAX_OPEN {
207            asks.ask(ask(&format!("h{i}"), "c", "Lead", "b", i as u64), i as u64);
208        }
209        asks.ask(ask("h-extra", "c", "Lead", "b", 99), 99);
210        let soon = asks.list(100);
211        assert_eq!(soon.len(), MAX_OPEN + 1, "the cap is for the agents' asks: the oldest of them went, the restart's stayed");
212        assert!(soon.iter().any(|a| a.host_id == "resumed") && !soon.iter().any(|a| a.host_id == "h0"));
213        let later = OPEN_MS + 1_000;
214        let left = asks.list(later);
215        assert_eq!(left.len(), 1, "the agents' asks ended with the hour and the oldest went first");
216        assert_eq!((left[0].host_id.as_str(), left[0].agent.as_str(), left[0].block_id.as_str()), ("resumed", "", "parked-block"));
217        assert!(asks.answer("resumed", "c", true, later));
218        assert!(asks.list(later).is_empty(), "the person's answer ends it");
219    }
220
221    #[test]
222    fn a_go_ahead_ends_the_ask_and_clears_an_old_no() {
223        let asks = Asks::default();
224        asks.answer("h", "c", false, 0);
225        assert!(!asks.answer("h", "c", true, 10), "nothing waited");
226        assert!(matches!(asks.ask(ask("h", "c", "Lead", "b1", 20), 20), Asked::Waiting { .. }));
227    }
228
229    #[test]
230    fn an_ask_nobody_answers_ends_and_the_oldest_goes_when_too_many_wait() {
231        let asks = Asks::default();
232        asks.ask(ask("h", "c", "Lead", "b1", 0), 0);
233        assert!(asks.list(OPEN_MS).is_empty());
234        for n in 0..=MAX_OPEN {
235            asks.ask(ask(&format!("h{n}"), "c", "Lead", "b1", 1), 1);
236        }
237        let waiting = asks.list(1);
238        assert_eq!(waiting.len(), MAX_OPEN);
239        assert!(waiting.iter().all(|a| a.host_id != "h0"));
240    }
241
242    #[test]
243    fn deleting_an_agent_ends_its_asks_and_its_nos() {
244        let asks = Asks::default();
245        asks.ask(ask("h", "c", "Lead", "b1", 0), 0);
246        asks.answer("h2", "c", false, 0);
247        asks.forget_agent("c");
248        assert!(asks.list(1).is_empty());
249        assert!(matches!(asks.ask(ask("h2", "c", "Lead", "b1", 2), 2), Asked::Waiting { .. }));
250    }
251}