1use std::path::{Path, PathBuf};
24
25const PORTABLE_MARKER: &str = "agentmux-portable.marker";
26
27pub const PACKAGE_HELPER: &str = "/opt/agentmux/bin/agentmux-install-update";
30
31const DPKG_FILE_LIST: &str = "/var/lib/dpkg/info/agentmux.list";
33
34#[derive(Debug, Clone, PartialEq, Eq)]
36pub enum InstallKind {
37 WindowsPortable { root: PathBuf },
39 WindowsSetup,
40 WindowsStore,
41 MacApp { app: PathBuf, blocked: Option<String> },
44 LinuxAppImage,
45 LinuxPortable { root: PathBuf },
48 LinuxPackage { debian: bool },
50 Unknown,
51}
52
53impl InstallKind {
54 pub fn label(&self) -> &'static str {
56 match self {
57 Self::WindowsPortable { .. } => "windows-portable",
58 Self::WindowsSetup => "windows-setup",
59 Self::WindowsStore => "windows-store",
60 Self::MacApp { .. } => "macos-app",
61 Self::LinuxAppImage => "linux-appimage",
62 Self::LinuxPortable { .. } => "linux-portable",
63 Self::LinuxPackage { .. } => "linux-package",
64 Self::Unknown => "unknown",
65 }
66 }
67
68 pub fn can_download(&self) -> bool {
71 self.can_download_with(Path::new(PACKAGE_HELPER).is_file())
72 }
73
74 pub fn can_download_with(&self, package_helper: bool) -> bool {
78 match self {
79 Self::MacApp { blocked, .. } => blocked.is_none(),
80 Self::LinuxPackage { .. } => package_helper,
81 _ => matches!(
82 self,
83 Self::WindowsPortable { .. } | Self::WindowsSetup | Self::LinuxPortable { .. } | Self::LinuxAppImage
84 ),
85 }
86 }
87
88 pub fn blocked_reason(&self) -> Option<&str> {
91 match self {
92 Self::MacApp { blocked, .. } => blocked.as_deref(),
93 _ => None,
94 }
95 }
96
97 pub fn asset_name(&self, version: &str, arch: &str) -> Option<String> {
100 let x64 = arch == "x86_64";
101 match self {
102 Self::WindowsPortable { .. } if x64 => Some(format!("agentmux-{version}-x64-portable.7z")),
103 Self::WindowsSetup if x64 => Some(format!("AgentMux-{version}-x64-setup.exe")),
104 Self::MacApp { .. } if arch == "aarch64" => Some(format!("AgentMux_{version}_arm64.dmg")),
105 Self::LinuxAppImage if x64 => Some(format!("AgentMux_{version}_amd64.AppImage")),
106 Self::LinuxPortable { .. } if x64 => Some(format!("AgentMux_{version}_amd64-portable.tar.xz")),
107 Self::LinuxPackage { debian: true } if x64 => Some(format!("AgentMux_{version}_amd64.deb")),
108 Self::LinuxPackage { debian: false } if x64 => Some(format!("AgentMux-{version}-1.x86_64.rpm")),
109 _ => None,
110 }
111 }
112}
113
114pub fn has_uninstaller(dir: &Path) -> bool {
117 std::fs::read_dir(dir).is_ok_and(|entries| {
118 entries.filter_map(|e| e.ok()).any(|e| {
119 let name = e.file_name().to_string_lossy().to_ascii_lowercase();
120 name.starts_with("unins") && name.ends_with(".exe")
121 })
122 })
123}
124
125fn detect_at(exe: &Path, os: &str, appimage: bool, debian: bool) -> InstallKind {
127 let dir = exe.parent();
128 let portable_root = dir
129 .filter(|d| d.join(PORTABLE_MARKER).is_file())
130 .and_then(|d| d.parent())
131 .map(Path::to_path_buf);
132 let text = exe.to_string_lossy().replace('\\', "/");
133 match os {
134 "windows" => {
135 if text.to_ascii_lowercase().contains("/windowsapps/") {
136 InstallKind::WindowsStore
137 } else if let Some(root) =
138 portable_root.filter(|r| r.join("agentmux.exe").is_file() && !has_uninstaller(r))
139 {
140 InstallKind::WindowsPortable { root }
141 } else if dir.and_then(Path::parent).is_some_and(|app| has_uninstaller(app) && app.join("agentmux.exe").is_file()) {
142 InstallKind::WindowsSetup
144 } else {
145 InstallKind::Unknown
146 }
147 }
148 "macos" if text.contains(".app/Contents/") => mac_app(exe),
149 "linux" if dir.is_some_and(|d| d.ends_with("usr/bin")) && linux_portable_root(exe).is_some() => {
151 InstallKind::LinuxPortable { root: linux_portable_root(exe).unwrap_or_default() }
152 }
153 "linux" if appimage => InstallKind::LinuxAppImage,
154 "linux" => match portable_root {
155 Some(root) => InstallKind::LinuxPortable { root },
156 None if text.starts_with("/usr/") || text.starts_with("/opt/") => InstallKind::LinuxPackage { debian },
157 None => InstallKind::Unknown,
158 },
159 _ => InstallKind::Unknown,
160 }
161}
162
163pub fn outermost_app(exe: &Path) -> Option<PathBuf> {
167 agentmux_common::runtime_mode::app_bundle_of(exe)
168}
169
170fn replace_blocker(app: &Path, read_only: bool, parent_writable: bool) -> Option<String> {
174 if read_only {
175 return Some(format!("{} is on a read-only volume (run from the .dmg?); drag it to Applications first", app.display()));
176 }
177 if app.to_string_lossy().contains("/AppTranslocation/") {
180 return Some(format!("{} is App-Translocated; move it to Applications and open it from there", app.display()));
181 }
182 if !parent_writable {
183 return Some(format!("the folder holding {} isn't writable by this user", app.display()));
184 }
185 None
186}
187
188#[cfg(target_os = "macos")]
191fn on_read_only_volume(path: &Path) -> bool {
192 use std::os::unix::ffi::OsStrExt;
193 let Ok(c) = std::ffi::CString::new(path.as_os_str().as_bytes()) else { return true };
194 let mut st: libc::statfs = unsafe { std::mem::zeroed() };
195 if unsafe { libc::statfs(c.as_ptr(), &mut st) } != 0 {
197 return true;
198 }
199 (st.f_flags as u64) & (libc::MNT_RDONLY as u64) != 0
200}
201
202#[cfg(not(target_os = "macos"))]
203fn on_read_only_volume(_: &Path) -> bool {
204 false
205}
206
207#[cfg(unix)]
209fn writable_dir(dir: &Path) -> bool {
210 use std::os::unix::ffi::OsStrExt;
211 std::ffi::CString::new(dir.as_os_str().as_bytes())
212 .is_ok_and(|c| unsafe { libc::access(c.as_ptr(), libc::W_OK | libc::X_OK) } == 0)
214}
215
216#[cfg(not(unix))]
217fn writable_dir(_: &Path) -> bool {
218 true
219}
220
221fn mac_app(exe: &Path) -> InstallKind {
223 let app = outermost_app(exe).unwrap_or_else(|| exe.to_path_buf());
224 let parent = app.parent().unwrap_or(&app);
225 let blocked = replace_blocker(&app, on_read_only_volume(&app), writable_dir(parent)).or_else(|| {
228 agentmux_common::runtime_mode::folder_others_can_change(parent).map(|who| format!("{who}; drag AgentMux to Applications first"))
229 });
230 if let Some(reason) = &blocked {
231 tracing::info!(app = %app.display(), "update: this AgentMux can't upgrade itself in place: {reason}");
232 }
233 InstallKind::MacApp { app, blocked }
234}
235
236pub fn linux_portable_root(exe: &Path) -> Option<PathBuf> {
239 let root = exe.parent()?.parent()?.parent()?;
240 root.join("agentmux.sh").is_file().then(|| root.to_path_buf())
241}
242
243fn owned_by_dpkg(exe: &Path, file_list: &Path) -> bool {
248 std::fs::read_to_string(file_list).is_ok_and(|list| list.lines().any(|l| Path::new(l) == exe))
249}
250
251pub fn detect() -> InstallKind {
253 let Ok(exe) = std::env::current_exe() else { return InstallKind::Unknown };
254 detect_at(
255 &exe,
256 std::env::consts::OS,
257 agentmux_common::runtime_mode::running_appimage(&exe).is_some(),
258 owned_by_dpkg(&exe, Path::new(DPKG_FILE_LIST)),
259 )
260}
261
262#[cfg(test)]
263mod tests {
264 use super::*;
265
266 fn portable(root: &Path) -> PathBuf {
267 let runtime = root.join("runtime");
268 std::fs::create_dir_all(&runtime).unwrap();
269 std::fs::write(runtime.join(PORTABLE_MARKER), b"").unwrap();
270 std::fs::write(root.join("agentmux.exe"), b"").unwrap();
271 runtime.join("agentmux-srv-0.59.26-windows.x64.exe")
272 }
273
274 #[test]
275 fn windows_installs_are_told_apart() {
276 let dir = tempfile::tempdir().unwrap();
277 let root = dir.path().join("agentmux-0.59.26-x64-portable");
278 let exe = portable(&root);
279 assert_eq!(detect_at(&exe, "windows", false, false), InstallKind::WindowsPortable { root });
280 let store = Path::new(r"C:\Program Files\WindowsApps\AgentMux.AgentMux_0.59.26.0_x64__vqr1k32tkfk4y\runtime\srv.exe");
281 assert_eq!(detect_at(store, "windows", false, false), InstallKind::WindowsStore);
282 let other = Path::new(r"C:\Users\u\AppData\Local\Programs\AgentMux\runtime\srv.exe");
285 assert_eq!(detect_at(other, "windows", false, false), InstallKind::Unknown);
286 let installed = dir.path().join("Programs/AgentMux");
289 let exe = portable(&installed);
290 std::fs::write(installed.join("unins000.exe"), b"").unwrap();
291 assert_eq!(detect_at(&exe, "windows", false, false), InstallKind::WindowsSetup);
292 }
293
294 #[test]
295 fn mac_and_linux_installs_are_told_apart() {
296 let app = Path::new("/Applications/AgentMux.app/Contents/Helpers/AgentMux Server.app/Contents/MacOS/srv");
297 assert!(matches!(detect_at(app, "macos", false, false), InstallKind::MacApp { app, .. } if app == Path::new("/Applications/AgentMux.app")));
298 let bin = Path::new("/tmp/.mount_AgentM/usr/bin/agentmux-srv");
299 assert_eq!(detect_at(bin, "linux", true, true), InstallKind::LinuxAppImage);
300 let deb = Path::new("/opt/AgentMux/agentmux-srv");
301 assert_eq!(detect_at(deb, "linux", false, true), InstallKind::LinuxPackage { debian: true });
302 let dir = tempfile::tempdir().unwrap();
303 let exe = portable(dir.path());
304 assert_eq!(detect_at(&exe, "linux", false, false), InstallKind::LinuxPortable { root: dir.path().to_path_buf() });
305 let tarball = tempfile::tempdir().unwrap();
308 let root = tarball.path().join("AgentMux");
309 std::fs::create_dir_all(root.join("usr/bin")).unwrap();
310 std::fs::write(root.join("agentmux.sh"), b"").unwrap();
311 let srv = root.join("usr/bin/agentmux-srv-0.59.30-linux.x64");
312 for appimage in [false, true] {
313 assert_eq!(detect_at(&srv, "linux", appimage, true), InstallKind::LinuxPortable { root: root.clone() });
314 }
315 assert!(InstallKind::LinuxPortable { root }.can_download() && InstallKind::LinuxAppImage.can_download());
316 }
317
318 #[test]
319 fn a_package_downloads_only_with_the_install_helper() {
320 let deb = InstallKind::LinuxPackage { debian: true };
321 assert!(deb.can_download_with(true));
322 assert!(!deb.can_download_with(false), "a package from before the helper shipped keeps the release page");
323 assert!(InstallKind::LinuxPackage { debian: false }.can_download_with(true));
324 assert!(InstallKind::LinuxAppImage.can_download_with(false), "the other kinds don't look for it");
325 }
326
327 #[test]
328 fn dpkg_owns_what_its_file_list_names() {
329 let dir = tempfile::tempdir().unwrap();
330 let list = dir.path().join("agentmux.list");
331 std::fs::write(&list, "/.\n/opt\n/opt/agentmux/bin/agentmux-srv-0.60.1-linux.x64\n/usr/bin/agentmux\n").unwrap();
332 assert!(owned_by_dpkg(Path::new("/opt/agentmux/bin/agentmux-srv-0.60.1-linux.x64"), &list));
333 assert!(!owned_by_dpkg(Path::new("/opt/agentmux/bin/agentmux-srv-0.60.0-linux.x64"), &list));
335 assert!(!owned_by_dpkg(Path::new("/opt/agentmux/bin/agentmux-srv-0.60.1-linux.x64"), &dir.path().join("missing")));
336 }
337
338 #[test]
339 fn each_kind_names_the_release_file_ci_publishes() {
340 let p = InstallKind::WindowsPortable { root: PathBuf::new() };
341 assert_eq!(p.asset_name("0.59.27", "x86_64").as_deref(), Some("agentmux-0.59.27-x64-portable.7z"));
342 assert_eq!(p.asset_name("0.59.27", "aarch64"), None);
343 assert_eq!(InstallKind::MacApp { app: PathBuf::new(), blocked: None }.asset_name("0.59.27", "aarch64").as_deref(), Some("AgentMux_0.59.27_arm64.dmg"));
344 assert_eq!(InstallKind::WindowsStore.asset_name("0.59.27", "x86_64"), None);
345 assert_eq!(
346 InstallKind::LinuxPackage { debian: false }.asset_name("0.59.27", "x86_64").as_deref(),
347 Some("AgentMux-0.59.27-1.x86_64.rpm")
348 );
349 assert!(p.can_download());
350 assert!(InstallKind::WindowsSetup.can_download());
351 assert!(!InstallKind::WindowsStore.can_download());
352 }
353
354 const NESTED: &str = "AgentMux.app/Contents/Helpers/AgentMux Server.app/Contents/MacOS/srv";
355
356 #[test]
357 fn the_outermost_app_is_the_one_replaced() {
358 let exe = Path::new("/Applications").join(NESTED);
359 assert_eq!(outermost_app(&exe), Some(PathBuf::from("/Applications/AgentMux.app")));
360 let dmg = Path::new("/Volumes/AgentMux 3").join(NESTED);
362 assert_eq!(outermost_app(&dmg), Some(PathBuf::from("/Volumes/AgentMux 3/AgentMux.app")));
363 let nested_in_app = Path::new("/Users/u/Foo.app/Resources").join(NESTED);
364 assert_eq!(outermost_app(&nested_in_app), Some(PathBuf::from("/Users/u/Foo.app/Resources/AgentMux.app")));
366 assert_eq!(outermost_app(Path::new("/usr/local/bin/srv")), None);
367 assert_eq!(outermost_app(Path::new("/x/my.application/srv")), None);
369 }
370
371 #[test]
372 fn an_app_is_replaced_in_place_only_where_that_can_work() {
373 let app = Path::new("/Applications/AgentMux.app");
374 assert_eq!(replace_blocker(app, false, true), None);
375 let dmg = replace_blocker(Path::new("/Volumes/AgentMux 3/AgentMux.app"), true, true).unwrap();
377 assert!(dmg.contains("read-only volume"), "{dmg}");
378 let translocated = Path::new("/private/var/folders/ab/xyz/T/AppTranslocation/1234-5678/d/AgentMux.app");
379 assert!(replace_blocker(translocated, false, true).unwrap().contains("App-Translocated"));
380 assert!(replace_blocker(app, false, false).unwrap().contains("isn't writable"));
381 assert!(replace_blocker(translocated, true, false).unwrap().contains("read-only"));
383 }
384
385 #[test]
386 fn a_mac_app_downloads_only_when_it_can_be_replaced() {
387 let kind = |blocked: Option<&str>| InstallKind::MacApp { app: PathBuf::from("/Applications/AgentMux.app"), blocked: blocked.map(String::from) };
388 assert!(kind(None).can_download());
389 assert!(!kind(Some("read-only")).can_download());
390 assert_eq!(kind(None).label(), "macos-app");
391 }
392
393 #[cfg(unix)]
394 #[test]
395 fn the_filesystem_checks_follow_the_real_folder() {
396 use std::os::unix::fs::PermissionsExt;
397 let dir = tempfile::tempdir().unwrap();
398 std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o755)).unwrap();
401 assert!(writable_dir(dir.path()));
402 assert!(!on_read_only_volume(dir.path()));
403 let exe = dir.path().join(NESTED);
405 std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
406 let kind = detect_at(&exe, "macos", false, false);
407 assert_eq!(kind, InstallKind::MacApp { app: dir.path().join("AgentMux.app"), blocked: None });
408 assert!(kind.can_download());
409 let locked = dir.path().join("locked");
411 std::fs::create_dir_all(&locked).unwrap();
412 std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o555)).unwrap();
413 let in_locked = locked.join(NESTED);
414 let blocked = detect_at(&in_locked, "macos", false, false);
415 std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o755)).unwrap();
416 if unsafe { libc::geteuid() } != 0 {
418 assert!(!blocked.can_download(), "{blocked:?}");
419 }
420 assert!(!writable_dir(&dir.path().join("missing")));
421 }
422}