1use 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
36pub(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 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
54fn 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#[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 t.retain(|id, _| crate::backend::sensitive_requests::registry().get(id).is_some_and(|r| r.status.is_open()));
90 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
99pub(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 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
123pub(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 #[serde(default)]
140 auth: Option<agentmux_common::api_types::UiAutomationAuth>,
141 #[serde(default)]
143 wait_secs: Option<u64>,
144}
145
146pub(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 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 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 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 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 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 #[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 send(&app, post("/api/v1/widgets/install", &[], json!({ "path": path, "agent": "AgentMux", "wait_secs": 20 }))).await
311 })
312 };
313 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 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 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 #[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 let (status, body) = install("/workspace/mine".to_string()).await;
375 assert_eq!(status, StatusCode::BAD_REQUEST, "{body}");
376 }
377}