Skip to main content

agentmux_srv_core/backend/widget/
requests.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Agents' requests to install a widget, waiting for the user
5//! (docs/specs/SPEC_USER_WIDGETS_AND_WIDGET_API_2026_10_09.md §10).
6//!
7//! `WidgetInstall` copies the package in (it then needs approval like any
8//! other) and asks here. The UI shows each request as a prompt; the user's
9//! answer reaches srv only through the host's approval route, which answers
10//! every request for that version. An agent can ask; it can never answer.
11
12use std::sync::{Mutex, OnceLock};
13
14use serde::{Deserialize, Serialize};
15use tokio::sync::oneshot;
16
17use super::packages::{WidgetKind, WidgetPackageInfo};
18
19#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ts_rs::TS)]
20#[ts(export, export_to = "../../../frontend/types/rpc/")]
21pub struct WidgetInstallRequest {
22    pub id: String,
23    pub hash: String,
24    pub name: String,
25    pub version: String,
26    pub description: Option<String>,
27    pub author: Option<String>,
28    pub kind: WidgetKind,
29    pub permissions: Vec<String>,
30    /// Who signed it (SPEC_WIDGET_SHARING_2026_10_10.md §2.3).
31    pub signature: crate::backend::widget::signature::WidgetSignatureInfo,
32    /// The agent that asked.
33    pub agent: String,
34    /// The asking agent's pane, for the card there; empty when it has none (an unverified asker, a bundle import).
35    pub block_id: String,
36    #[ts(type = "number")]
37    pub requested_ms: u64,
38}
39
40impl WidgetInstallRequest {
41    pub fn of(pkg: &WidgetPackageInfo, agent: &str, block_id: &str) -> Self {
42        Self {
43            id: pkg.id.clone(),
44            hash: pkg.hash.clone(),
45            name: pkg.name.clone(),
46            version: pkg.version.clone(),
47            description: pkg.description.clone(),
48            author: pkg.author.clone(),
49            kind: pkg.kind.clone(),
50            permissions: pkg.permissions.clone(),
51            signature: pkg.signature.clone(),
52            agent: agent.to_string(),
53            block_id: block_id.to_string(),
54            requested_ms: agentmux_common::time::now_ms_u64(),
55        }
56    }
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum Answer {
61    Approved,
62    Declined,
63}
64
65#[derive(Default)]
66pub struct Requests {
67    pending: Mutex<Vec<(WidgetInstallRequest, Vec<oneshot::Sender<Answer>>)>>,
68}
69
70pub fn requests() -> &'static Requests {
71    static REQUESTS: OnceLock<Requests> = OnceLock::new();
72    REQUESTS.get_or_init(Requests::default)
73}
74
75/// At most this many requests wait at once; the oldest goes first.
76const MAX_PENDING: usize = 32;
77
78impl Requests {
79    /// Asks the user; the receiver gets their answer. Asking again for the
80    /// same version (the same files and the same signing key) joins the
81    /// request already waiting; any other request for the widget is
82    /// replaced, its waiters declined. The key counts because `widget.sig`
83    /// isn't in the hash: a re-signed package must be shown with its new
84    /// signer (SPEC_WIDGET_SHARING_2026_10_10.md §2.3).
85    pub fn ask(&self, req: WidgetInstallRequest) -> oneshot::Receiver<Answer> {
86        let (tx, rx) = oneshot::channel();
87        let mut pending = self.pending.lock().unwrap_or_else(|p| p.into_inner());
88        let same = |r: &WidgetInstallRequest| r.id == req.id && r.hash == req.hash && r.signature.fingerprint == req.signature.fingerprint;
89        pending.retain_mut(|(r, waiters)| {
90            if r.id != req.id || same(r) {
91                return true;
92            }
93            for tx in waiters.drain(..) {
94                let _ = tx.send(Answer::Declined);
95            }
96            false
97        });
98        if let Some((kept, waiters)) = pending.iter_mut().find(|(r, _)| same(r)) {
99            // Agents in two panes wait on one request: it names no single pane, so the window asks.
100            if kept.block_id != req.block_id {
101                kept.block_id.clear();
102            }
103            waiters.push(tx);
104        } else {
105            if pending.len() >= MAX_PENDING {
106                pending.remove(0);
107            }
108            pending.push((req, vec![tx]));
109        }
110        rx
111    }
112
113    /// The user's answer for `id` at `hash`; returns whether anything waited.
114    /// Any answer about a widget also ends requests for its other versions,
115    /// which the user has now seen past.
116    pub fn answer(&self, id: &str, hash: &str, answer: Answer) -> bool {
117        let mut pending = self.pending.lock().unwrap_or_else(|p| p.into_inner());
118        let mut found = false;
119        pending.retain_mut(|(r, waiters)| {
120            if r.id != id {
121                return true;
122            }
123            let this_version = r.hash == hash;
124            found |= this_version;
125            for tx in waiters.drain(..) {
126                let _ = tx.send(if this_version { answer } else { Answer::Declined });
127            }
128            false
129        });
130        found
131    }
132
133    /// Declines every request for `id`, whatever version (its package was
134    /// uninstalled); returns whether any waited.
135    pub fn decline_all(&self, id: &str) -> bool {
136        let mut pending = self.pending.lock().unwrap_or_else(|p| p.into_inner());
137        let before = pending.len();
138        pending.retain_mut(|(r, waiters)| {
139            if r.id != id {
140                return true;
141            }
142            for tx in waiters.drain(..) {
143                let _ = tx.send(Answer::Declined);
144            }
145            false
146        });
147        pending.len() != before
148    }
149
150    pub fn list(&self) -> Vec<WidgetInstallRequest> {
151        self.pending.lock().unwrap_or_else(|p| p.into_inner()).iter().map(|(r, _)| r.clone()).collect()
152    }
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    fn req(id: &str, hash: &str, agent: &str) -> WidgetInstallRequest {
160        WidgetInstallRequest {
161            id: id.into(),
162            hash: hash.into(),
163            name: id.into(),
164            version: "1.0.0".into(),
165            description: None,
166            author: None,
167            kind: WidgetKind::Sandboxed,
168            permissions: vec![],
169            signature: crate::backend::widget::signature::describe(id, None, &Default::default()),
170            agent: agent.into(),
171            block_id: String::new(),
172            requested_ms: 0,
173        }
174    }
175
176    #[tokio::test]
177    async fn a_second_asker_in_another_pane_leaves_the_request_with_no_single_pane() {
178        let r = Requests::default();
179        let mut first = req("acme.x", "h1", "a");
180        first.block_id = "b1".into();
181        let _a = r.ask(first.clone());
182        let _again = r.ask(first.clone());
183        assert_eq!(r.list()[0].block_id, "b1", "the same pane asking again keeps its card");
184        let mut other = first.clone();
185        other.agent = "b".into();
186        other.block_id = "b2".into();
187        let _b = r.ask(other);
188        assert_eq!(r.list().len(), 1);
189        assert_eq!(r.list()[0].block_id, "", "two panes wait on it: the window asks");
190    }
191
192    #[tokio::test]
193    async fn a_re_signed_package_replaces_the_waiting_request() {
194        let r = Requests::default();
195        let first = r.ask(req("acme.x", "h1", "a"));
196        let mut resigned = req("acme.x", "h1", "a");
197        resigned.signature.fingerprint = Some("AAAA-BBBB-CCCC-DDDD".into());
198        let second = r.ask(resigned);
199        assert_eq!(first.await.unwrap(), Answer::Declined, "the old signer's prompt is gone");
200        let list = r.list();
201        assert_eq!(list.len(), 1);
202        assert_eq!(list[0].signature.fingerprint.as_deref(), Some("AAAA-BBBB-CCCC-DDDD"));
203        assert!(r.answer("acme.x", "h1", Answer::Approved));
204        assert_eq!(second.await.unwrap(), Answer::Approved);
205    }
206
207    #[tokio::test]
208    async fn the_users_answer_reaches_every_agent_that_asked_for_that_version() {
209        let r = Requests::default();
210        let a = r.ask(req("acme.x", "h1", "Lark"));
211        let b = r.ask(req("acme.x", "h1", "Korp"));
212        assert_eq!(r.list().len(), 1, "one prompt per version");
213        assert!(r.answer("acme.x", "h1", Answer::Approved));
214        assert_eq!(a.await.unwrap(), Answer::Approved);
215        assert_eq!(b.await.unwrap(), Answer::Approved);
216        assert!(r.list().is_empty());
217        assert!(!r.answer("acme.x", "h1", Answer::Approved), "nothing left to answer");
218    }
219
220    #[tokio::test]
221    async fn uninstalling_declines_the_widgets_requests() {
222        let r = Requests::default();
223        let waiting = r.ask(req("acme.x", "h1", "Lark"));
224        let other = r.ask(req("acme.y", "h1", "Lark"));
225        assert!(r.decline_all("acme.x"));
226        assert_eq!(waiting.await.unwrap(), Answer::Declined);
227        assert_eq!(r.list().iter().map(|q| q.id.as_str()).collect::<Vec<_>>(), ["acme.y"]);
228        assert!(!r.decline_all("acme.x"), "nothing left for it");
229        drop(other);
230    }
231
232    #[tokio::test]
233    async fn a_newer_version_replaces_the_older_request() {
234        let r = Requests::default();
235        let old = r.ask(req("acme.x", "h1", "Lark"));
236        let new = r.ask(req("acme.x", "h2", "Lark"));
237        assert_eq!(old.await.unwrap(), Answer::Declined, "the old request is declined");
238        assert_eq!(r.list().iter().map(|q| q.hash.as_str()).collect::<Vec<_>>(), ["h2"]);
239        let other = r.ask(req("acme.y", "h9", "Lark"));
240        r.answer("acme.x", "h2", Answer::Declined);
241        assert_eq!(new.await.unwrap(), Answer::Declined);
242        assert_eq!(r.list().len(), 1, "another widget's request stays");
243        drop(other);
244    }
245}