Skip to main content

agentmux_common/
user_path.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The person's own PATH on Windows (`HKEY_CURRENT_USER\Environment`, value `Path`): what `install.ps1 -Headless` adds
5//! one entry to, and `agentmux uninstall` takes that entry back out of. Only the person's own list is read or written,
6//! never the machine's, and only entries inside the install folder are removed; the rest of the value is kept as it is.
7//! The text work is plain code that is tested on every platform.
8
9use std::path::Path;
10
11/// An entry as it is compared: a `%LOCALAPPDATA%` or `%USERPROFILE%` written in it is replaced by the value in `vars`,
12/// quotes and a closing `\` or `/` are dropped, `/` becomes `\`, and the case does not matter.
13fn normalized(entry: &str, vars: &[(&str, &str)]) -> String {
14    let mut text = entry.trim().trim_matches('"').to_string();
15    for (name, value) in vars {
16        let marker = format!("%{}%", name.to_ascii_lowercase());
17        while let Some(at) = text.to_ascii_lowercase().find(&marker) {
18            text.replace_range(at..at + marker.len(), value);
19        }
20    }
21    text.replace('/', "\\").trim_end_matches('\\').to_ascii_lowercase()
22}
23
24/// `path_value` without the entries that are `base` or inside it, or `None` when none are (so nothing is written). An
25/// empty `base` removes nothing.
26pub fn without_under(path_value: &str, base: &Path, vars: &[(&str, &str)]) -> Option<String> {
27    let base = normalized(&base.to_string_lossy(), &[]);
28    if base.is_empty() {
29        return None;
30    }
31    let inside = |entry: &str| {
32        let entry = normalized(entry, vars);
33        entry == base || entry.strip_prefix(base.as_str()).is_some_and(|rest| rest.starts_with('\\'))
34    };
35    let entries: Vec<&str> = path_value.split(';').collect();
36    let kept: Vec<&str> = entries.iter().copied().filter(|e| !inside(e)).collect();
37    (kept.len() != entries.len()).then(|| kept.join(";"))
38}
39
40/// Take every entry inside `base` out of the person's own PATH. `Ok(true)` when the value was changed. The value keeps
41/// its type (an expandable one stays expandable). New programs started from a window that is already open do not see
42/// the change until they are started again; nothing is broadcast.
43#[cfg(windows)]
44pub fn remove_under_from_user_path(base: &Path) -> Result<bool, String> {
45    use windows_sys::Win32::Foundation::ERROR_SUCCESS;
46    use windows_sys::Win32::System::Registry::{RegCloseKey, RegOpenKeyExW, RegQueryValueExW, RegSetValueExW, HKEY, HKEY_CURRENT_USER, KEY_QUERY_VALUE, KEY_SET_VALUE};
47
48    let subkey: Vec<u16> = "Environment\0".encode_utf16().collect();
49    let name: Vec<u16> = "Path\0".encode_utf16().collect();
50    // SAFETY: NUL-terminated names that outlive the calls, a buffer as long as the call asked for, and the key closed on
51    // every path.
52    unsafe {
53        let mut key: HKEY = std::ptr::null_mut();
54        if RegOpenKeyExW(HKEY_CURRENT_USER, subkey.as_ptr(), 0, KEY_QUERY_VALUE | KEY_SET_VALUE, &mut key) as u32 != ERROR_SUCCESS {
55            return Err("cannot open your user environment to read PATH".to_string());
56        }
57        let result = (|| {
58            let (mut kind, mut bytes) = (0u32, 0u32);
59            let first = RegQueryValueExW(key, name.as_ptr(), std::ptr::null(), &mut kind, std::ptr::null_mut(), &mut bytes);
60            if first as u32 != ERROR_SUCCESS || bytes == 0 {
61                return Ok(false);
62            }
63            let mut buf: Vec<u16> = vec![0u16; (bytes as usize).div_ceil(2)];
64            let second = RegQueryValueExW(key, name.as_ptr(), std::ptr::null(), &mut kind, buf.as_mut_ptr().cast(), &mut bytes);
65            if second as u32 != ERROR_SUCCESS {
66                return Err("cannot read your user PATH".to_string());
67            }
68            let len = (bytes as usize / 2).min(buf.len());
69            let text = String::from_utf16_lossy(&buf[..len]);
70            let text = text.trim_end_matches('\0');
71            let local = std::env::var("LOCALAPPDATA").unwrap_or_default();
72            let profile = std::env::var("USERPROFILE").unwrap_or_default();
73            let Some(new) = without_under(text, base, &[("localappdata", local.as_str()), ("userprofile", profile.as_str())]) else { return Ok(false) };
74            let wide: Vec<u16> = new.encode_utf16().chain(std::iter::once(0)).collect();
75            let set = RegSetValueExW(key, name.as_ptr(), 0, kind, wide.as_ptr().cast(), (wide.len() * 2) as u32);
76            if set as u32 != ERROR_SUCCESS {
77                return Err("cannot write your user PATH".to_string());
78            }
79            Ok(true)
80        })();
81        RegCloseKey(key);
82        result
83    }
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89
90    const BASE: &str = r"C:\Users\sam\AppData\Local\AgentMux\Headless";
91
92    #[test]
93    fn only_the_entries_inside_the_install_folder_are_taken_out() {
94        let vars = [("localappdata", r"C:\Users\sam\AppData\Local"), ("userprofile", r"C:\Users\sam")];
95        let value = r"C:\Windows;C:\Users\sam\AppData\Local\AgentMux\Headless\current\bin;%LOCALAPPDATA%\AgentMux\Headless\0.60.30\bin;C:\tools";
96        assert_eq!(without_under(value, Path::new(BASE), &vars).as_deref(), Some(r"C:\Windows;C:\tools"));
97        // Case, quotes, `/` and a closing `\` do not matter.
98        assert_eq!(without_under(r#"C:\a;"c:/users/SAM/appdata/local/agentmux/headless/current/bin\";C:\b"#, Path::new(BASE), &vars).as_deref(), Some(r"C:\a;C:\b"));
99    }
100
101    #[test]
102    fn a_folder_that_only_starts_with_the_same_letters_is_not_inside() {
103        let vars = [];
104        let value = r"C:\Users\sam\AppData\Local\AgentMux\HeadlessTools\bin;C:\Users\sam\AppData\Local\AgentMux";
105        assert_eq!(without_under(value, Path::new(BASE), &vars), None);
106    }
107
108    #[test]
109    fn nothing_is_written_when_nothing_is_ours_and_an_empty_base_takes_nothing() {
110        assert_eq!(without_under(r"C:\Windows;C:\tools", Path::new(BASE), &[]), None);
111        assert_eq!(without_under(r"C:\Windows;;C:\tools", Path::new(""), &[]), None);
112        assert_eq!(without_under("", Path::new(BASE), &[]), None);
113        // The entries that stay keep their order and their own text, empty ones too.
114        assert_eq!(without_under(r"C:\a;;%X%\b;C:\Users\sam\AppData\Local\AgentMux\Headless\current\bin", Path::new(BASE), &[]).as_deref(), Some(r"C:\a;;%X%\b"));
115    }
116}