Skip to main content

agentmux_launcher/autostart/
login_item.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! macOS: start at login through `SMAppService`, so the entry shows in System Settings -> General -> Login Items &
5//! Extensions where people look for it, and respects the approval they give there
6//! (`docs/specs/SPEC_START_WITH_OS_2026_09_25.md` ยง3.7, phase 4).
7//!
8//! ## What is registered, and why not `SMAppService.mainApp`
9//!
10//! A bundle that ships `Contents/Library/LaunchAgents/<label>.plist` registers that **agent**
11//! (`SMAppService.agent(plistName:)`). The plist's job is the launcher itself with `--login-start`: a shim that, at
12//! login, opens the app through LaunchServices (`open <app> --args --background`) unless it already runs, then exits.
13//!
14//! - `mainApp` cannot carry `--background`, which is what makes a login start a tray start with no window.
15//! - An agent whose job *is* AgentMux dies when the entry is switched off: unregistering boots the job out and
16//!   launchd stops its process (checked on macOS 26.5, 2026-11-20). With the shim, the running app is a LaunchServices
17//!   child, not the job, so Settings can switch the entry off from inside the app that login started.
18//! - A process started by `launchd` rather than LaunchServices is refused by `UNUserNotificationCenter` ("notifications
19//!   are not allowed", with no prompt; checked on macOS 26.5). Going through `open` keeps the login-started app able
20//!   to notify.
21//! - `BundleProgram` must be a signed Mach-O inside the bundle: a shell script fails launchd's launch constraints.
22//!
23//! The plist ships only in a bundle whose identifier is stable across versions (`scripts/package-macos.sh`); a bundle
24//! without it keeps writing the LaunchAgent plist of `autostart/mod.rs`, so nothing changes for dev, test or
25//! per-version builds. Registering an entry replaces that LaunchAgent plist (no double start, no orphan).
26
27#![cfg_attr(not(target_os = "macos"), allow(dead_code))]
28
29use std::path::{Path, PathBuf};
30
31/// What the launcher is asked to do by the login job: start AgentMux through LaunchServices if it is not running.
32pub const LOGIN_START_FLAG: &str = "--login-start";
33
34/// `--open-login-items`: open System Settings at Login Items (the page where the person approves AgentMux).
35pub const OPEN_LOGIN_ITEMS_FLAG: &str = "--open-login-items";
36
37/// The folder inside an app bundle that holds a registrable agent plist.
38pub const AGENT_PLIST_DIR: &str = "Contents/Library/LaunchAgents";
39
40/// `SMAppService.Status`.
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum Registration {
43    NotRegistered,
44    Enabled,
45    /// Registered, but the person has not allowed it (or switched it off) in System Settings.
46    RequiresApproval,
47    /// The system has no such service: the plist is not where the bundle says, or the bundle was not found.
48    NotFound,
49}
50
51/// The raw `SMAppService.Status` (`notRegistered` 0, `enabled` 1, `requiresApproval` 2, `notFound` 3).
52pub 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    /// Whether the system will start the entry at login, or would once the person approves it: the registration
64    /// exists, so it is "on" as far as a second registration or a read of the entry is concerned.
65    pub fn is_registered(self) -> bool {
66        matches!(self, Registration::Enabled | Registration::RequiresApproval)
67    }
68}
69
70/// The file name of the agent plist a bundle ships, when it ships exactly one. More than one is a packaging mistake
71/// (which would the system start?), so it counts as none.
72pub 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
81/// The agent plist the bundle that holds `app` ships: its file name, if it ships exactly one.
82fn 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
92/// The app bundle and agent plist name this launcher registers: set when this launcher runs from an app bundle that
93/// ships an agent plist and the system has `SMAppService` (macOS 13). `None` everywhere else.
94pub 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
108/// Whether start at login goes through `SMAppService` in this launcher.
109pub fn available() -> bool {
110    bundle().is_some()
111}
112
113/// The registration as the system has it. `None` when [`available`] is false or the system does not answer.
114pub fn registration() -> Option<Registration> {
115    let (_, plist) = bundle()?;
116    platform::status(&plist)
117}
118
119/// Register the agent. Re-registering one that is registered is not an error.
120pub 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
125/// Remove the registration. Succeeds when there is none.
126pub 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
134/// Open System Settings at Login Items, where the person allows AgentMux (status `RequiresApproval`).
135pub fn open_settings() -> Result<(), String> {
136    platform::open_settings()
137}
138
139/// What the login job does: nothing when this app already runs (a registration made while it is open, or a second
140/// login item), otherwise open it through LaunchServices in background mode and leave. Returns the exit code.
141pub 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        // The same signatures as `splash_mac.rs` declares (the linker sees one symbol).
177        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        // The text is ours (a plist file name); a NUL inside it would cut it short, so it is rejected before.
215        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    /// Run `body` inside an autorelease pool: the launcher's threads that call this have none of their own.
234    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    /// `SMAppService` exists from macOS 13; before that the class is not there.
244    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    /// Whether an app with this bundle's identifier is running (this process excluded).
297    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}