agentmux_launcher/autostart/
login_item.rs1#![cfg_attr(not(target_os = "macos"), allow(dead_code))]
28
29use std::path::{Path, PathBuf};
30
31pub const LOGIN_START_FLAG: &str = "--login-start";
33
34pub const OPEN_LOGIN_ITEMS_FLAG: &str = "--open-login-items";
36
37pub const AGENT_PLIST_DIR: &str = "Contents/Library/LaunchAgents";
39
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Registration {
43 NotRegistered,
44 Enabled,
45 RequiresApproval,
47 NotFound,
49}
50
51pub fn registration_from_raw(raw: i64) -> Option<Registration> {
53 match raw {
54 0 => Some(Registration::NotRegistered),
55 1 => Some(Registration::Enabled),
56 2 => Some(Registration::RequiresApproval),
57 3 => Some(Registration::NotFound),
58 _ => None,
59 }
60}
61
62impl Registration {
63 pub fn is_registered(self) -> bool {
66 matches!(self, Registration::Enabled | Registration::RequiresApproval)
67 }
68}
69
70pub fn agent_plist_in(names: &[String]) -> Option<&str> {
73 let mut plists = names.iter().filter(|n| n.ends_with(".plist") && !n.starts_with('.'));
74 let first = plists.next()?;
75 if plists.next().is_some() {
76 return None;
77 }
78 Some(first.as_str())
79}
80
81fn bundled_agent_plist(app: &Path) -> Option<String> {
83 let names: Vec<String> = std::fs::read_dir(app.join(AGENT_PLIST_DIR))
84 .ok()?
85 .flatten()
86 .filter(|e| e.file_type().is_ok_and(|t| t.is_file()))
87 .map(|e| e.file_name().to_string_lossy().into_owned())
88 .collect();
89 agent_plist_in(&names).map(str::to_string)
90}
91
92pub fn bundle() -> Option<(PathBuf, String)> {
95 static BUNDLE: std::sync::OnceLock<Option<(PathBuf, String)>> = std::sync::OnceLock::new();
96 BUNDLE
97 .get_or_init(|| {
98 if !cfg!(target_os = "macos") || !platform::service_available() {
99 return None;
100 }
101 let app = agentmux_common::runtime_mode::app_bundle_of(&std::env::current_exe().ok()?)?;
102 let plist = bundled_agent_plist(&app)?;
103 Some((app, plist))
104 })
105 .clone()
106}
107
108pub fn available() -> bool {
110 bundle().is_some()
111}
112
113pub fn registration() -> Option<Registration> {
115 let (_, plist) = bundle()?;
116 platform::status(&plist)
117}
118
119pub fn register() -> Result<(), String> {
121 let (_, plist) = bundle().ok_or_else(|| "this build has no login item".to_string())?;
122 platform::register(&plist)
123}
124
125pub fn unregister() -> Result<(), String> {
127 let Some((_, plist)) = bundle() else { return Ok(()) };
128 match platform::status(&plist) {
129 Some(Registration::NotRegistered | Registration::NotFound) => Ok(()),
130 _ => platform::unregister(&plist),
131 }
132}
133
134pub fn open_settings() -> Result<(), String> {
136 platform::open_settings()
137}
138
139pub fn login_start() -> i32 {
142 let Some(app) = agentmux_common::runtime_mode::app_bundle_of(&std::env::current_exe().unwrap_or_default()) else {
143 return 2;
144 };
145 if platform::app_is_running() {
146 crate::log("login start: AgentMux is already running; nothing to do");
147 return 0;
148 }
149 crate::log(&format!("login start: opening {} in background mode", app.display()));
150 match std::process::Command::new("/usr/bin/open").arg(&app).arg("--args").arg(crate::autostart::BACKGROUND_FLAG).status() {
151 Ok(s) if s.success() => 0,
152 Ok(s) => {
153 crate::log(&format!("login start: open exited with {s}"));
154 1
155 }
156 Err(e) => {
157 crate::log(&format!("login start: could not run open: {e}"));
158 1
159 }
160 }
161}
162
163#[cfg(target_os = "macos")]
164mod platform {
165 use super::Registration;
166 use std::os::raw::c_char;
167
168 type Id = *mut std::ffi::c_void;
169 type Sel = *mut std::ffi::c_void;
170
171 #[link(name = "ServiceManagement", kind = "framework")]
172 #[link(name = "AppKit", kind = "framework")]
173 #[link(name = "Foundation", kind = "framework")]
174 #[link(name = "objc")]
175 extern "C" {
176 fn objc_getClass(name: *const c_char) -> *const std::ffi::c_void;
178 fn sel_registerName(name: *const c_char) -> *const std::ffi::c_void;
179 fn objc_msgSend();
180 }
181
182 unsafe fn class(name: &[u8]) -> Id {
183 objc_getClass(name.as_ptr() as *const c_char) as Id
184 }
185 unsafe fn sel(name: &[u8]) -> Sel {
186 sel_registerName(name.as_ptr() as *const c_char) as Sel
187 }
188 unsafe fn send(recv: Id, s: Sel) -> Id {
189 let f: extern "C" fn(Id, Sel) -> Id = std::mem::transmute(objc_msgSend as *const ());
190 f(recv, s)
191 }
192 unsafe fn send_id(recv: Id, s: Sel, a: Id) -> Id {
193 let f: extern "C" fn(Id, Sel, Id) -> Id = std::mem::transmute(objc_msgSend as *const ());
194 f(recv, s, a)
195 }
196 unsafe fn send_i64(recv: Id, s: Sel) -> i64 {
197 let f: extern "C" fn(Id, Sel) -> i64 = std::mem::transmute(objc_msgSend as *const ());
198 f(recv, s)
199 }
200 unsafe fn send_usize(recv: Id, s: Sel) -> usize {
201 let f: extern "C" fn(Id, Sel) -> usize = std::mem::transmute(objc_msgSend as *const ());
202 f(recv, s)
203 }
204 unsafe fn send_err(recv: Id, s: Sel, err: *mut Id) -> u8 {
205 let f: extern "C" fn(Id, Sel, *mut Id) -> u8 = std::mem::transmute(objc_msgSend as *const ());
206 f(recv, s, err)
207 }
208 unsafe fn send_void(recv: Id, s: Sel) {
209 let f: extern "C" fn(Id, Sel) = std::mem::transmute(objc_msgSend as *const ());
210 f(recv, s)
211 }
212
213 unsafe fn nsstring(s: &str) -> Id {
214 let c = std::ffi::CString::new(s.replace('\0', "")).unwrap_or_default();
216 let f: extern "C" fn(Id, Sel, *const c_char) -> Id = std::mem::transmute(objc_msgSend as *const ());
217 f(class(b"NSString\0"), sel(b"stringWithUTF8String:\0"), c.as_ptr())
218 }
219
220 unsafe fn rust_string(ns: Id) -> String {
221 if ns.is_null() {
222 return String::new();
223 }
224 let f: extern "C" fn(Id, Sel) -> *const c_char = std::mem::transmute(objc_msgSend as *const ());
225 let p = f(ns, sel(b"UTF8String\0"));
226 if p.is_null() {
227 String::new()
228 } else {
229 std::ffi::CStr::from_ptr(p).to_string_lossy().into_owned()
230 }
231 }
232
233 fn pooled<T>(body: impl FnOnce() -> T) -> T {
235 unsafe {
236 let pool = send(send(class(b"NSAutoreleasePool\0"), sel(b"alloc\0")), sel(b"init\0"));
237 let out = body();
238 send_void(pool, sel(b"drain\0"));
239 out
240 }
241 }
242
243 pub fn service_available() -> bool {
245 unsafe { !class(b"SMAppService\0").is_null() }
246 }
247
248 unsafe fn service(plist: &str) -> Id {
249 send_id(class(b"SMAppService\0"), sel(b"agentServiceWithPlistName:\0"), nsstring(plist))
250 }
251
252 pub fn status(plist: &str) -> Option<Registration> {
253 pooled(|| unsafe {
254 let svc = service(plist);
255 if svc.is_null() {
256 return None;
257 }
258 super::registration_from_raw(send_i64(svc, sel(b"status\0")))
259 })
260 }
261
262 pub fn register(plist: &str) -> Result<(), String> {
263 change(plist, b"registerAndReturnError:\0", "register")
264 }
265
266 pub fn unregister(plist: &str) -> Result<(), String> {
267 change(plist, b"unregisterAndReturnError:\0", "unregister")
268 }
269
270 fn change(plist: &str, verb: &'static [u8], what: &str) -> Result<(), String> {
271 pooled(|| unsafe {
272 let svc = service(plist);
273 if svc.is_null() {
274 return Err(format!("{what} the login item: the system has no such service"));
275 }
276 let mut err: Id = std::ptr::null_mut();
277 if send_err(svc, sel(verb), &mut err) != 0 {
278 return Ok(());
279 }
280 let why = if err.is_null() { "no reason given".to_string() } else { rust_string(send(err, sel(b"localizedDescription\0"))) };
281 Err(format!("{what} the login item: {why}"))
282 })
283 }
284
285 pub fn open_settings() -> Result<(), String> {
286 pooled(|| unsafe {
287 let cls = class(b"SMAppService\0");
288 if cls.is_null() {
289 return Err("this macOS cannot open the Login Items settings".to_string());
290 }
291 send_void(cls, sel(b"openSystemSettingsLoginItems\0"));
292 Ok(())
293 })
294 }
295
296 pub fn app_is_running() -> bool {
298 pooled(|| unsafe {
299 let bundle = send(class(b"NSBundle\0"), sel(b"mainBundle\0"));
300 let id = send(bundle, sel(b"bundleIdentifier\0"));
301 if id.is_null() {
302 return false;
303 }
304 let apps = send_id(class(b"NSRunningApplication\0"), sel(b"runningApplicationsWithBundleIdentifier:\0"), id);
305 let me = std::process::id() as i64;
306 let count = send_usize(apps, sel(b"count\0"));
307 (0..count).any(|i| {
308 let f: extern "C" fn(Id, Sel, usize) -> Id = std::mem::transmute(objc_msgSend as *const ());
309 let app = f(apps, sel(b"objectAtIndex:\0"), i);
310 send_i64(app, sel(b"processIdentifier\0")) != me
311 })
312 })
313 }
314}
315
316#[cfg(not(target_os = "macos"))]
317mod platform {
318 use super::Registration;
319
320 pub fn service_available() -> bool {
321 false
322 }
323 pub fn status(_plist: &str) -> Option<Registration> {
324 None
325 }
326 pub fn register(_plist: &str) -> Result<(), String> {
327 Err("not macOS".to_string())
328 }
329 pub fn unregister(_plist: &str) -> Result<(), String> {
330 Err("not macOS".to_string())
331 }
332 pub fn open_settings() -> Result<(), String> {
333 Err("not macOS".to_string())
334 }
335 pub fn app_is_running() -> bool {
336 false
337 }
338}
339
340#[cfg(test)]
341mod tests {
342 use super::*;
343
344 #[test]
345 fn the_raw_status_maps_to_the_four_states_and_nothing_else() {
346 assert_eq!(registration_from_raw(0), Some(Registration::NotRegistered));
347 assert_eq!(registration_from_raw(1), Some(Registration::Enabled));
348 assert_eq!(registration_from_raw(2), Some(Registration::RequiresApproval));
349 assert_eq!(registration_from_raw(3), Some(Registration::NotFound));
350 assert_eq!(registration_from_raw(4), None);
351 assert_eq!(registration_from_raw(-1), None);
352 }
353
354 #[test]
355 fn a_registration_waiting_for_approval_still_counts_as_registered() {
356 assert!(Registration::Enabled.is_registered());
357 assert!(Registration::RequiresApproval.is_registered());
358 assert!(!Registration::NotRegistered.is_registered());
359 assert!(!Registration::NotFound.is_registered());
360 }
361
362 #[test]
363 fn exactly_one_plist_is_the_bundles_login_agent() {
364 let names = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<Vec<_>>();
365 assert_eq!(agent_plist_in(&names(&["ai.agentmux.stable.login.plist"])), Some("ai.agentmux.stable.login.plist"));
366 assert_eq!(agent_plist_in(&names(&[])), None);
367 assert_eq!(agent_plist_in(&names(&["a.plist", "b.plist"])), None, "two would leave the system to choose");
368 assert_eq!(agent_plist_in(&names(&[".DS_Store", "readme.txt"])), None);
369 assert_eq!(agent_plist_in(&names(&[".hidden.plist", "a.plist"])), Some("a.plist"));
370 }
371
372 #[test]
373 fn a_bundle_without_the_plist_has_no_login_item() {
374 let dir = std::env::temp_dir().join(format!("agentmux-login-item-test-{}", std::process::id()));
375 let app = dir.join("AgentMux.app");
376 std::fs::create_dir_all(app.join("Contents/MacOS")).unwrap();
377 assert_eq!(bundled_agent_plist(&app), None);
378 std::fs::create_dir_all(app.join(AGENT_PLIST_DIR)).unwrap();
379 assert_eq!(bundled_agent_plist(&app), None, "an empty folder is no plist");
380 std::fs::write(app.join(AGENT_PLIST_DIR).join("ai.agentmux.stable.login.plist"), "x").unwrap();
381 assert_eq!(bundled_agent_plist(&app).as_deref(), Some("ai.agentmux.stable.login.plist"));
382 let _ = std::fs::remove_dir_all(&dir);
383 }
384}