Skip to main content

agentmux_srv/server/
uninstall_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `install.uninstall`: Toolchain's Uninstall for an agent CLI AgentMux installed.
5//! It removes AgentMux's own copy of the registry's pin and nothing else
6//! (`backend::cli_uninstall`; SPEC_ISOLATED_INSTALL_FOR_NON_NPM_CLIS_2026_11_05.md ยง4).
7
8use std::sync::Arc;
9
10use serde::{Deserialize, Serialize};
11
12use crate::backend::cli_uninstall::{uninstall, Uninstalled};
13use crate::backend::rpc::engine::WshRpcEngine;
14use crate::server::install_handlers::installable_provider;
15use crate::server::AppState;
16
17pub const COMMAND_INSTALL_UNINSTALL: &str = "install.uninstall";
18
19#[derive(Debug, Deserialize, Serialize, ts_rs::TS)]
20#[ts(export, export_to = "../../../frontend/types/rpc/")]
21#[serde(rename_all = "camelCase")]
22pub struct UninstallReq {
23    /// The agent CLI whose AgentMux copy goes. The folder comes from srv's own registry, never the caller.
24    pub provider_id: String,
25}
26
27#[derive(Debug, Deserialize, Serialize, ts_rs::TS)]
28#[ts(export, export_to = "../../../frontend/types/rpc/")]
29#[serde(rename_all = "camelCase")]
30pub struct UninstallResult {
31    /// A folder was removed (false: there was none).
32    pub removed: bool,
33    #[ts(type = "number")]
34    pub bytes: u64,
35}
36
37/// The command of every block that records one: the open panes and the ones
38/// restored from a layout, which keep the absolute CLI path until they mount.
39pub(crate) fn live_block_commands(mstore: &crate::backend::storage::store::Store) -> Result<Vec<String>, String> {
40    let blocks = mstore.get_all::<crate::backend::obj::Block>().map_err(|e| e.to_string())?;
41    Ok(blocks
42        .iter()
43        .filter_map(|b| {
44            let mut parts: Vec<String> = Vec::new();
45            if let Some(c) = b.meta.get("cmd").and_then(|v| v.as_str()) {
46                parts.push(c.to_string());
47            }
48            if let Some(a) = b.meta.get("cmd:args").and_then(|v| v.as_array()) {
49                parts.extend(a.iter().filter_map(|v| v.as_str().map(str::to_string)));
50            }
51            (!parts.is_empty()).then(|| parts.join(" "))
52        })
53        .collect())
54}
55
56pub fn register_uninstall_handlers(engine: &Arc<WshRpcEngine>, state: &AppState) {
57    let mstore = state.mstore.clone();
58    engine.register_typed(COMMAND_INSTALL_UNINSTALL, move |req: UninstallReq, _ctx| {
59        let mstore = mstore.clone();
60        async move {
61            let live = live_block_commands(&mstore).map_err(|e| format!("install.uninstall: {e}"))?;
62            install_uninstall(live, req).await
63        }
64    });
65}
66
67pub(crate) async fn install_uninstall(live_commands: Vec<String>, req: UninstallReq) -> Result<UninstallResult, String> {
68    let provider = installable_provider(&req.provider_id)?;
69    if provider.pinned_version.is_empty() {
70        return Err(format!("{} has no pinned version, so AgentMux has no copy to remove", provider.id));
71    }
72    let paths = agentmux_common::DataPaths::from_env().ok_or_else(|| "DataPaths::from_env() failed".to_string())?;
73    let (id, pin, cli) = (provider.id, provider.pinned_version, provider.cli_command);
74    let outcome = tokio::task::spawn_blocking(move || {
75        let in_use = crate::backend::cli_prune::gather_in_use(&live_commands);
76        uninstall(&paths, id, pin, cli, &in_use)
77    })
78    .await
79    .map_err(|e| format!("install.uninstall: {e}"))??;
80    tracing::info!(provider = %id, ?outcome, "install.uninstall");
81    Ok(match outcome {
82        Uninstalled::Removed { bytes } => UninstallResult { removed: true, bytes },
83        Uninstalled::NotInstalled => UninstallResult { removed: false, bytes: 0 },
84    })
85}
86
87#[cfg(test)]
88mod tests {
89    use super::*;
90
91    #[tokio::test]
92    async fn only_a_provider_agentmux_installs_can_be_uninstalled() {
93        for id in ["no-such-provider", "../claude", ""] {
94            let err = install_uninstall(vec![], UninstallReq { provider_id: id.into() }).await.unwrap_err();
95            assert!(!err.is_empty(), "{id:?}");
96        }
97    }
98
99    #[test]
100    fn the_request_names_only_the_provider() {
101        let req: UninstallReq = serde_json::from_value(serde_json::json!({"providerId": "goose"})).unwrap();
102        assert_eq!(req.provider_id, "goose");
103        assert!(serde_json::from_value::<UninstallReq>(serde_json::json!({"provider_id": "goose"})).is_err());
104        let res = serde_json::to_value(UninstallResult { removed: true, bytes: 3 }).unwrap();
105        assert_eq!(res, serde_json::json!({"removed": true, "bytes": 3}));
106    }
107}