Skip to main content

agentmux_srv_core/backend/
cli_uninstall.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Toolchain's Uninstall: remove AgentMux's own copy of one agent CLI,
5//! `<shared>/cli/<provider>/<pin>/`, and nothing else. The person's own copy on
6//! PATH, the CLI's sign-in state and every other pin are never touched
7//! (docs/specs/SPEC_ISOLATED_INSTALL_FOR_NON_NPM_CLIS_2026_11_05.md ยง4).
8//!
9//! Unlike a prune this is the person's own click, so disuse is not asked; the
10//! guards that stay are the ones that protect a running agent: the install lock,
11//! and no open pane that runs the CLI and no running process using the folder.
12//! The pane check does not depend on the process scan, which cannot run on
13//! Windows: a pane records its CLI as a bare name or as a path, so both count.
14
15use agentmux_common::DataPaths;
16
17use super::cli_install::{shared_cli_dir, try_lock_install, COMPLETE_MARKER};
18use super::cli_prune::{dir_size, InUse};
19
20#[derive(Debug, PartialEq, Eq)]
21pub enum Uninstalled {
22    Removed { bytes: u64 },
23    /// There was no folder: nothing to do.
24    NotInstalled,
25}
26
27/// Whether `command` (a pane's program and arguments) runs the CLI called
28/// `cli_name`, by its bare name or by a path to it.
29fn runs_cli(command: &str, cli_name: &str) -> bool {
30    let program = command.split_whitespace().next().unwrap_or("");
31    let file = program.rsplit(['/', '\\']).next().unwrap_or(program).to_ascii_lowercase();
32    let stem = [".exe", ".cmd", ".bat"].iter().find_map(|ext| file.strip_suffix(ext)).unwrap_or(&file);
33    stem == cli_name.to_ascii_lowercase()
34}
35
36/// Remove `<shared>/cli/<provider_id>/<pin>/`. `in_use` is what runs now
37/// ([`super::cli_prune::gather_in_use`]); a folder one of its commands mentions,
38/// or an open pane that runs `cli_name`, leaves it alone and the error says why.
39pub fn uninstall(paths: &DataPaths, provider_id: &str, pin: &str, cli_name: &str, in_use: &InUse) -> Result<Uninstalled, String> {
40    let dir = shared_cli_dir(paths, provider_id, pin).ok_or_else(|| format!("{provider_id}@{pin} is not a safe folder name"))?;
41    match std::fs::symlink_metadata(&dir) {
42        Ok(m) if m.is_dir() && !m.file_type().is_symlink() => {}
43        Ok(_) => return Err(format!("{} is not a plain folder, so it was left alone", dir.display())),
44        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Uninstalled::NotInstalled),
45        Err(e) => return Err(format!("could not look at {}: {e}", dir.display())),
46    }
47    let _lock = match try_lock_install(paths, provider_id, pin) {
48        Ok(Some(guard)) => guard,
49        Ok(None) => return Err(format!("{provider_id} is being installed right now; try again when it ends")),
50        Err(e) => return Err(format!("could not take the install lock for {provider_id}: {e}")),
51    };
52    if in_use.mentions(&dir) || in_use.live_commands.iter().any(|c| runs_cli(c, cli_name)) {
53        return Err(format!("a running agent uses {provider_id}; close it first"));
54    }
55    let bytes = dir_size(&dir);
56    // The marker first: a folder half removed by a crash is already "not an install".
57    let _ = std::fs::remove_file(dir.join(COMPLETE_MARKER));
58    std::fs::remove_dir_all(&dir)
59        .map_err(|e| format!("could not remove all of {}: {e}. A part may be gone; AgentMux installs it again the next time it is needed", dir.display()))?;
60    Ok(Uninstalled::Removed { bytes })
61}
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66    use std::path::Path;
67
68    fn paths_in(root: &Path) -> DataPaths {
69        let version_dir = root.join("channels").join("c").join("versions").join("1.0.0");
70        DataPaths {
71            home_dir: root.to_path_buf(),
72            instance_dir: root.join("channels").join("c"),
73            channel: "c".to_string(),
74            data_dir: version_dir.join("data"),
75            config_dir: root.join("channels").join("c").join("config"),
76            logs_dir: version_dir.join("logs"),
77            cef_cache_dir: version_dir.join("cef-cache"),
78            agents_dir: root.join("channels").join("c").join("agents"),
79            instance_runtime_dir: version_dir.join("runtime"),
80            shared_dir: root.join("shared"),
81            mode: agentmux_common::RuntimeMode::Portable,
82        }
83    }
84
85    fn install(p: &DataPaths, provider: &str, pin: &str) -> std::path::PathBuf {
86        let dir = p.shared_dir.join("cli").join(provider).join(pin);
87        std::fs::create_dir_all(dir.join("bin")).unwrap();
88        std::fs::write(dir.join("bin").join(provider), vec![0u8; 100]).unwrap();
89        std::fs::write(dir.join(COMPLETE_MARKER), pin).unwrap();
90        dir
91    }
92
93    fn idle() -> InUse {
94        InUse { live_commands: vec![], process_commands: Some(vec!["/usr/bin/vim".into()]) }
95    }
96
97    #[test]
98    fn it_removes_that_pin_of_that_provider_and_nothing_else() {
99        let root = tempfile::tempdir().unwrap();
100        let p = paths_in(root.path());
101        let goose = install(&p, "goose", "1.54.0");
102        let other_pin = install(&p, "goose", "1.50.0");
103        let other_provider = install(&p, "grok", "1.0.52");
104        let sign_in = p.shared_dir.join("identities").join("x").join("goose");
105        std::fs::create_dir_all(&sign_in).unwrap();
106
107        assert_eq!(uninstall(&p, "goose", "1.54.0", "goose", &idle()), Ok(Uninstalled::Removed { bytes: 100 + "1.54.0".len() as u64 }));
108        assert!(!goose.exists());
109        assert!(other_pin.exists() && other_provider.exists() && sign_in.exists());
110    }
111
112    #[test]
113    fn a_folder_that_is_not_there_is_nothing_to_do() {
114        let root = tempfile::tempdir().unwrap();
115        assert_eq!(uninstall(&paths_in(root.path()), "goose", "1.54.0", "goose", &idle()), Ok(Uninstalled::NotInstalled));
116    }
117
118    #[test]
119    fn a_running_agent_keeps_its_cli() {
120        let root = tempfile::tempdir().unwrap();
121        let p = paths_in(root.path());
122        let dir = install(&p, "goose", "1.54.0");
123        let cmd = format!("{}{}bin{}goose acp", dir.display(), std::path::MAIN_SEPARATOR, std::path::MAIN_SEPARATOR);
124        let in_use = InUse { live_commands: vec![cmd], process_commands: None };
125
126        let err = uninstall(&p, "goose", "1.54.0", "goose", &in_use).unwrap_err();
127        assert!(err.contains("close it first"), "{err}");
128        assert!(dir.join(COMPLETE_MARKER).exists(), "an install left alone stays complete");
129    }
130
131    #[test]
132    fn an_open_pane_that_runs_the_cli_by_name_keeps_it_even_when_no_process_scan_ran() {
133        let root = tempfile::tempdir().unwrap();
134        let p = paths_in(root.path());
135        let dir = install(&p, "goose", "1.54.0");
136        for pane in ["goose acp", "goose", r"C:\tools\goose.exe acp", "/usr/local/bin/goose term", "GOOSE.CMD run"] {
137            let in_use = InUse { live_commands: vec![pane.into()], process_commands: None };
138            let err = uninstall(&p, "goose", "1.54.0", "goose", &in_use).unwrap_err();
139            assert!(err.contains("close it first"), "{pane}: {err}");
140            assert!(dir.exists(), "{pane}");
141        }
142        // Another CLI whose name only starts the same does not count.
143        let others = InUse { live_commands: vec!["goosed serve".into(), "claude --resume".into(), "".into()], process_commands: None };
144        assert!(matches!(uninstall(&p, "goose", "1.54.0", "goose", &others), Ok(Uninstalled::Removed { .. })));
145    }
146
147    #[test]
148    fn it_waits_for_an_install_in_progress() {
149        let root = tempfile::tempdir().unwrap();
150        let p = paths_in(root.path());
151        let dir = install(&p, "goose", "1.54.0");
152        let _held = try_lock_install(&p, "goose", "1.54.0").unwrap().expect("the lock is free");
153
154        let err = uninstall(&p, "goose", "1.54.0", "goose", &idle()).unwrap_err();
155        assert!(err.contains("being installed"), "{err}");
156        assert!(dir.exists());
157    }
158
159    #[test]
160    fn a_name_that_is_not_a_safe_folder_is_refused() {
161        let root = tempfile::tempdir().unwrap();
162        let p = paths_in(root.path());
163        for (provider, pin) in [("..", "1.0.0"), ("goose", "../x"), ("goose", ""), ("go/ose", "1.0.0")] {
164            assert!(uninstall(&p, provider, pin, "goose", &idle()).is_err(), "{provider}@{pin}");
165        }
166    }
167
168    #[cfg(unix)]
169    #[test]
170    fn a_link_in_place_of_the_folder_is_left_alone() {
171        let root = tempfile::tempdir().unwrap();
172        let p = paths_in(root.path());
173        let real = root.path().join("elsewhere");
174        std::fs::create_dir_all(&real).unwrap();
175        let link = p.shared_dir.join("cli").join("goose").join("1.54.0");
176        std::fs::create_dir_all(link.parent().unwrap()).unwrap();
177        std::os::unix::fs::symlink(&real, &link).unwrap();
178
179        assert!(uninstall(&p, "goose", "1.54.0", "goose", &idle()).unwrap_err().contains("not a plain folder"));
180        assert!(real.exists());
181    }
182}