Skip to main content

agentmux_srv_core/backend/
app_version.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The version of an application on this computer, found from the executable names a computer-use skill lists
5//! (docs/specs/SPEC_PACKS_2026_11_05.md ยง8: "a lookup per row, no inventory scan"). "Not found" is a normal answer.
6//!
7//! - **Windows:** the App Paths registry key, then `PATH`, then the folders directly under Program Files and
8//!   `%LOCALAPPDATA%\Programs` (one level further down); the version is the executable's file version.
9//! - **macOS:** the `.app` bundles directly in `/Applications` and `~/Applications` that hold `Contents/MacOS/<name>`;
10//!   the version is the bundle's `CFBundleShortVersionString`.
11//! - **Linux:** `PATH` only. The app is found, its version is not read.
12
13use std::path::PathBuf;
14#[cfg(any(windows, target_os = "macos"))]
15use std::path::Path;
16
17/// An application found here.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Found {
20    /// What the executable or bundle says it is; `None` when it says nothing readable.
21    pub version: Option<String>,
22}
23
24/// The first of `executables` that is installed here, with its version.
25pub fn find(executables: &[String]) -> Option<Found> {
26    executables.iter().filter(|e| !e.trim().is_empty()).find_map(|name| locate(name.trim()))
27}
28
29/// `a.b.c.d` from a Windows file version, without trailing zero parts beyond the first two (`16.0.0.0` is `16.0`).
30#[cfg(any(windows, test))]
31fn dotted(parts: [u16; 4]) -> String {
32    let keep = parts.iter().rposition(|p| *p != 0).map_or(2, |i| (i + 1).max(2));
33    parts[..keep].iter().map(u16::to_string).collect::<Vec<_>>().join(".")
34}
35
36/// The value of `key` in an XML property list (the text of the `<string>` that follows `<key>key</key>`).
37#[cfg(any(target_os = "macos", test))]
38fn plist_string(xml: &str, key: &str) -> Option<String> {
39    let after = &xml[xml.find(&format!("<key>{key}</key>"))? + key.len() + 11..];
40    let rest = after.trim_start().strip_prefix("<string>")?;
41    let value = rest[..rest.find("</string>")?].trim();
42    (!value.is_empty() && value.len() <= 64).then(|| value.to_string())
43}
44
45/// `name` in the folders of `path_var`, as a file.
46#[cfg_attr(target_os = "macos", allow(dead_code))]
47fn on_path(name: &str, path_var: &std::ffi::OsStr) -> Option<PathBuf> {
48    std::env::split_paths(path_var).map(|d| d.join(name)).find(|p| p.is_file())
49}
50
51#[cfg(windows)]
52fn locate(name: &str) -> Option<Found> {
53    let name = if name.contains('.') { name.to_string() } else { format!("{name}.exe") };
54    let path = app_paths(&name)
55        .or_else(|| std::env::var_os("PATH").and_then(|p| on_path(&name, &p)))
56        .or_else(|| in_install_folders(&name))?;
57    Some(Found { version: file_version(&path) })
58}
59
60/// The path Windows registers for the program, if it registered one.
61#[cfg(windows)]
62fn app_paths(name: &str) -> Option<PathBuf> {
63    use windows::Win32::System::Registry::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE};
64    let key = format!(r"Software\Microsoft\Windows\CurrentVersion\App Paths\{name}");
65    [HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE]
66        .into_iter()
67        .filter_map(|root| crate::backend::file_icons::registry_string(root, &key, ""))
68        .map(|v| PathBuf::from(v.trim().trim_matches('"')))
69        .find(|p| p.is_file())
70}
71
72/// `<root>/<app>/<name>` and `<root>/<vendor>/<app>/<name>` for the usual install roots.
73#[cfg(windows)]
74fn in_install_folders(name: &str) -> Option<PathBuf> {
75    let roots: Vec<PathBuf> = ["ProgramFiles", "ProgramFiles(x86)"]
76        .iter()
77        .filter_map(|v| std::env::var_os(v).map(PathBuf::from))
78        .chain(std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join("Programs")))
79        .collect();
80    roots.iter().find_map(|root| {
81        let dirs = subfolders(root);
82        dirs.iter()
83            .map(|d| d.join(name))
84            .find(|p| p.is_file())
85            .or_else(|| dirs.iter().flat_map(|d| subfolders(d)).map(|d| d.join(name)).find(|p| p.is_file()))
86    })
87}
88
89#[cfg(windows)]
90fn subfolders(dir: &Path) -> Vec<PathBuf> {
91    std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect()
92}
93
94/// The executable's file version (the fixed part of its version resource).
95#[cfg(windows)]
96fn file_version(path: &Path) -> Option<String> {
97    use std::os::windows::ffi::OsStrExt;
98    use windows::core::{w, PCWSTR};
99    use windows::Win32::Storage::FileSystem::{GetFileVersionInfoSizeW, GetFileVersionInfoW, VerQueryValueW, VS_FIXEDFILEINFO};
100    let wide: Vec<u16> = path.as_os_str().encode_wide().chain(std::iter::once(0)).collect();
101    // SAFETY: `wide` is NUL-terminated and outlives the calls; the buffer is the size Windows asked for; the pointer
102    // VerQueryValueW returns points into that buffer and is read before the buffer is dropped, as an unaligned read.
103    unsafe {
104        let size = GetFileVersionInfoSizeW(PCWSTR(wide.as_ptr()), None);
105        if size == 0 {
106            return None;
107        }
108        let mut buf = vec![0u8; size as usize];
109        GetFileVersionInfoW(PCWSTR(wide.as_ptr()), None, size, buf.as_mut_ptr().cast()).ok()?;
110        let mut at: *mut std::ffi::c_void = std::ptr::null_mut();
111        let mut len = 0u32;
112        if !VerQueryValueW(buf.as_ptr().cast(), w!("\\"), &mut at, &mut len).as_bool() || (len as usize) < std::mem::size_of::<VS_FIXEDFILEINFO>() {
113            return None;
114        }
115        let info = std::ptr::read_unaligned(at as *const VS_FIXEDFILEINFO);
116        let ms = info.dwFileVersionMS;
117        let ls = info.dwFileVersionLS;
118        let parts = [(ms >> 16) as u16, ms as u16, (ls >> 16) as u16, ls as u16];
119        (parts != [0; 4]).then(|| dotted(parts))
120    }
121}
122
123#[cfg(target_os = "macos")]
124fn locate(name: &str) -> Option<Found> {
125    let homes = std::env::var_os("HOME").map(|h| PathBuf::from(h).join("Applications"));
126    let bundle = [PathBuf::from("/Applications")]
127        .into_iter()
128        .chain(homes)
129        .flat_map(|root: PathBuf| std::fs::read_dir(root).into_iter().flatten().flatten().map(|e| e.path()))
130        .filter(|p| p.extension().is_some_and(|x| x == "app"))
131        .find(|p| p.join("Contents/MacOS").join(name).is_file())?;
132    Some(Found { version: bundle_version(&bundle) })
133}
134
135/// A bundle's version from its `Info.plist`: read as XML, or through `plutil` when it is the binary form.
136#[cfg(target_os = "macos")]
137fn bundle_version(bundle: &Path) -> Option<String> {
138    let plist = bundle.join("Contents/Info.plist");
139    let raw = std::fs::read(&plist).ok()?;
140    if let Ok(xml) = std::str::from_utf8(&raw) {
141        if xml.trim_start().starts_with("<?xml") {
142            return plist_string(xml, "CFBundleShortVersionString").or_else(|| plist_string(xml, "CFBundleVersion"));
143        }
144    }
145    let mut cmd = std::process::Command::new("/usr/bin/plutil");
146    crate::backend::pane_env::sanitize_external_std_command(&mut cmd);
147    let out = cmd.args(["-extract", "CFBundleShortVersionString", "raw", "-o", "-"]).arg(&plist).output().ok()?;
148    let v = String::from_utf8(out.stdout).ok()?.trim().to_string();
149    (out.status.success() && !v.is_empty() && v.len() <= 64).then_some(v)
150}
151
152#[cfg(not(any(windows, target_os = "macos")))]
153fn locate(name: &str) -> Option<Found> {
154    std::env::var_os("PATH").and_then(|p| on_path(name, &p)).map(|_| Found { version: None })
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn a_windows_file_version_drops_trailing_zero_parts_but_keeps_two() {
163        assert_eq!(dotted([16, 0, 18227, 20162]), "16.0.18227.20162");
164        assert_eq!(dotted([12, 2, 0, 0]), "12.2");
165        assert_eq!(dotted([21, 0, 1, 0]), "21.0.1");
166        assert_eq!(dotted([16, 0, 0, 0]), "16.0");
167        assert_eq!(dotted([7, 0, 0, 0]), "7.0");
168    }
169
170    #[test]
171    fn a_plist_string_is_read_by_its_key_and_only_when_it_is_a_string() {
172        let xml = "<?xml version=\"1.0\"?><plist><dict>\n<key>CFBundleName</key>\n<string>Live</string>\n\
173                   <key>CFBundleShortVersionString</key>\n\t<string>12.2.1</string>\n<key>CFBundleVersion</key><integer>5</integer></dict></plist>";
174        assert_eq!(plist_string(xml, "CFBundleShortVersionString").as_deref(), Some("12.2.1"));
175        assert_eq!(plist_string(xml, "CFBundleName").as_deref(), Some("Live"));
176        assert_eq!(plist_string(xml, "CFBundleVersion"), None, "an integer is not a string");
177        assert_eq!(plist_string(xml, "Missing"), None);
178        assert_eq!(plist_string("<key>K</key><string> </string>", "K"), None, "blank is nothing");
179    }
180
181    #[test]
182    fn a_name_is_looked_for_in_each_folder_of_the_path_and_must_be_a_file() {
183        let a = tempfile::tempdir().unwrap();
184        let b = tempfile::tempdir().unwrap();
185        std::fs::write(b.path().join("tool"), b"x").unwrap();
186        std::fs::create_dir(a.path().join("dir-not-file")).unwrap();
187        let path = std::env::join_paths([a.path(), b.path()]).unwrap();
188        assert_eq!(on_path("tool", &path), Some(b.path().join("tool")));
189        assert_eq!(on_path("dir-not-file", &path), None);
190        assert_eq!(on_path("absent", &path), None);
191    }
192
193    #[test]
194    fn blank_names_find_nothing_and_an_app_that_is_not_here_is_not_found() {
195        assert_eq!(find(&[]), None);
196        assert_eq!(find(&["  ".to_string()]), None);
197        assert_eq!(find(&["agentmux-no-such-app-zz.exe".to_string(), "AgentMuxNoSuchAppZz".to_string()]), None);
198    }
199
200    /// notepad.exe is in System32, which is on PATH, and has a file version.
201    #[cfg(windows)]
202    #[test]
203    fn a_windows_program_on_the_path_is_found_with_its_file_version() {
204        let found = find(&["notepad.exe".to_string()]).expect("notepad is installed");
205        let v = found.version.expect("notepad has a version resource");
206        assert!(v.split('.').count() >= 2 && v.split('.').all(|p| p.parse::<u16>().is_ok()), "{v}");
207        assert_eq!(find(&["Nope.exe".to_string(), "notepad".to_string()]).map(|f| f.version.is_some()), Some(true), "the name may omit .exe, and the first found wins");
208    }
209
210    /// `sh` is on PATH on any Unix; the app is found and no version is read.
211    #[cfg(target_os = "linux")]
212    #[test]
213    fn a_linux_program_on_the_path_is_found_without_a_version() {
214        assert_eq!(find(&["sh".to_string()]), Some(Found { version: None }));
215    }
216}