Skip to main content

agentmux_srv/server/
widget_agent_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What agents can do with widgets
5//! (docs/specs/SPEC_USER_WIDGETS_AND_WIDGET_API_2026_10_09.md §10), for
6//! agentmux-mcp's `WidgetList`, `WidgetInstall` and `OpenWidget`: list the
7//! packages, and install one and wait for the user's answer. An agent never
8//! approves: the prompt is the user's, and only the host carries the answer.
9
10use std::sync::Arc;
11use std::time::Duration;
12
13use axum::extract::State;
14use axum::http::StatusCode;
15use axum::response::{IntoResponse, Response};
16use axum::Json;
17use serde::Deserialize;
18use serde_json::json;
19
20use crate::backend::rpc::engine::WshRpcEngine;
21use crate::backend::widget::packages::{self, WidgetKind, WidgetPackageInfo, WidgetState};
22use crate::backend::widget::signature::SignatureState;
23use crate::backend::widget::requests::{self, Answer, WidgetInstallRequest};
24
25use super::AppState;
26
27const DEFAULT_WAIT: Duration = Duration::from_secs(300);
28const MAX_WAIT: Duration = Duration::from_secs(600);
29
30#[derive(Debug, Clone, serde::Serialize, Deserialize, ts_rs::TS)]
31#[ts(export, export_to = "../../../frontend/types/rpc/")]
32pub struct WidgetRequestsResult {
33    pub requests: Vec<WidgetInstallRequest>,
34}
35
36/// Tells every UI the requests now waiting.
37pub(crate) fn publish_requests(state: &AppState) {
38    let event = crate::backend::mps_events::WidgetRequestsEvent { requests: requests::requests().list() };
39    state.broker.publish_event::<crate::backend::mps_events::WidgetRequests>(&event, vec![], 0);
40}
41
42pub fn register(engine: &Arc<WshRpcEngine>) {
43    // widgets.requests: the install requests waiting for the user, for a UI
44    // that starts after they were made.
45    engine.register_typed("widgets.requests", |_req: serde_json::Value, _ctx| async move {
46        Ok(WidgetRequestsResult { requests: requests::requests().list() })
47    });
48}
49
50fn error(status: StatusCode, message: impl Into<String>) -> Response {
51    (status, Json(json!({ "error": message.into() }))).into_response()
52}
53
54/// Who the prompt says is asking: the agent whose signature verified, or,
55/// without one, a plain "not a verified agent" (never a name the caller chose).
56/// Its pane comes with it, the one the waiting tone plays for.
57fn asking_agent(state: &AppState, auth: Option<&agentmux_common::api_types::UiAutomationAuth>) -> (String, Option<String>) {
58    const UNVERIFIED: &str = "Something on this computer (not a verified agent)";
59    match auth {
60        Some(a) => match super::ui_handlers::verified_block_id(state, None, a) {
61            Ok(pane) => (a.agent_id.chars().take(64).collect(), Some(pane)),
62            Err(e) => {
63                tracing::warn!(claimed = %a.agent_id, error = %e, "a widget install's signed identity didn't verify");
64                (UNVERIFIED.to_string(), None)
65            }
66        },
67        None => (UNVERIFIED.to_string(), None),
68    }
69}
70
71/// The package an install request was filed for, by the request's id: the runner approves
72/// exactly this version and signer, so a package changed in the meantime is not approved.
73#[derive(Debug, Clone, PartialEq, Eq)]
74pub(crate) struct InstallTarget {
75    pub id: String,
76    pub hash: String,
77    pub signer: String,
78}
79
80fn targets() -> std::sync::MutexGuard<'static, std::collections::HashMap<String, InstallTarget>> {
81    static TARGETS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, InstallTarget>>> = std::sync::OnceLock::new();
82    TARGETS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner())
83}
84
85pub(crate) fn remember_target(request_id: &str, target: InstallTarget) {
86    let mut t = targets();
87    // A request that ended without running (denied, vetoed, withdrawn) leaves no use for its entry,
88    // and what stays is bounded by the open requests there can be.
89    t.retain(|id, _| crate::backend::sensitive_requests::registry().get(id).is_some_and(|r| r.status.is_open()));
90    // The content is part of what the request shows, so a request joined is for the same content;
91    // the first target stands in any case.
92    t.entry(request_id.to_string()).or_insert(target);
93}
94
95pub(crate) fn take_target(request_id: &str) -> Option<InstallTarget> {
96    targets().remove(request_id)
97}
98
99/// The facts a widget install request shows the person: every permission, who signed it, and
100/// plainly when it is a trusted widget (full access to AgentMux).
101pub(crate) fn install_facts(pkg: &WidgetPackageInfo) -> std::collections::BTreeMap<String, String> {
102    let name: String = pkg.name.chars().take(80).collect();
103    let publisher = match (&pkg.signature.state, &pkg.signature.fingerprint) {
104        (SignatureState::Unsigned, _) | (_, None) => format!("{} (unsigned)", pkg.signature.publisher),
105        (SignatureState::KeyChanged, Some(f)) => format!("{} (signed by a different key than before, {f})", pkg.signature.publisher),
106        (_, Some(f)) => format!("{} (signed, key {f})", pkg.signature.publisher),
107    };
108    let permissions = if pkg.kind == WidgetKind::Trusted {
109        "TRUSTED: full access to AgentMux".to_string()
110    } else if pkg.permissions.is_empty() {
111        "none".to_string()
112    } else {
113        pkg.permissions.join(", ")
114    };
115    // The start of the content's hash: different files are a different request, never a join.
116    let content: String = pkg.hash.chars().take(12).collect();
117    [("widget", format!("{name} ({} {}, content {content})", pkg.id, pkg.version)), ("publisher", publisher), ("permissions", permissions)]
118        .into_iter()
119        .map(|(k, v)| (k.to_string(), v))
120        .collect()
121}
122
123/// `GET /api/v1/widgets`: every package and its state.
124pub(super) async fn handle_widgets_list() -> Response {
125    match packages::service() {
126        Some(s) => Json(json!({ "packages": s.list() })).into_response(),
127        None => error(StatusCode::SERVICE_UNAVAILABLE, "widget packages aren't available on this AgentMux"),
128    }
129}
130
131#[derive(Debug, Deserialize)]
132pub(super) struct InstallBody {
133    path: String,
134    #[serde(default)]
135    replace: bool,
136    /// The asking agent's signed identity, which names it in the prompt.
137    /// Anything holding the auth key can call this route, so a name in the
138    /// body proves nothing; a signature only that agent can make does.
139    #[serde(default)]
140    auth: Option<agentmux_common::api_types::UiAutomationAuth>,
141    /// How long to wait for the user's answer.
142    #[serde(default)]
143    wait_secs: Option<u64>,
144}
145
146/// `POST /api/v1/widgets/install`: copy the package in and, for a verified agent, file a
147/// sensitive request to install it (answered at once with the request's id; the agent is told as
148/// it goes). Without a verified agent, ask the user and answer when they do (or when the wait
149/// runs out, with the request left for them to answer later in Settings → Widgets).
150pub(super) async fn handle_widgets_install(
151    State(state): State<AppState>,
152    grant: Option<axum::Extension<crate::backend::container::credential::ContainerGrant>>,
153    Json(mut body): Json<InstallBody>,
154) -> Response {
155    let Some(svc) = packages::service() else {
156        return error(StatusCode::SERVICE_UNAVAILABLE, "widget packages aren't available on this AgentMux");
157    };
158    // A container agent builds the widget under its `/workspace`, a folder of the host's; nothing else of the host's is read,
159    // and the copy checks every file it opens against that folder (`install_within`).
160    let mut workspace = None;
161    if let Some(axum::Extension(grant)) = grant {
162        let host_path = super::container_workspace::workspace_of(&state, &grant.block_id)
163            .ok_or_else(|| "this container agent has no workspace folder to install from".to_string())
164            .and_then(|w| super::container_workspace::inside(&w, &body.path).map(|p| (w, p)));
165        match host_path {
166            Ok((w, p)) => (workspace, body.path) = (Some(w), p),
167            Err(e) => return error(StatusCode::FORBIDDEN, format!("{e} Build the widget under /workspace and install it from there.")),
168        }
169    }
170    let (dir, source) = (svc.widgets_dir.clone(), std::path::PathBuf::from(&body.path));
171    let installed = tokio::task::spawn_blocking(move || match workspace {
172        Some(root) => packages::install_within(&dir, &source, body.replace, &root),
173        None => packages::install(&dir, &source, body.replace),
174    })
175    .await;
176    let id = match installed {
177        Ok(Ok(id)) => id,
178        Ok(Err(e)) => return error(StatusCode::BAD_REQUEST, e),
179        Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
180    };
181    let packages = packages::refresh_off_thread(&state.config_watcher, &state.event_bus, &state.broker).await;
182    let Some(pkg) = packages.into_iter().find(|p| p.id == id) else {
183        return error(StatusCode::INTERNAL_SERVER_ERROR, format!("{id} was copied in but isn't listed"));
184    };
185    let views: Vec<String> = pkg.panes.iter().map(|p| p.view.clone()).collect();
186    // Who signed it, so the agent can tell the user what the prompt says
187    // (SPEC_WIDGET_SHARING_2026_10_10.md §2.3).
188    let signature = pkg.signature.clone();
189    match pkg.state {
190        WidgetState::Approved => return Json(json!({ "status": "installed", "id": id, "views": views, "signature": signature })).into_response(),
191        WidgetState::Invalid => return error(StatusCode::BAD_REQUEST, pkg.error.unwrap_or_else(|| "the package isn't valid".into())),
192        WidgetState::Disabled => {
193            return Json(json!({ "status": "disabled", "id": id, "views": views, "signature": signature, "message": "the user turned this widget off; it stays off" }))
194                .into_response()
195        }
196        _ => {}
197    }
198    let (agent, pane) = asking_agent(&state, body.auth.as_ref());
199    // A verified agent's install is a sensitive request: the super agent decides and the person
200    // can veto the countdown. Something that isn't a verified agent has no one to answer for it,
201    // so the person is asked, as before.
202    if let Some(uid) = pane.as_ref().and_then(|_| crate::backend::reactive::get_global_handler().get_agent(&agent)).and_then(|r| r.uid) {
203        let reason = format!("install the widget {} for the user", pkg.name);
204        let facts = install_facts(&pkg);
205        // The person is shown every permission, never a shortened list: too many to show whole is
206        // refused, and the agent is told what to do.
207        if facts["permissions"].chars().count() > crate::backend::sensitive_ops::VALUE_MAX {
208            return error(
209                StatusCode::BAD_REQUEST,
210                format!("{id} asks for too many permissions to show the person whole ({} characters, at most {}); ask for fewer and install again", facts["permissions"].chars().count(), crate::backend::sensitive_ops::VALUE_MAX),
211            );
212        }
213        return match super::sensitive_handlers::file_request(&state, &uid, &agent, "widget_install", &facts, &reason).await {
214            Ok(filed) => {
215                let request_id = filed["id"].as_str().unwrap_or_default().to_string();
216                remember_target(&request_id, InstallTarget { id: id.clone(), hash: pkg.hash.clone(), signer: pkg.signature.fingerprint.clone().unwrap_or_default() });
217                Json(json!({
218                    "status": "requested",
219                    "id": id,
220                    "request": request_id,
221                    "views": views,
222                    "signature": signature,
223                    "review": filed["review"],
224                }))
225                .into_response()
226            }
227            Err(e) => error(StatusCode::BAD_REQUEST, e),
228        };
229    }
230    let answer = requests::requests().ask(WidgetInstallRequest::of(&pkg, &agent, pane.as_deref().unwrap_or("")));
231    publish_requests(&state);
232    // The asking agent's pane (or, unverified, no pane) waits on the user
233    // until this returns: the waiting tone and notification for it.
234    let _asking = crate::backend::user_attention::Asking::start(
235        &state.broker,
236        &state.mstore,
237        pane.as_deref().unwrap_or(""),
238        "widget",
239        &format!("{agent} wants to install {}", pkg.name),
240    );
241    tracing::info!(id = %id, agent = %agent, "an agent asked to install a widget; waiting for the user");
242    let wait = body.wait_secs.map(Duration::from_secs).unwrap_or(DEFAULT_WAIT).min(MAX_WAIT);
243    match tokio::time::timeout(wait, answer).await {
244        Ok(Ok(Answer::Approved)) => Json(json!({ "status": "installed", "id": id, "views": views, "signature": signature })).into_response(),
245        Ok(Ok(Answer::Declined)) | Ok(Err(_)) => Json(json!({
246            "status": "declined",
247            "id": id,
248            "signature": signature,
249            "message": "the user didn't approve it; it stays in Settings → Widgets until they approve or remove it",
250        }))
251        .into_response(),
252        Err(_) => Json(json!({
253            "status": "pending",
254            "id": id,
255            "signature": signature,
256            "message": "the user hasn't answered yet; the request stays open in AgentMux",
257        }))
258        .into_response(),
259    }
260}
261
262#[cfg(test)]
263mod tests {
264    use super::*;
265    use axum::body::Body;
266    use axum::http::Request;
267    use tower::ServiceExt;
268
269    async fn send(app: &axum::Router, req: Request<Body>) -> (StatusCode, serde_json::Value) {
270        let resp = app.clone().oneshot(req).await.unwrap();
271        let status = resp.status();
272        let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
273        (status, serde_json::from_slice(&body).unwrap_or_default())
274    }
275
276    fn post(uri: &str, headers: &[(&str, &str)], body: serde_json::Value) -> Request<Body> {
277        let mut b = Request::builder().uri(uri).method("POST").header("X-AuthKey", "test-secret-key").header("Content-Type", "application/json");
278        for (k, v) in headers {
279            b = b.header(*k, *v);
280        }
281        b.body(Body::from(body.to_string())).unwrap()
282    }
283
284    // §10: an agent's install waits for the user; its auth key can't answer
285    // for them, only the host can, and the agent then hears "installed".
286    #[tokio::test]
287    async fn an_agents_install_waits_for_the_users_answer_through_the_host() {
288        let tmp = tempfile::tempdir().unwrap();
289        packages::WidgetPackages::for_tests();
290        let src = tmp.path().join("src").join("acme.agentmade");
291        std::fs::create_dir_all(&src).unwrap();
292        std::fs::write(
293            src.join("widget.json"),
294            json!({ "manifestVersion": 1, "id": "acme.agentmade", "name": "Made by an agent", "version": "1.0.0", "kind": "sandboxed",
295                    "permissions": ["storage"], "contributes": { "panes": [{ "name": "main" }] } })
296                .to_string(),
297        )
298        .unwrap();
299        std::fs::write(src.join("index.html"), "<p>hi</p>").unwrap();
300
301        let state = crate::server::tests::test_state();
302        *state.host_ipc.lock().await = Some(crate::server::state::HostIpc { port: 1, token: "host-ipc-token".into() });
303        let app = crate::server::build_router(state);
304
305        let install = {
306            let app = app.clone();
307            let path = src.to_string_lossy().into_owned();
308            tokio::spawn(async move {
309                // A name in the body is ignored: only a signed identity names the agent.
310                send(&app, post("/api/v1/widgets/install", &[], json!({ "path": path, "agent": "AgentMux", "wait_secs": 20 }))).await
311            })
312        };
313        // The request shows up for the user.
314        let mut req = None;
315        for _ in 0..100 {
316            req = requests::requests().list().into_iter().find(|r| r.id == "acme.agentmade");
317            if req.is_some() {
318                break;
319            }
320            tokio::time::sleep(Duration::from_millis(50)).await;
321        }
322        let req = req.expect("the install asks the user");
323        assert_eq!(req.agent, "Something on this computer (not a verified agent)");
324        assert_eq!(req.permissions, ["storage".to_string()]);
325        // Only the host can answer for the user.
326        let decision = json!({ "id": "acme.agentmade", "hash": req.hash, "decision": "approve" });
327        let (s, _) = send(&app, post("/api/v1/host/widget_approval", &[], decision.clone())).await;
328        assert_eq!(s, StatusCode::FORBIDDEN);
329        assert!(!install.is_finished(), "still waiting");
330        let (s, _) = send(&app, post("/api/v1/host/widget_approval", &[("X-Host-Token", "host-ipc-token")], decision)).await;
331        assert_eq!(s, StatusCode::OK);
332        let (s, body) = install.await.unwrap();
333        assert_eq!(s, StatusCode::OK, "{body}");
334        assert_eq!(body["status"], "installed");
335        assert_eq!(body["views"], json!(["ext:acme.agentmade/main"]));
336        // By then the list says so too, for the agent's next step, OpenWidget.
337        let listed = packages::service().unwrap().list().into_iter().find(|p| p.id == "acme.agentmade").unwrap();
338        assert_eq!(listed.state, WidgetState::Approved);
339        assert!(requests::requests().list().iter().all(|r| r.id != "acme.agentmade"));
340    }
341    // A container agent installs from its `/workspace` (a folder of the host's) and from nowhere else on the host.
342    #[tokio::test]
343    async fn a_container_agent_installs_only_from_its_workspace() {
344        packages::WidgetPackages::for_tests();
345        let tmp = tempfile::tempdir().unwrap();
346        let (ws, outside) = (tmp.path().join("ws"), tmp.path().join("outside"));
347        std::fs::create_dir_all(ws.join("mine")).unwrap();
348        std::fs::create_dir_all(&outside).unwrap();
349        let state = crate::server::tests::test_state();
350        let mut meta = crate::backend::obj::MetaMapType::new();
351        meta.insert("cmd:cwd".to_string(), json!(ws.to_string_lossy()));
352        let mut block = crate::backend::obj::Block { oid: uuid::Uuid::new_v4().to_string(), meta, ..Default::default() };
353        state.mstore.insert(&mut block).unwrap();
354        let token = crate::backend::container::credential::token_for_block(&block.oid, Some("agent-tok"));
355        let app = crate::server::build_router(state);
356        let install = |path: String| {
357            let app = app.clone();
358            let token = token.clone();
359            async move {
360                let req = Request::builder()
361                    .uri("/api/v1/widgets/install")
362                    .method("POST")
363                    .header("X-AuthKey", token)
364                    .header("Content-Type", "application/json")
365                    .body(Body::from(json!({ "path": path }).to_string()))
366                    .unwrap();
367                send(&app, req).await
368            }
369        };
370        let (status, body) = install(outside.to_string_lossy().into_owned()).await;
371        assert_eq!(status, StatusCode::FORBIDDEN, "{body}");
372        assert!(body.to_string().contains("under /workspace"), "{body}");
373        // Its own name for the folder reaches the install itself, which finds no widget in it.
374        let (status, body) = install("/workspace/mine".to_string()).await;
375        assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
376    }
377}