Skip to main content

agentmux_srv/server/
widget_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The widget packages' RPCs and routes
5//! (docs/specs/SPEC_USER_WIDGETS_AND_WIDGET_API_2026_10_09.md §5.2, §8):
6//! listing and managing packages, serving an approved package's files, and
7//! the user's approval, which only the host can carry.
8
9use std::sync::Arc;
10
11use axum::extract::{Path as UrlPath, State};
12use axum::http::{header, HeaderMap, HeaderValue, StatusCode};
13use axum::response::{IntoResponse, Response};
14use axum::Json;
15use serde::{Deserialize, Serialize};
16use serde_json::json;
17
18use crate::backend::rpc::engine::WshRpcEngine;
19use crate::backend::widget::packages::{self, FileError, WidgetKind, WidgetPackageInfo};
20use crate::backend::widget::requests;
21
22use super::AppState;
23
24#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
25#[ts(export, export_to = "../../../frontend/types/rpc/")]
26pub struct WidgetPackagesResult {
27    pub packages: Vec<WidgetPackageInfo>,
28    /// Publishers pinned to a key here (SPEC_WIDGET_SHARING_2026_10_10.md §2.2).
29    #[serde(default)]
30    pub publishers: Vec<crate::backend::widget::signature::WidgetPublisherPin>,
31}
32
33/// The widget catalog, checked, with what is installed here
34/// (SPEC_WIDGET_SHARING_2026_10_10.md §4.5).
35#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
36#[ts(export, export_to = "../../../frontend/types/rpc/")]
37pub struct WidgetCatalogResult {
38    pub url: String,
39    pub items: Vec<crate::backend::widget::catalog::WidgetCatalogItem>,
40}
41
42/// The list, with the publishers this instance has pinned.
43fn packages_result(packages: Vec<WidgetPackageInfo>) -> WidgetPackagesResult {
44    WidgetPackagesResult { packages, publishers: svc().map(|s| s.publishers()).unwrap_or_default() }
45}
46
47#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
48#[ts(export, export_to = "../../../frontend/types/rpc/")]
49pub struct WidgetIdReq {
50    pub id: String,
51}
52
53#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
54#[ts(export, export_to = "../../../frontend/types/rpc/")]
55pub struct WidgetSetEnabledReq {
56    pub id: String,
57    pub enabled: bool,
58}
59
60pub use crate::backend::rpc_types::WidgetInstallReq;
61
62#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
63#[ts(export, export_to = "../../../frontend/types/rpc/")]
64pub struct WidgetInstallResult {
65    pub id: String,
66    pub packages: Vec<WidgetPackageInfo>,
67}
68
69/// "Pin this section to the widget bar": the section's widget-bar entry, added to the user's
70/// widgets.json when no entry opens that section yet (pane-sections.ts).
71#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
72#[ts(export, export_to = "../../../frontend/types/rpc/")]
73pub struct WidgetSectionEntryReq {
74    /// The pane's view (`warden`).
75    pub view: String,
76    /// The section, or `<section>/<its section>` (`vault/cards`).
77    pub section: String,
78    pub label: String,
79    /// A Font Awesome name.
80    pub icon: String,
81}
82
83#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
84#[ts(export, export_to = "../../../frontend/types/rpc/")]
85pub struct WidgetSectionEntryResult {
86    /// The entry's key in widgets.json, which is also its pin id (`section@warden-lan`, or
87    /// `section@warden-lan-2` when the user's file already used that key for something else).
88    pub key: String,
89}
90
91/// The widgets.json key for a section's entry, or why the request can't make one. Names are
92/// lowercase letters, digits and `-`, with at most one `/` in the section.
93pub fn section_entry_key(req: &WidgetSectionEntryReq) -> Result<String, String> {
94    let name = |s: &str| !s.is_empty() && s.len() <= 40 && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
95    if !name(&req.view) {
96        return Err(format!("not a view name: {:?}", req.view));
97    }
98    let parts: Vec<&str> = req.section.split('/').collect();
99    if parts.len() > 2 || !parts.iter().all(|p| name(p)) {
100        return Err(format!("not a section: {:?}", req.section));
101    }
102    let label = req.label.trim();
103    if label.is_empty() || label.chars().count() > 60 {
104        return Err("a section entry needs a label of at most 60 characters".to_string());
105    }
106    if !name(&req.icon) {
107        return Err(format!("not an icon name: {:?}", req.icon));
108    }
109    Ok(format!("section@{}-{}", req.view, parts.join("-")))
110}
111
112#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
113#[ts(export, export_to = "../../../frontend/types/rpc/")]
114pub struct WidgetReadFileReq {
115    pub id: String,
116    pub hash: String,
117    pub path: String,
118}
119
120#[derive(Debug, Clone, Serialize, Deserialize, ts_rs::TS)]
121#[ts(export, export_to = "../../../frontend/types/rpc/")]
122pub struct WidgetReadFileResult {
123    pub content: String,
124}
125
126fn svc() -> Result<&'static Arc<packages::WidgetPackages>, String> {
127    packages::service().ok_or_else(|| "widget packages aren't available on this AgentMux".to_string())
128}
129
130pub fn register_widget_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
131    // A sandboxed widget's sessions and calls (W3), agents' install requests (W4).
132    super::widget_access_handlers::register(engine, state);
133    super::widget_agent_handlers::register(engine);
134    // Job templates share the widgets' signing and approval (jobs.templates.*).
135    super::job_template_handlers::register(engine);
136
137    engine.register_typed("widgets.list", |_req: serde_json::Value, _ctx| async move { widgets_list() });
138
139    let st = state.clone();
140    engine.register_typed("widgets.rescan", move |_req: serde_json::Value, _ctx| {
141        let st = st.clone();
142        async move { widgets_rescan(&st).await }
143    });
144
145    let st = state.clone();
146    engine.register_typed("widgets.setenabled", move |req: WidgetSetEnabledReq, _ctx| {
147        let st = st.clone();
148        async move { widgets_set_enabled(&st, req).await }
149    });
150
151    let st = state.clone();
152    engine.register_typed("widgets.install", move |req: WidgetInstallReq, _ctx| {
153        let st = st.clone();
154        async move { widgets_install(&st, req).await }
155    });
156
157    engine.register_typed("widgets.catalog", |_req: serde_json::Value, _ctx| async move { widgets_catalog().await });
158
159    let st = state.clone();
160    engine.register_typed("widgets.catalog.install", move |req: WidgetIdReq, _ctx| {
161        let st = st.clone();
162        async move { widgets_catalog_install(&st, req).await }
163    });
164
165    let st = state.clone();
166    engine.register_typed("widgets.uninstall", move |req: WidgetIdReq, _ctx| {
167        let st = st.clone();
168        async move { widgets_uninstall(&st, req).await }
169    });
170
171    let st = state.clone();
172    engine.register_typed("widgets.sectionentry", move |req: WidgetSectionEntryReq, _ctx| {
173        let st = st.clone();
174        async move { widgets_section_entry(&st, req).await }
175    });
176
177    engine.register_typed("widgets.readfile", |req: WidgetReadFileReq, _ctx| async move { widgets_read_file(req) });
178}
179
180/// widgets.list: every package and its state.
181pub(crate) fn widgets_list() -> Result<WidgetPackagesResult, String> {
182    Ok(packages_result(svc()?.list()))
183}
184
185/// widgets.rescan.
186pub(crate) async fn widgets_rescan(st: &AppState) -> Result<WidgetPackagesResult, String> {
187    svc()?;
188    Ok(packages_result(packages::refresh_off_thread(&st.config_watcher, &st.event_bus, &st.broker).await))
189}
190
191/// widgets.setenabled.
192pub(crate) async fn widgets_set_enabled(st: &AppState, req: WidgetSetEnabledReq) -> Result<WidgetPackagesResult, String> {
193    svc()?.set_enabled(&req.id, req.enabled)?;
194    Ok(packages_result(packages::refresh_off_thread(&st.config_watcher, &st.event_bus, &st.broker).await))
195}
196
197/// widgets.install: copy a package in. It doesn't run until the user
198/// approves it in the UI (the host-only route below).
199pub(crate) async fn widgets_install(st: &AppState, req: WidgetInstallReq) -> Result<WidgetInstallResult, String> {
200    let dir = svc()?.widgets_dir.clone();
201    let source = std::path::PathBuf::from(req.path.trim());
202    let id = tokio::task::spawn_blocking(move || packages::install(&dir, &source, req.replace))
203        .await
204        .map_err(|e| e.to_string())??;
205    tracing::info!(id = %id, "widget package installed (awaiting approval)");
206    let packages = packages::refresh_off_thread(&st.config_watcher, &st.event_bus, &st.broker).await;
207    Ok(WidgetInstallResult { id, packages })
208}
209
210/// widgets.catalog: the catalog's widgets, its signature checked against
211/// the key pinned in this AgentMux, each with what is installed here.
212pub(crate) async fn widgets_catalog() -> Result<WidgetCatalogResult, String> {
213    let url = crate::backend::widget::catalog::DEFAULT_CATALOG_URL.to_string();
214    let entries = crate::backend::widget::catalog::fetch(&url).await?;
215    Ok(WidgetCatalogResult { items: crate::backend::widget::catalog::items(entries, &svc()?.list()), url })
216}
217
218/// widgets.catalog.install: download a catalog widget, check it against
219/// the (freshly fetched and checked) index, and copy it in. Like any
220/// install, it doesn't run until the user approves it.
221pub(crate) async fn widgets_catalog_install(st: &AppState, req: WidgetIdReq) -> Result<WidgetInstallResult, String> {
222    use crate::backend::widget::catalog as wc;
223    let entries = wc::fetch(wc::DEFAULT_CATALOG_URL).await?;
224    let entry = entries.iter().find(|e| e.id == req.id).ok_or(format!("the catalog doesn't list {}", req.id))?;
225    let id = wc::install(&svc()?.widgets_dir, entry).await?;
226    tracing::info!(id = %id, version = %entry.version, "catalog widget installed (awaiting approval)");
227    let packages = packages::refresh_off_thread(&st.config_watcher, &st.event_bus, &st.broker).await;
228    Ok(WidgetInstallResult { id, packages })
229}
230
231/// widgets.uninstall: delete the package folder and its approval. A v1
232/// widget is a widgets.json entry, which stays the user's to edit.
233pub(crate) async fn widgets_uninstall(st: &AppState, req: WidgetIdReq) -> Result<WidgetPackagesResult, String> {
234    let s = svc()?;
235    let (dir, implied) = s.package_dir(&req.id).ok_or("no such widget")?;
236    if implied {
237        return Err(format!("{} comes from widgets.json: remove its entry there", req.id));
238    }
239    if !dir.starts_with(&s.widgets_dir) {
240        return Err("that widget isn't in the widgets folder".to_string());
241    }
242    // Its open panes stop first, so none can write its data back;
243    // then what it stored goes (Settings asked the user): if that
244    // fails, nothing is removed, so a reinstall can't find it again.
245    let sessions = crate::backend::widget::access::sessions();
246    sessions.begin_removal(&req.id);
247    let removed = async {
248        st.mstore.widget_storage_purge(&req.id).map_err(|e| format!("can't delete its data: {e}"))?;
249        tokio::task::spawn_blocking(move || std::fs::remove_dir_all(&dir))
250            .await
251            .map_err(|e| e.to_string())?
252            .map_err(|e| format!("can't remove it: {e}"))?;
253        s.forget(&req.id)?;
254        // A write that passed its check just before the panes stopped
255        // can land after the first purge; the package is gone now, so
256        // nothing can write again.
257        st.mstore.widget_storage_purge(&req.id).map_err(|e| format!("can't delete its data: {e}"))
258    }
259    .await;
260    if let Err(e) = removed {
261        sessions.end_removal(&req.id);
262        return Err(e);
263    }
264    tracing::info!(id = %req.id, "widget package uninstalled");
265    // Sessions stay refused until the list no longer has it.
266    let packages = packages::refresh_off_thread(&st.config_watcher, &st.event_bus, &st.broker).await;
267    sessions.end_removal(&req.id);
268    // An agent waiting to have it installed hears it won't be, and
269    // its prompt closes.
270    if requests::requests().decline_all(&req.id) {
271        super::widget_agent_handlers::publish_requests(st);
272    }
273    Ok(packages_result(packages))
274}
275
276/// widgets.sectionentry: "Pin this section to the widget bar". Adds the section's entry to
277/// the user's widgets.json and applies it before answering, so the bar can pin it at once.
278pub(crate) async fn widgets_section_entry(st: &AppState, req: WidgetSectionEntryReq) -> Result<WidgetSectionEntryResult, String> {
279    let key = section_entry_key(&req)?;
280    let entry = serde_json::json!({
281        "label": req.label.trim(),
282        "icon": req.icon,
283        "section": req.section,
284        "blockdef": { "meta": { "view": req.view } },
285    });
286    let (config, bus) = (st.config_watcher.clone(), st.event_bus.clone());
287    let key = tokio::task::spawn_blocking(move || crate::backend::user_widgets::add_section_entry(&config, &bus, &key, entry))
288        .await
289        .map_err(|e| e.to_string())??;
290    Ok(WidgetSectionEntryResult { key })
291}
292
293/// widgets.readfile: a trusted widget's module, for the loader. Only the
294/// approved version's bytes, checked like the files route.
295pub(crate) fn widgets_read_file(req: WidgetReadFileReq) -> Result<WidgetReadFileResult, String> {
296    let s = svc()?;
297    let pkg = s.list().into_iter().find(|p| p.id == req.id).ok_or("no such widget")?;
298    if pkg.kind != WidgetKind::Trusted {
299        return Err("only a trusted widget's module is read this way".to_string());
300    }
301    let key = pkg
302        .files_url
303        .as_deref()
304        .and_then(|u| u.trim_end_matches('/').rsplit('/').next())
305        .ok_or("that widget isn't approved and enabled")?
306        .to_string();
307    let bytes = s.read_file(&req.id, &req.hash, &key, &req.path).map_err(|e| match e {
308        FileError::NotFound => "no such file in the approved widget".to_string(),
309        FileError::Changed => "the widget changed since it was approved".to_string(),
310    })?;
311    Ok(WidgetReadFileResult { content: String::from_utf8_lossy(&bytes).into_owned() })
312}
313
314/// `GET /agentmux/widget-files/<id>/<hash>/<key>/<path>`: an approved,
315/// enabled package's file, as approved (spec §5.2). No auth key: an iframe
316/// loads these, and the key segment is what keeps other web pages out.
317pub(crate) async fn handle_widget_file(UrlPath((id, hash, key, path)): UrlPath<(String, String, String, String)>) -> Response {
318    let Ok(s) = svc() else {
319        return StatusCode::NOT_FOUND.into_response();
320    };
321    let s = s.clone();
322    let path_for_read = path.clone();
323    let read = tokio::task::spawn_blocking(move || s.read_file(&id, &hash, &key, &path_for_read)).await;
324    let bytes = match read {
325        Ok(Ok(b)) => b,
326        Ok(Err(FileError::Changed)) => {
327            return (StatusCode::CONFLICT, "this widget changed since it was approved").into_response();
328        }
329        _ => return StatusCode::NOT_FOUND.into_response(),
330    };
331    let mut resp = bytes.into_response();
332    let h = resp.headers_mut();
333    h.insert(header::CONTENT_TYPE, HeaderValue::from_static(packages::content_type(&path)));
334    h.insert(header::CONTENT_SECURITY_POLICY, HeaderValue::from_static(packages::WIDGET_CSP));
335    h.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
336    h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
337    h.insert(header::REFERRER_POLICY, HeaderValue::from_static("no-referrer"));
338    // A sandboxed widget's document has an opaque origin, so its module
339    // scripts load with `Origin: null` in CORS mode. The files aren't
340    // secret and no credentials ride along: any origin may read them.
341    h.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
342    resp
343}
344
345/// The widget SDK and its stylesheet (spec §7), served next to the widgets.
346const SDK_V1_JS: &str = include_str!("../../../../sdk/widget-sdk/v1.js");
347const SDK_V1_CSS: &str = include_str!("../../../../sdk/widget-sdk/am-widget.css");
348const SDK_V1_TYPES: &str = include_str!("../../../../sdk/widget-sdk/v1.d.ts");
349const SDK_README: &str = include_str!("../../../../sdk/widget-sdk/README.md");
350
351/// `GET /agentmux/widget-sdk/<file>`: `v1.js` and `am-widget.css`, which a
352/// widget's iframe imports like its own files, and `v1.d.ts` and
353/// `README.md`, the reference an agent writing a widget reads. No auth.
354pub(crate) async fn handle_widget_sdk(UrlPath(file): UrlPath<String>) -> Response {
355    let (body, ty) = match file.as_str() {
356        "v1.js" => (SDK_V1_JS, "text/javascript; charset=utf-8"),
357        "am-widget.css" => (SDK_V1_CSS, "text/css; charset=utf-8"),
358        "v1.d.ts" => (SDK_V1_TYPES, "text/plain; charset=utf-8"),
359        "README.md" => (SDK_README, "text/markdown; charset=utf-8"),
360        _ => return StatusCode::NOT_FOUND.into_response(),
361    };
362    let mut resp = body.into_response();
363    let h = resp.headers_mut();
364    h.insert(header::CONTENT_TYPE, HeaderValue::from_static(ty));
365    h.insert(header::X_CONTENT_TYPE_OPTIONS, HeaderValue::from_static("nosniff"));
366    h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
367    h.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
368    resp
369}
370
371/// `POST /api/v1/host/widget_approval`: the user's answer to an install
372/// prompt (spec §8.3), relayed by the CEF host with its own token. The
373/// instance auth key, which every agent has, isn't enough.
374pub(crate) async fn handle_host_widget_approval(
375    State(state): State<AppState>,
376    headers: HeaderMap,
377    Json(body): Json<serde_json::Value>,
378) -> Response {
379    if !super::ui_handlers::from_host(&state, &headers).await {
380        return (StatusCode::FORBIDDEN, Json(json!({ "ok": false, "error": "only the AgentMux host can approve a widget" })))
381            .into_response();
382    }
383    let s = |k: &str| body.get(k).and_then(|v| v.as_str()).unwrap_or("").to_string();
384    let (id, hash, decision, signer) = (s("id"), s("hash"), s("decision"), s("signer"));
385    let Ok(service) = svc() else {
386        return (StatusCode::NOT_FOUND, Json(json!({ "ok": false, "error": "widget packages aren't available" }))).into_response();
387    };
388    let result = match decision.as_str() {
389        "approve" => service.approve(&id, &hash, &signer),
390        "cancel" => Ok(()),
391        // Settings → Widgets → Forget key: `id` names the publisher
392        // (SPEC_WIDGET_SHARING_2026_10_10.md §2.3). Only the user can, like
393        // an approval: forgetting a key lets another key pin that publisher.
394        "forget_key" => service.forget_publisher(&id),
395        _ => Err(format!("unknown decision {decision:?}")),
396    };
397    match result {
398        Ok(()) => {
399            if decision == "approve" {
400                tracing::info!(id = %id, "widget package approved by the user");
401            }
402            let packages = packages::refresh_off_thread(&state.config_watcher, &state.event_bus, &state.broker).await;
403            if decision == "forget_key" {
404                tracing::info!(publisher = %id, "widget publisher key forgotten by the user");
405                return (StatusCode::OK, Json(json!({ "ok": true, "packages": packages }))).into_response();
406            }
407            // An agent waiting on this install hears the answer, once the
408            // package list says so too: its next step is often OpenWidget.
409            // "Installed" only if the list, rescanned just now, still has that
410            // version approved: a reinstall in the meantime replaced it.
411            let approved_now = packages.iter().any(|p| p.id == id && p.hash == hash && p.state == packages::WidgetState::Approved);
412            let answer = if decision == "approve" && approved_now {
413                requests::Answer::Approved
414            } else {
415                requests::Answer::Declined
416            };
417            if requests::requests().answer(&id, &hash, answer) {
418                super::widget_agent_handlers::publish_requests(&state);
419            }
420            (StatusCode::OK, Json(json!({ "ok": true, "packages": packages }))).into_response()
421        }
422        Err(e) => (StatusCode::CONFLICT, Json(json!({ "ok": false, "error": e }))).into_response(),
423    }
424}
425
426#[cfg(test)]
427mod tests {
428    use super::*;
429    use axum::body::Body;
430
431    #[test]
432    fn a_section_entry_is_keyed_by_its_pane_and_section_and_checked() {
433        let req = |view: &str, section: &str, label: &str, icon: &str| WidgetSectionEntryReq {
434            view: view.into(),
435            section: section.into(),
436            label: label.into(),
437            icon: icon.into(),
438        };
439        assert_eq!(section_entry_key(&req("warden", "lan", "LAN", "network-wired")).unwrap(), "section@warden-lan");
440        assert_eq!(section_entry_key(&req("warden", "vault/cards", "Cards", "credit-card")).unwrap(), "section@warden-vault-cards");
441        for bad in [
442            req("Warden", "lan", "LAN", "x"),
443            req("warden", "a/b/c", "LAN", "x"),
444            req("warden", "../lan", "LAN", "x"),
445            req("warden", "lan", " ", "x"),
446            req("warden", "lan", &"L".repeat(61), "x"),
447            req("warden", "lan", "LAN", "x\" onclick=\""),
448        ] {
449            assert!(section_entry_key(&bad).is_err(), "{bad:?}");
450        }
451    }
452    use axum::http::Request;
453    use tower::ServiceExt;
454
455    async fn send(app: &axum::Router, req: Request<Body>) -> (StatusCode, HeaderMap, Vec<u8>) {
456        let resp = app.clone().oneshot(req).await.unwrap();
457        let (status, headers) = (resp.status(), resp.headers().clone());
458        let body = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap().to_vec();
459        (status, headers, body)
460    }
461
462    fn approval(headers: &[(&str, &str)], id: &str, hash: &str) -> Request<Body> {
463        let mut b = Request::builder()
464            .uri("/api/v1/host/widget_approval")
465            .method("POST")
466            .header("X-AuthKey", "test-secret-key")
467            .header("Content-Type", "application/json");
468        for (k, v) in headers {
469            b = b.header(*k, *v);
470        }
471        b.body(Body::from(json!({ "id": id, "hash": hash, "decision": "approve" }).to_string())).unwrap()
472    }
473
474    fn get(uri: &str) -> Request<Body> {
475        Request::builder().uri(uri).body(Body::empty()).unwrap()
476    }
477
478    // SPEC_USER_WIDGETS_AND_WIDGET_API_2026_10_09.md §5.2, §8.3: nothing is
479    // served before the user approves; the instance auth key, which every
480    // agent has, can't approve; only the host's token can; and an edit after
481    // approval is never served.
482    #[tokio::test]
483    async fn only_the_host_can_approve_and_only_approved_bytes_are_served() {
484        let svc = packages::WidgetPackages::for_tests();
485        let pkg = svc.widgets_dir.join("acme.test");
486        std::fs::create_dir_all(&pkg).unwrap();
487        std::fs::write(
488            pkg.join("widget.json"),
489            json!({ "manifestVersion": 1, "id": "acme.test", "name": "Test", "version": "1.0.0", "contributes": { "panes": [{ "name": "main" }] } })
490                .to_string(),
491        )
492        .unwrap();
493        std::fs::write(pkg.join("index.html"), "<p>approved</p>").unwrap();
494        let hash = svc.rescan(&Default::default()).into_iter().find(|p| p.id == "acme.test").unwrap().hash;
495        let key = packages::files_key("test-secret-key", "acme.test", &hash);
496        let file_uri = format!("/agentmux/widget-files/acme.test/{hash}/{key}/index.html");
497
498        let state = crate::server::tests::test_state();
499        *state.host_ipc.lock().await = Some(crate::server::state::HostIpc { port: 1, token: "host-ipc-token".into() });
500        let app = crate::server::build_router(state);
501
502        let (s, _, _) = send(&app, get(&file_uri)).await;
503        assert_eq!(s, StatusCode::NOT_FOUND, "not served before approval");
504
505        let (s, _, _) = send(&app, approval(&[], "acme.test", &hash)).await;
506        assert_eq!(s, StatusCode::FORBIDDEN, "the auth key alone can't approve");
507        let (s, _, _) = send(&app, approval(&[("X-Host-Token", "guess")], "acme.test", &hash)).await;
508        assert_eq!(s, StatusCode::FORBIDDEN);
509        let (s, _, _) = send(&app, approval(&[("X-Host-Token", "host-ipc-token")], "acme.test", "stale")).await;
510        assert_eq!(s, StatusCode::CONFLICT, "an approval of another version is refused");
511        let (s, _, body) = send(&app, approval(&[("X-Host-Token", "host-ipc-token")], "acme.test", &hash)).await;
512        assert_eq!(s, StatusCode::OK, "{}", String::from_utf8_lossy(&body));
513
514        let (s, headers, body) = send(&app, get(&file_uri)).await;
515        assert_eq!(s, StatusCode::OK);
516        assert_eq!(body, b"<p>approved</p>");
517        assert!(headers[header::CONTENT_SECURITY_POLICY].to_str().unwrap().contains("connect-src 'none'"));
518        assert_eq!(headers[header::CONTENT_TYPE], "text/html; charset=utf-8");
519        assert_eq!(headers[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*", "an opaque-origin iframe loads it");
520
521        let (s, headers, body) = send(&app, get("/agentmux/widget-sdk/v1.js")).await;
522        assert_eq!(s, StatusCode::OK);
523        assert!(String::from_utf8_lossy(&body).contains("export async function connect"));
524        assert_eq!(headers[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*");
525        let (s, _, body) = send(&app, get("/agentmux/widget-sdk/v1.d.ts")).await;
526        assert_eq!(s, StatusCode::OK);
527        assert!(String::from_utf8_lossy(&body).contains("export declare function connect"), "the types an agent reads");
528        let (s, _, _) = send(&app, get("/agentmux/widget-sdk/../widget-approvals.json")).await;
529        assert_eq!(s, StatusCode::NOT_FOUND);
530
531        let (s, _, _) = send(&app, get(&format!("/agentmux/widget-files/acme.test/{hash}/wrongkey/index.html"))).await;
532        assert_eq!(s, StatusCode::NOT_FOUND, "the key segment is required");
533
534        std::fs::write(pkg.join("index.html"), "<p>edited</p>").unwrap();
535        let (s, _, body) = send(&app, get(&file_uri)).await;
536        assert_eq!(s, StatusCode::CONFLICT, "an edit after approval isn't served");
537        assert!(!String::from_utf8_lossy(&body).contains("edited"));
538    }
539
540    fn write_widget(svc: &packages::WidgetPackages, id: &str, kind: &str) {
541        let pkg = svc.widgets_dir.join(id);
542        std::fs::create_dir_all(&pkg).unwrap();
543        std::fs::write(
544            pkg.join("widget.json"),
545            json!({ "manifestVersion": 1, "id": id, "name": "T", "version": "1.0.0", "kind": kind, "entry": "index.html", "contributes": { "panes": [{ "name": "main" }] } }).to_string(),
546        )
547        .unwrap();
548        std::fs::write(pkg.join("index.html"), "<p>x</p>").unwrap();
549    }
550
551    #[tokio::test]
552    async fn the_list_has_a_package_that_was_put_in_the_widgets_folder() {
553        let svc = packages::WidgetPackages::for_tests();
554        write_widget(svc, "acme.listed", "sandboxed");
555        svc.rescan(&Default::default());
556        let listed = widgets_list().unwrap();
557        assert!(listed.packages.iter().any(|p| p.id == "acme.listed"));
558    }
559
560    #[tokio::test]
561    async fn only_a_trusted_widgets_module_is_read_through_the_loader_route() {
562        let svc = packages::WidgetPackages::for_tests();
563        write_widget(svc, "acme.sandboxed", "sandboxed");
564        svc.rescan(&Default::default());
565        let req = |id: &str| WidgetReadFileReq { id: id.into(), hash: "h".into(), path: "index.html".into() };
566        assert_eq!(widgets_read_file(req("acme.sandboxed")).err().unwrap(), "only a trusted widget's module is read this way");
567        assert_eq!(widgets_read_file(req("acme.nope")).err().unwrap(), "no such widget");
568    }
569
570    #[tokio::test]
571    async fn uninstalling_a_widget_that_is_not_there_says_so() {
572        packages::WidgetPackages::for_tests();
573        let state = crate::server::tests::test_state();
574        let err = widgets_uninstall(&state, WidgetIdReq { id: "acme.never-installed".into() }).await.err().unwrap();
575        assert_eq!(err, "no such widget");
576    }
577
578    #[tokio::test]
579    async fn enabling_a_widget_the_user_never_approved_is_refused() {
580        packages::WidgetPackages::for_tests();
581        let state = crate::server::tests::test_state();
582        let err = widgets_set_enabled(&state, WidgetSetEnabledReq { id: "acme.unapproved".into(), enabled: true }).await.err().unwrap();
583        assert_eq!(err, "that widget isn't approved");
584    }
585
586    #[tokio::test]
587    async fn installing_from_a_folder_that_is_not_there_is_an_error() {
588        packages::WidgetPackages::for_tests();
589        let state = crate::server::tests::test_state();
590        let req = WidgetInstallReq { path: "/nonexistent/agentmux-widget-folder".into(), replace: false };
591        assert!(widgets_install(&state, req).await.is_err());
592    }
593
594    #[tokio::test]
595    async fn a_section_entry_with_a_bad_key_is_refused_before_anything_is_written() {
596        let state = crate::server::tests::test_state();
597        let req = WidgetSectionEntryReq { view: "Warden".into(), section: "lan".into(), label: "LAN".into(), icon: "x".into() };
598        assert!(widgets_section_entry(&state, req).await.is_err());
599    }
600}