Skip to main content

agentmux_launcher/
start_at_login.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `app:startatlogin`: one setting, three views
5//! (`docs/specs/SPEC_START_WITH_OS_2026_09_25.md` ยง3.9).
6//!
7//! The setting is the single source of truth, owned by srv like every other
8//! setting. The Settings toggle writes it with `setconfig`; the tray's check
9//! item writes it the same way, over the launcher's srv connection
10//! (`notify::request_start_at_login`, the path the tray's "pause
11//! notifications" already uses). srv broadcasts every change to all clients,
12//! so the Settings page, the tray check mark and the OS login entry all follow
13//! the one value: this module receives it (`observe`), refreshes the tray, and
14//! reconciles the login entry to it (`autostart::plan`).
15//!
16//! Off unless the user turns it on (owner decision, 2026-09-25).
17
18use std::sync::Mutex;
19
20/// Settings key.
21pub const SETTINGS_KEY: &str = "app:startatlogin";
22
23/// The last value srv reported. `None` until the first config frame arrives:
24/// the tray shows the item disabled until then, rather than guess.
25static SEEN: Mutex<Option<Option<bool>>> = Mutex::new(None);
26
27/// The log said once that the login entry's file is gone.
28static TOLD_MISSING: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
29
30/// Serializes reconciles, so two quick toggles cannot interleave their writes.
31static RECONCILE: Mutex<()> = Mutex::new(());
32
33/// The setting as the tray should show it: `None` = not known yet.
34pub fn current() -> Option<bool> {
35    SEEN.lock().unwrap_or_else(|e| e.into_inner()).map(|v| v.unwrap_or(false))
36}
37
38/// srv reported the setting (on connect, and after every settings change).
39/// `None` means the key is not set.
40pub fn observe(setting: Option<bool>) {
41    {
42        let mut seen = SEEN.lock().unwrap_or_else(|e| e.into_inner());
43        // Every settings change broadcasts the whole config; only act on this key.
44        if *seen == Some(setting) {
45            return;
46        }
47        *seen = Some(setting);
48    }
49    crate::tray::notify_menu::wake();
50    // Blocking I/O (schtasks on Windows), so off the async session.
51    std::thread::Builder::new()
52        .name("agentmux-start-at-login".into())
53        .spawn(reconcile_latest)
54        .ok();
55}
56
57/// The tray's check item was clicked.
58pub fn toggle() {
59    if let Some(on) = current() {
60        crate::notify::request_start_at_login(!on);
61    }
62    // Put the item back to the known value until srv confirms the change:
63    // some menus flip their own check mark on click.
64    crate::tray::notify_menu::wake();
65}
66
67fn reconcile_latest() {
68    let _guard = RECONCILE.lock().unwrap_or_else(|e| e.into_inner());
69    // Apply the newest value, not the one that spawned this thread, so a
70    // burst of changes ends in the last state.
71    let Some(setting) = *SEEN.lock().unwrap_or_else(|e| e.into_inner()) else { return };
72    let channel = crate::autostart::current_channel();
73    // Only a write needs the target. Resolving it must not stand in the way of
74    // turning start-at-login off (ReAgent P1 on #3788).
75    let target = crate::autostart::stable_target();
76    let target_str = target.as_ref().ok().map(|t| t.display().to_string());
77    let entry = crate::autostart::read_entry();
78    let moved_from = crate::autostart::moved_from();
79    let plan = crate::autostart::plan(setting, entry.as_ref(), &channel, target_str.as_deref(), moved_from.as_deref());
80    let result = match plan {
81        crate::autostart::Plan::Nothing => {
82            // Nothing to write, but an entry whose file is gone starts nothing at the next login, with no error
83            // anywhere: say so in the log, once per run.
84            if let Some(missing) = entry.as_ref().and_then(crate::autostart::missing_target) {
85                if !TOLD_MISSING.swap(true, std::sync::atomic::Ordering::Relaxed) {
86                    crate::log(&format!(
87                        "start-at-login: the login entry runs {missing}, which isn't there, so it will start nothing at login (written by channel {:?}; this is channel {channel})",
88                        entry.as_ref().and_then(|e| e.channel.as_deref())
89                    ));
90                }
91            }
92            return;
93        }
94        crate::autostart::Plan::Repoint => match (&target, &entry) {
95            // Same install, new place: the channel that owns the entry keeps owning it.
96            (Ok(t), Some(e)) => crate::autostart::enable(t, e.channel.as_deref().unwrap_or(&channel)),
97            _ => Err("no target to point the login entry at".to_string()),
98        },
99        crate::autostart::Plan::Write => match &target {
100            Ok(t) => crate::autostart::enable(t, &channel),
101            Err(e) => Err(format!("no target to register: {e}")),
102        },
103        crate::autostart::Plan::Remove => crate::autostart::disable(),
104        crate::autostart::Plan::Adopt => {
105            crate::notify::request_start_at_login(true);
106            Ok(())
107        }
108    };
109    match result {
110        Ok(()) => crate::log(&format!(
111            "start-at-login: {plan:?} (setting={setting:?}, channel={channel}, target={target_str:?}, was={entry:?})"
112        )),
113        Err(e) => crate::log(&format!("start-at-login: {plan:?} failed: {e}")),
114    }
115}