Skip to main content

agentmux_srv/server/app_api/
desktop_group.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Several apps asked for in one `Desktop` call. Each app is still its own
5//! sensitive request, with its own card, countdown, veto and grant, and nothing
6//! about one decides another. What the group changes is only what the agent is
7//! told: the notes for the requests of one call are held, and when every one
8//! has ended the agent gets a single note naming each app as allowed, declined,
9//! vetoed or not decided.
10
11use std::sync::Mutex;
12
13use crate::backend::sensitive_requests::{self as requests, Request};
14
15/// The most apps one call asks for.
16pub(crate) const MAX_MEMBERS: usize = 8;
17/// The most groups waiting at once, across all agents.
18const MAX_GROUPS: usize = 32;
19/// A group that has not finished by then is flushed: the agent is told what is known, and its
20/// requests go back to sending their own notes. Longer than any review plus countdown.
21pub(crate) const GROUP_TTL: std::time::Duration = std::time::Duration::from_secs(15 * 60);
22
23/// How a request of a group ended.
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub(crate) enum Settled {
26    /// The grant was made.
27    Allowed,
28    /// The grant could not be made, and why.
29    Failed(String),
30    /// The super agent said no.
31    Declined,
32    /// The person stopped it in the countdown.
33    Vetoed,
34    /// Withdrawn, or ended with no answer.
35    Ended,
36}
37
38#[derive(Debug, Clone)]
39struct Member {
40    request_id: String,
41    app: String,
42    outcome: Option<Settled>,
43}
44
45#[derive(Debug, Clone)]
46struct Group {
47    /// The asking agent, its pane and the call's own id, so one agent's call can't be joined by another.
48    key: String,
49    /// The asking agent's uid: the one the group's note is for.
50    owner: String,
51    block_id: String,
52    members: Vec<Member>,
53    /// The call has filed all its requests. Until then a request that ends early does not finish the group.
54    sealed: bool,
55}
56
57static GROUPS: Mutex<Vec<Group>> = Mutex::new(Vec::new());
58
59/// The key of one call's group.
60pub(crate) fn key(uid: &str, block_id: &str, call: &str) -> String {
61    format!("{uid}|{block_id}|{call}")
62}
63
64/// What `add` did.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub(crate) enum Added {
67    /// Not added (full, sealed, or too many groups): the request sends its own notes.
68    No,
69    /// Joined a group already there.
70    Joined,
71    /// Made the group: the caller starts its deadline.
72    Created,
73}
74
75impl Added {
76    /// The request is in a group.
77    pub(crate) fn grouped(self) -> bool {
78        self != Added::No
79    }
80}
81
82/// Add the request filed for `app` to the group of this call, making the group if it is the first.
83pub(crate) fn add(key: &str, block_id: &str, request_id: &str, app: &str) -> Added {
84    let mut groups = GROUPS.lock().unwrap_or_else(|e| e.into_inner());
85    let member = Member { request_id: request_id.to_string(), app: app.to_string(), outcome: None };
86    if let Some(g) = groups.iter_mut().find(|g| g.key == key) {
87        if g.sealed || g.members.len() >= MAX_MEMBERS || g.members.iter().any(|m| m.request_id == request_id) {
88            return Added::No;
89        }
90        g.members.push(member);
91        return Added::Joined;
92    }
93    if groups.len() >= MAX_GROUPS {
94        return Added::No;
95    }
96    let owner = key.split('|').next().unwrap_or_default().to_string();
97    groups.push(Group { key: key.to_string(), owner, block_id: block_id.to_string(), members: vec![member], sealed: false });
98    Added::Created
99}
100
101/// Whether `request_id` is part of a group, whoever asks for it now.
102#[cfg(test)]
103pub(crate) fn is_member(request_id: &str) -> bool {
104    GROUPS.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|g| g.members.iter().any(|m| m.request_id == request_id))
105}
106
107/// Whether `request_id` is already one of the requests of the group `key`: the call named a second window of an
108/// app it already asked for.
109pub(crate) fn in_group(key: &str, request_id: &str) -> bool {
110    GROUPS.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|g| g.key == key && g.members.iter().any(|m| m.request_id == request_id))
111}
112
113/// Whether the group's agent is the only one that asks for the request now. A request another agent joined, or one
114/// the group's agent withdrew, is the other agents' to be told about, so it is not the group's.
115fn owned_by(g: &Group, askers: &[&str]) -> bool {
116    askers == [g.owner.as_str()]
117}
118
119/// The pane and the note to send when the group is finished, and the group is gone.
120type Done = (String, String);
121
122/// Every member ended: it has an outcome, or its request is no longer open.
123fn finished(g: &Group, is_open: &dyn Fn(&str) -> bool) -> bool {
124    g.sealed && g.members.iter().all(|m| m.outcome.is_some() || !is_open(&m.request_id))
125}
126
127fn take_if_finished(groups: &mut Vec<Group>, at: usize, is_open: &dyn Fn(&str) -> bool) -> Option<Done> {
128    if !finished(&groups[at], is_open) {
129        return None;
130    }
131    let g = groups.remove(at);
132    Some((g.block_id.clone(), note(&g, is_open)))
133}
134
135/// End the group now whatever is left, as its deadline does: the note says what is known, and an
136/// app still waiting says so and will send its own note when it is decided. Nothing happens if the
137/// group already finished.
138pub(crate) fn flush(key: &str, is_open: &dyn Fn(&str) -> bool) -> Option<Done> {
139    let mut groups = GROUPS.lock().unwrap_or_else(|e| e.into_inner());
140    let at = groups.iter().position(|g| g.key == key)?;
141    let g = groups.remove(at);
142    Some((g.block_id.clone(), note(&g, is_open)))
143}
144
145/// Record how `request_id` ended, with `askers`, the agents that ask for it now. Returns whether its own note is left
146/// out (it is a member and the group's agent is the only asker), and the note to send when that finished its group.
147/// Both come from one look at the groups, so a deadline that ends the group in between can't make a request look held
148/// when it is not. A request the group's agent no longer asks for alone is recorded as not decided for the group, so
149/// the group's note never reports an answer that was another agent's.
150pub(crate) fn settle_member(request_id: &str, outcome: Settled, askers: &[&str], is_open: &dyn Fn(&str) -> bool) -> (bool, Option<Done>) {
151    let mut groups = GROUPS.lock().unwrap_or_else(|e| e.into_inner());
152    let Some(at) = groups.iter().position(|g| g.members.iter().any(|m| m.request_id == request_id)) else {
153        return (false, None);
154    };
155    let owned = owned_by(&groups[at], askers);
156    if let Some(m) = groups[at].members.iter_mut().find(|m| m.request_id == request_id) {
157        m.outcome.get_or_insert(if owned { outcome } else { Settled::Ended });
158    }
159    (owned, take_if_finished(&mut groups, at, is_open))
160}
161
162/// The call has filed every request: from now on the group may finish. Returns the note when every one
163/// has already ended.
164pub(crate) fn seal(key: &str, is_open: &dyn Fn(&str) -> bool) -> Option<Done> {
165    let mut groups = GROUPS.lock().unwrap_or_else(|e| e.into_inner());
166    let at = groups.iter().position(|g| g.key == key)?;
167    groups[at].sealed = true;
168    take_if_finished(&mut groups, at, is_open)
169}
170
171/// `app` and what became of it.
172fn line(m: &Member, is_open: &dyn Fn(&str) -> bool) -> String {
173    let said = match &m.outcome {
174        Some(Settled::Allowed) => "allowed, you may use it now".to_string(),
175        Some(Settled::Failed(why)) => format!("could not be allowed: {}", crate::backend::reactive::sanitize::quote_in_system_note(why)),
176        Some(Settled::Declined) => "declined".to_string(),
177        Some(Settled::Vetoed) => "vetoed by the person".to_string(),
178        None if is_open(&m.request_id) => "still waiting for an answer; its own note will follow".to_string(),
179        Some(Settled::Ended) | None => "not decided (withdrawn or timed out)".to_string(),
180    };
181    format!("{}: {said}", m.app)
182}
183
184fn note(g: &Group, is_open: &dyn Fn(&str) -> bool) -> String {
185    let lines: Vec<String> = g.members.iter().map(|m| line(m, is_open)).collect();
186    format!("[AgentMux] Your request to control {} apps has been answered: {}. Each answer is for that app alone.", g.members.len(), lines.join("; "))
187}
188
189/// Whether a request is still open in the registry.
190pub(crate) fn request_is_open(request_id: &str) -> bool {
191    requests::registry().get(request_id).is_some_and(|r| r.status.is_open())
192}
193
194/// A request's progress notes (approved, counting down) are held while it is in a group and the group's agent
195/// is the only one that asks for it.
196pub(crate) fn holds(request: &Request) -> bool {
197    holds_for(&request.id, &request.askers())
198}
199
200fn holds_for(request_id: &str, askers: &[&str]) -> bool {
201    GROUPS.lock().unwrap_or_else(|e| e.into_inner()).iter().any(|g| g.members.iter().any(|m| m.request_id == request_id) && owned_by(g, askers))
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    /// A request is open until the test says it ended.
209    fn open_all(_: &str) -> bool {
210        true
211    }
212
213    fn fresh(name: &str) -> String {
214        key("agent-uid", "block-1", name)
215    }
216
217    /// The group's agent asks for the request alone.
218    const OWNER: &[&str] = &["agent-uid"];
219
220    fn settle(request_id: &str, outcome: Settled, is_open: &dyn Fn(&str) -> bool) -> Option<Done> {
221        settle_member(request_id, outcome, OWNER, is_open).1
222    }
223
224    #[test]
225    fn one_note_names_each_app_allowed_declined_or_vetoed() {
226        let k = fresh("mixed");
227        assert!(add(&k, "block-1", "mixed-a", "cantabile").grouped());
228        assert!(add(&k, "block-1", "mixed-b", "voicemeeter").grouped());
229        assert!(add(&k, "block-1", "mixed-c", "notepad").grouped());
230        assert_eq!(seal(&k, &open_all), None);
231        // The first two ending does not finish it, and sends nothing.
232        assert_eq!(settle("mixed-a", Settled::Allowed, &open_all), None);
233        assert_eq!(settle("mixed-b", Settled::Declined, &open_all), None);
234        let (block, said) = settle("mixed-c", Settled::Vetoed, &open_all).expect("the last one ends the group");
235        assert_eq!(block, "block-1");
236        assert!(said.contains("cantabile: allowed"), "{said}");
237        assert!(said.contains("voicemeeter: declined"), "{said}");
238        assert!(said.contains("notepad: vetoed by the person"), "{said}");
239        assert!(said.contains("Each answer is for that app alone"), "{said}");
240        // The group is gone: nothing more is held.
241        assert!(!is_member("mixed-a"));
242    }
243
244    #[test]
245    fn an_app_is_allowed_only_by_its_own_outcome() {
246        let k = fresh("alone");
247        assert!(add(&k, "block-1", "alone-a", "cantabile").grouped());
248        assert!(add(&k, "block-1", "alone-b", "voicemeeter").grouped());
249        seal(&k, &open_all);
250        // One allowed and one that timed out: the second is never reported as allowed.
251        settle("alone-a", Settled::Allowed, &open_all);
252        let (_, said) = settle("alone-b", Settled::Ended, &open_all).unwrap();
253        assert!(said.contains("cantabile: allowed"));
254        assert!(said.contains("voicemeeter: not decided"), "{said}");
255        assert!(!said.contains("voicemeeter: allowed"));
256    }
257
258    #[test]
259    fn requests_that_end_before_the_call_has_filed_them_all_do_not_finish_it() {
260        let k = fresh("early");
261        assert!(add(&k, "block-1", "early-a", "one").grouped());
262        assert_eq!(settle("early-a", Settled::Declined, &open_all), None);
263        assert!(add(&k, "block-1", "early-b", "two").grouped());
264        // Sealing with the second still open sends nothing; its end then sends the one note.
265        assert_eq!(seal(&k, &|id| id == "early-b"), None);
266        let (_, said) = settle("early-b", Settled::Allowed, &open_all).unwrap();
267        assert!(said.contains("one: declined") && said.contains("two: allowed"), "{said}");
268    }
269
270    #[test]
271    fn a_group_whose_requests_all_ended_before_sealing_is_told_at_the_seal() {
272        let k = fresh("sealed-late");
273        assert!(add(&k, "block-1", "late-a", "one").grouped());
274        settle("late-a", Settled::Vetoed, &open_all);
275        let (_, said) = seal(&k, &open_all).expect("nothing is left open");
276        assert!(said.contains("one: vetoed by the person"), "{said}");
277    }
278
279    #[test]
280    fn a_withdrawn_request_does_not_hold_the_group_forever() {
281        let k = fresh("withdrawn");
282        assert!(add(&k, "block-1", "wd-a", "one").grouped());
283        assert!(add(&k, "block-1", "wd-b", "two").grouped());
284        seal(&k, &open_all);
285        settle("wd-a", Settled::Allowed, &open_all);
286        // `wd-b` is no longer open in the registry and has no outcome of its own.
287        let (_, said) = settle("wd-a", Settled::Allowed, &|id| id != "wd-b").unwrap();
288        assert!(said.contains("one: allowed") && said.contains("two: not decided"), "{said}");
289    }
290
291    #[test]
292    fn a_failed_grant_says_why_without_allowing_it() {
293        let k = fresh("failed");
294        assert!(add(&k, "block-1", "f-a", "one").grouped());
295        seal(&k, &open_all);
296        let (_, said) = settle("f-a", Settled::Failed("Desktop driving is off".into()), &open_all).unwrap();
297        assert!(said.contains("one: could not be allowed: Desktop driving is off"), "{said}");
298    }
299
300    #[test]
301    fn a_group_is_bounded_and_one_agents_call_is_not_joined_by_anothers() {
302        let k = fresh("bounded");
303        for i in 0..MAX_MEMBERS {
304            assert!(add(&k, "block-1", &format!("b-{i}"), "app").grouped(), "{i}");
305        }
306        assert_eq!(add(&k, "block-1", "b-extra", "app"), Added::No, "a ninth app is not added");
307        // A different agent, pane or call has its own key.
308        assert_ne!(key("a", "b", "c"), key("a", "b", "d"));
309        assert_ne!(key("a", "b", "c"), key("x", "b", "c"));
310        assert_ne!(key("a", "b", "c"), key("a", "y", "c"));
311        // A sealed group takes no more.
312        let s = fresh("closed");
313        assert!(add(&s, "block-1", "c-a", "app").grouped());
314        seal(&s, &|_| true);
315        assert_eq!(add(&s, "block-1", "c-b", "app"), Added::No);
316    }
317
318    #[test]
319    fn the_first_request_creates_the_group_and_the_rest_join_it() {
320        let k = fresh("created");
321        assert_eq!(add(&k, "block-1", "cr-a", "one"), Added::Created);
322        assert_eq!(add(&k, "block-1", "cr-b", "two"), Added::Joined);
323        flush(&k, &|_| true);
324    }
325
326    #[test]
327    fn a_group_that_never_finishes_is_flushed_by_its_deadline_and_stops_holding_notes() {
328        let k = fresh("stuck");
329        assert!(add(&k, "block-1", "st-a", "one").grouped());
330        assert!(add(&k, "block-1", "st-b", "two").grouped());
331        // The call was never sealed; `one` was allowed, `two` is still open.
332        settle("st-a", Settled::Allowed, &|_| true);
333        assert!(is_member("st-b"));
334        let (block, said) = flush(&k, &|id| id == "st-b").expect("the deadline ends it");
335        assert_eq!(block, "block-1");
336        assert!(said.contains("one: allowed"), "{said}");
337        assert!(said.contains("two: still waiting for an answer; its own note will follow"), "{said}");
338        // Its requests send their own notes again, and the slot is free.
339        assert!(!is_member("st-b"));
340        assert_eq!(flush(&k, &|_| true), None);
341    }
342
343    #[test]
344    fn settling_says_whether_the_request_was_in_a_group() {
345        let k = fresh("member");
346        assert!(add(&k, "block-1", "mem-a", "one").grouped());
347        assert_eq!(settle_member("not-in-a-group", Settled::Allowed, OWNER, &|_| true), (false, None));
348        let (member, done) = settle_member("mem-a", Settled::Allowed, OWNER, &|_| true);
349        assert!(member);
350        assert_eq!(done, None, "an unsealed group does not finish");
351        flush(&k, &|_| true);
352        // After the deadline took the group, the same request is no longer a member.
353        assert_eq!(settle_member("mem-a", Settled::Allowed, OWNER, &|_| true), (false, None));
354    }
355
356    #[test]
357    fn the_request_that_finishes_a_group_does_not_send_its_own_note_as_well() {
358        let k = fresh("last");
359        assert!(add(&k, "block-1", "last-a", "one").grouped());
360        assert!(add(&k, "block-1", "last-b", "two").grouped());
361        seal(&k, &|_| true);
362        settle_member("last-a", Settled::Allowed, OWNER, &|_| true);
363        // `last-b` is the one that ends the group: the group is gone when `settled` decides.
364        let (held, done) = settle_member("last-b", Settled::Vetoed, OWNER, &|_| true);
365        assert!(done.is_some() && !is_member("last-b"));
366        assert!(held, "its own vetoed note is not sent after the combined one");
367        // A request that was never in a group sends its own.
368        assert!(!settle_member("never-in-one", Settled::Vetoed, OWNER, &|_| true).0);
369    }
370
371    #[test]
372    fn a_request_another_agent_joined_or_the_group_agent_withdrew_is_not_the_groups() {
373        let k = fresh("shared");
374        assert!(add(&k, "block-1", "sh-a", "one").grouped());
375        assert!(add(&k, "block-1", "sh-b", "two").grouped());
376        seal(&k, &open_all);
377        // Both asked for `sh-a`: its notes go to each of them, not only into the group's note.
378        assert!(holds_for("sh-a", OWNER));
379        assert!(!holds_for("sh-a", &["agent-uid", "joiner-uid"]));
380        // The group's agent withdrew `sh-b` and the joiner is its only asker now: its notes are the joiner's own.
381        assert!(!holds_for("sh-b", &["joiner-uid"]));
382        let (held, done) = settle_member("sh-b", Settled::Allowed, &["joiner-uid"], &open_all);
383        assert!(!held, "the joiner is sent its own note");
384        assert_eq!(done, None, "the other request is still open");
385        // The group's agent is never told that app was allowed: the answer was the joiner's.
386        let (_, said) = settle_member("sh-a", Settled::Declined, OWNER, &open_all).1.expect("the last one ends the group");
387        assert!(said.contains("one: declined") && said.contains("two: not decided"), "{said}");
388        assert!(!said.contains("two: allowed"), "{said}");
389    }
390
391    #[test]
392    fn a_request_is_in_the_group_of_its_own_call_only() {
393        let k = fresh("same-app");
394        assert!(add(&k, "block-1", "same-a", "one").grouped());
395        assert!(in_group(&k, "same-a"));
396        assert!(!in_group(&k, "someone-elses"), "a request of no group of this call");
397        assert!(!in_group(&fresh("another-call"), "same-a"), "nor of another call's group");
398        flush(&k, &|_| true);
399        assert!(!in_group(&k, "same-a"), "once the group is gone");
400    }
401}