Skip to main content

agentmux_launcher/autostart/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Auto-start-at-login registration — issue #2977 Workstream 2,
5//! `docs/specs/SPEC_TRAY_OPTIONAL_BACKGROUND_SERVICE_2026_09_04.md` §4.
6//!
7//! ## Opt-in, off by default, and separate from "close to tray"
8//!
9//! Nothing here runs unless the user explicitly asks for it. The issue is
10//! emphatic that these are two different decisions: "a user can have
11//! 'close-to-tray keeps it running for this session' without 'starts
12//! automatically at every login' being bundled into the same toggle". So
13//! auto-start has its own state, its own enable/disable, and is never
14//! implied by `AGENTMUX_TRAY` or `AGENTMUX_BACKGROUND_SERVICE`.
15//!
16//! ## Mechanism per platform, and what was rejected
17//!
18//! - **Windows — Scheduled Task, `LogonType=InteractiveToken`.** Not a
19//!   Windows Service (needs admin to register, and Session-0 isolation means
20//!   it structurally cannot show a tray icon), and not a bare `Run` registry
21//!   key (no crash supervision, no delay control).
22//! - **macOS — LaunchAgent plist. This DEVIATES from the governing spec, and
23//!   the deviation has a user-visible consequence.**
24//!   `SPEC_TRAY_OPTIONAL_BACKGROUND_SERVICE_2026_09_04.md` §4 calls
25//!   `SMAppService` "unambiguously current best practice" and notes it is the
26//!   only path that surfaces correctly in **System Settings → Login Items &
27//!   Extensions**. Writing the LaunchAgent directly means the entry may not
28//!   appear there the way a user expects, which matters more than usual here:
29//!   Workstream 4 requires that a user be able to *see* and remove a
30//!   background service, and Login Items is where they will look.
31//!   `SMAppService` is only callable through its ObjC interface from inside a
32//!   **bundled, signed** app, so adopting it means objc2 bindings plus a
33//!   bundle identifier that matches the registered agent — real work that
34//!   cannot be written blind or verified on a non-macOS machine. Recorded as
35//!   a known gap rather than pretended away: macOS auto-start should move to
36//!   `SMAppService` before it is offered to users. (ReAgent P1 on PR #2999.)
37//! - **Linux — XDG autostart `.desktop`.** `systemd --user` is deliberately
38//!   NOT the default: surviving logout needs `loginctl enable-linger`, which
39//!   is a separate, consequential decision the issue says must never be
40//!   silently enabled.
41//!
42//! ## Uninstall is a first-class operation (Workstream 4)
43//!
44//! WS4 requires "one complete, independently-testable uninstall path that
45//! actually removes the LaunchAgent/Scheduled-Task/autostart artifact — not
46//! just closes the window". `disable()` is that path, and `is_enabled()`
47//! makes it independently checkable: the pair is the whole contract, and
48//! `disable()` is idempotent so an uninstaller can call it unconditionally.
49//!
50//! ## Structure
51//!
52//! The artifact *content* (Task Scheduler XML, plist, desktop entry) is
53//! generated by pure functions that take an exe path and return a string.
54//! That keeps the part most likely to be subtly wrong — escaping, schema
55//! fields, the `InteractiveToken` logon type — unit-testable without
56//! touching the machine's real login configuration.
57
58#[cfg(windows)]
59use agentmux_common::win32::NoWindow;
60use std::path::Path;
61
62pub mod login_item;
63#[cfg(target_os = "windows")]
64pub mod packaged;
65
66#[cfg(any(target_os = "windows", test))]
67mod task_xml;
68#[cfg(any(target_os = "windows", test))]
69pub use task_xml::scheduled_task_xml;
70
71/// The flag every generated artifact passes to the launcher.
72///
73/// This is the ONLY thing that makes an auto-started instance behave like a
74/// background service. Without it being interpreted, an auto-start entry
75/// would just open an ordinary foreground window at login and still quit when
76/// the user closed it — i.e. the feature would silently not work (Codex P1 on
77/// PR #2999).
78pub const BACKGROUND_FLAG: &str = "--background";
79
80/// Did the launcher get started in background mode?
81///
82/// Pure so the argv parsing is testable. Callers turn this into the env the
83/// host actually reads (`AGENTMUX_BACKGROUND_SERVICE`, plus `AGENTMUX_TRAY` —
84/// see `background_env_for`).
85pub fn background_requested(args: &[String]) -> bool {
86    args.iter().any(|a| a == BACKGROUND_FLAG) || started_by_login_task()
87}
88
89/// The Store package's startup task starts the exe with no arguments, so a login start there is known from how
90/// Windows activated the process, not from `--background`. Nowhere else is it ever true.
91fn started_by_login_task() -> bool {
92    #[cfg(target_os = "windows")]
93    {
94        packaged::started_by_startup_task()
95    }
96    #[cfg(not(target_os = "windows"))]
97    {
98        false
99    }
100}
101
102/// Was this process started by a login entry? Every artifact passes
103/// `--background`, and nothing else does.
104pub fn login_start() -> bool {
105    background_requested(&crate::launch_link::own_args())
106}
107
108/// A launcher that finds AgentMux already running forwards `open_new_window`
109/// to it, so a double-click opens a window. A login entry firing while the
110/// user already has AgentMux open must not (`SPEC_START_WITH_OS_2026_09_25.md`
111/// §3.6): it just exits.
112pub fn second_instance_opens_window(args: &[String]) -> bool {
113    !background_requested(args)
114}
115
116/// Environment the host must receive when the launcher was started with
117/// `--background`.
118///
119/// Sets BOTH switches deliberately. Background mode without a tray icon is
120/// the precise anti-pattern Workstream 4 exists to prevent: a process that
121/// starts itself at login, keeps running with no window, and offers the user
122/// no visible indicator that it is there or any way to stop it. Auto-start is
123/// the one context where the indicator is not optional, so `--background`
124/// implies the tray rather than leaving them independently settable.
125///
126/// Returns pairs rather than mutating a `Command` so the mapping is testable.
127pub fn background_env_for(args: &[String]) -> Vec<(&'static str, &'static str)> {
128    if background_requested(args) {
129        vec![
130            ("AGENTMUX_BACKGROUND_SERVICE", "1"),
131            ("AGENTMUX_TRAY", "1"),
132        ]
133    } else {
134        Vec::new()
135    }
136}
137
138/// Identifier used for the artifact on every platform: the Scheduled Task
139/// name, the LaunchAgent label's suffix, and the `.desktop` filename stem.
140/// Stable, because `disable()` has to find what `enable()` created —
141/// including across upgrades, so it deliberately carries no version.
142#[cfg(any(target_os = "windows", target_os = "linux", test))]
143pub const AUTOSTART_ID: &str = "AgentMux";
144
145/// Reverse-DNS label for the macOS LaunchAgent, which requires that form.
146#[cfg(any(not(target_os = "windows"), test))]
147pub const MACOS_LABEL: &str = "com.agentmux.launcher";
148
149/// Marks the owning channel inside the Task's `<Description>`, the only
150/// free-text field Task Scheduler keeps verbatim.
151const TASK_CHANNEL_MARKER: &str = "[agentmux-channel=";
152
153/// macOS LaunchAgent plist.
154///
155/// `RunAtLoad` starts it at login. `KeepAlive` is deliberately **false**: the
156/// launcher already supervises `srv`/`host` and owns its own restart policy,
157/// so letting `launchd` also restart it would give two supervisors fighting
158/// over the same process — and would make a user-requested Quit from the tray
159/// come straight back, which is worse than useless.
160#[cfg(any(not(target_os = "windows"), test))]
161pub fn launch_agent_plist(exe: &Path, channel: &str) -> String {
162    let exe = xml_escape(&exe.display().to_string());
163    let channel = xml_escape(channel);
164    format!(
165        r#"<?xml version="1.0" encoding="UTF-8"?>
166<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
167<plist version="1.0">
168<dict>
169    <key>Label</key>
170    <string>{label}</string>
171    <key>ProgramArguments</key>
172    <array>
173        <string>{exe}</string>
174        <string>--background</string>
175    </array>
176    <key>RunAtLoad</key>
177    <true/>
178    <key>KeepAlive</key>
179    <false/>
180    <key>ProcessType</key>
181    <string>Interactive</string>
182    <key>{channel_key}</key>
183    <string>{channel}</string>
184</dict>
185</plist>
186"#,
187        label = MACOS_LABEL,
188        exe = exe,
189        channel_key = PLIST_CHANNEL_KEY,
190        channel = channel,
191    )
192}
193
194/// Owning channel, as a plist key launchd ignores.
195const PLIST_CHANNEL_KEY: &str = "AgentMuxChannel";
196
197/// Linux XDG autostart desktop entry.
198///
199/// `X-GNOME-Autostart-enabled=true` is included because some desktops treat a
200/// missing value as disabled. `Terminal=false` keeps it from spawning a
201/// console window on desktops that honor it.
202///
203/// `TryExec` makes the entry inert once the target is gone (app removed,
204/// AppImage deleted): the session skips it instead of failing at every login
205/// (`SPEC_START_WITH_OS_2026_09_25.md` §3.1). `X-GNOME-Autostart-Delay` gives
206/// the tray host time to come up first (§3.4). `X-AgentMux-Channel` records
207/// which build owns the entry (§3.5).
208#[cfg(any(not(target_os = "windows"), test))]
209pub fn xdg_desktop_entry(exe: &Path, channel: &str) -> String {
210    format!(
211        "[Desktop Entry]\n\
212         Type=Application\n\
213         Name=AgentMux\n\
214         Comment=Starts AgentMux in the background at login\n\
215         TryExec={try_exec}\n\
216         Exec={prefix}\"{exe}\" {flag}\n\
217         Terminal=false\n\
218         X-GNOME-Autostart-enabled=true\n\
219         X-GNOME-Autostart-Delay=10\n\
220         {channel_key}={channel}\n",
221        try_exec = desktop_string_escape(&exe.display().to_string()),
222        prefix = exec_prefix(exe),
223        exe = desktop_exec_escape(exe),
224        flag = BACKGROUND_FLAG,
225        channel_key = XDG_CHANNEL_KEY,
226        channel = desktop_string_escape(channel),
227    )
228}
229
230/// Owning channel, as a vendor key (`X-` keys are ignored by the session).
231const XDG_CHANNEL_KEY: &str = "X-AgentMux-Channel";
232
233/// What goes before the program in the login entry's `Exec` line. An AppImage is run with AppImageLauncher
234/// switched off, as the in-app upgrade's restart does: at login that tool stops a file it hasn't integrated
235/// behind an "Integrate or Run once" window, and AgentMux doesn't start until someone answers it (#47873).
236#[cfg(any(not(target_os = "windows"), test))]
237fn exec_prefix(exe: &Path) -> &'static str {
238    if is_appimage(exe) {
239        APPIMAGELAUNCHER_OFF_PREFIX
240    } else {
241        ""
242    }
243}
244
245/// How an AppImage's `Exec` line starts.
246const APPIMAGELAUNCHER_OFF_PREFIX: &str = "env APPIMAGELAUNCHER_DISABLE=1 ";
247
248fn is_appimage(exe: &Path) -> bool {
249    exe.extension().is_some_and(|e| e.eq_ignore_ascii_case("appimage"))
250}
251
252/// Escape a plain desktop-entry string value (`TryExec`, vendor keys), per the
253/// Desktop Entry spec's `\\`, `\n`, `\t`, `\r` escapes. A raw newline would
254/// end the line and let a path inject keys, as `desktop_exec_escape` explains.
255#[cfg(any(not(target_os = "windows"), test))]
256fn desktop_string_escape(s: &str) -> String {
257    let mut out = String::with_capacity(s.len());
258    for c in s.chars() {
259        match c {
260            '\\' => out.push_str("\\\\"),
261            '\n' => out.push_str("\\n"),
262            '\t' => out.push_str("\\t"),
263            '\r' => out.push_str("\\r"),
264            _ => out.push(c),
265        }
266    }
267    out
268}
269
270fn desktop_string_unescape(s: &str) -> String {
271    let mut out = String::with_capacity(s.len());
272    let mut it = s.chars();
273    while let Some(c) = it.next() {
274        if c != '\\' {
275            out.push(c);
276            continue;
277        }
278        match it.next() {
279            Some('n') => out.push('\n'),
280            Some('t') => out.push('\t'),
281            Some('r') => out.push('\r'),
282            Some('s') => out.push(' '),
283            Some(o) => out.push(o),
284            None => out.push('\\'),
285        }
286    }
287    out
288}
289
290/// Escape a path for use inside a **quoted argument** of a desktop entry's
291/// `Exec=` value.
292///
293/// Stripping newlines is not enough (ReAgent/Codex P2 on PR #2999). All of
294/// these are legal in a Unix path and all of them change how the desktop-entry
295/// parser tokenizes the command:
296///
297/// - `"` terminates the quoted argument — the rest of the path becomes
298///   separate argv entries, so the app is launched with the wrong executable.
299/// - `\`, `` ` ``, `$` are reserved inside quoted arguments per the
300///   Desktop Entry Specification and must be backslash-escaped.
301/// - `%` introduces a **field code** (`%f`, `%U`, …); an unescaped one is
302///   substituted by the launcher. The spec's escape for a literal is `%%`.
303/// - newline/CR would end the `Exec=` line entirely and let the remainder be
304///   parsed as further desktop-entry keys (the original guard, kept).
305///
306/// Same injection class the XML path already handles via `xml_escape`; this
307/// is the desktop-entry grammar's version of it.
308#[cfg(any(not(target_os = "windows"), test))]
309fn desktop_exec_escape(exe: &Path) -> String {
310    let raw = exe.display().to_string();
311    let mut out = String::with_capacity(raw.len());
312    for c in raw.chars() {
313        match c {
314            // Reserved inside a quoted argument — escape with a backslash.
315            '"' | '\\' | '`' | '$' => {
316                out.push('\\');
317                out.push(c);
318            }
319            // Field-code introducer; `%%` is the literal.
320            '%' => out.push_str("%%"),
321            // Would terminate the Exec= line and allow key injection.
322            '\n' | '\r' => {}
323            _ => out.push(c),
324        }
325    }
326    out
327}
328
329/// Minimal XML text escaping for the two generated XML documents.
330///
331/// Only the five predefined entities matter here, and the only untrusted-ish
332/// input is a filesystem path (which can legitimately contain `&` and, on
333/// Unix, `<`/`>`/quotes). Hand-rolled rather than pulling an XML crate into a
334/// binary the codebase deliberately keeps tiny — the same reasoning
335/// `second_instance.rs` gives for hand-rolling its HTTP request.
336fn xml_escape(s: &str) -> String {
337    let mut out = String::with_capacity(s.len());
338    for c in s.chars() {
339        match c {
340            '&' => out.push_str("&amp;"),
341            '<' => out.push_str("&lt;"),
342            '>' => out.push_str("&gt;"),
343            '"' => out.push_str("&quot;"),
344            '\'' => out.push_str("&apos;"),
345            _ => out.push(c),
346        }
347    }
348    out
349}
350
351/// Where the artifact lives, for the platforms that use a plain file.
352/// Not used on Windows, whose artifact lives in the Task Scheduler store
353/// rather than a path we own.
354#[cfg(not(target_os = "windows"))]
355pub fn artifact_path() -> Option<std::path::PathBuf> {
356    #[cfg(target_os = "macos")]
357    {
358        let home = std::env::var("HOME").ok()?;
359        Some(
360            Path::new(&home)
361                .join("Library/LaunchAgents")
362                .join(format!("{}.plist", MACOS_LABEL)),
363        )
364    }
365    #[cfg(target_os = "linux")]
366    {
367        // Honor XDG_CONFIG_HOME; fall back to the spec's default.
368        let base = std::env::var("XDG_CONFIG_HOME")
369            .ok()
370            .filter(|s| !s.is_empty())
371            .unwrap_or_else(|| format!("{}/.config", std::env::var("HOME").unwrap_or_default()));
372        Some(
373            Path::new(&base)
374                .join("autostart")
375                .join(format!("{}.desktop", AUTOSTART_ID.to_lowercase())),
376        )
377    }
378    #[cfg(not(any(target_os = "macos", target_os = "linux")))]
379    {
380        None
381    }
382}
383
384/// A `schtasks` command that never opens a console window.
385///
386/// The launcher is a GUI-subsystem process and `schtasks.exe` is a console
387/// program, so a bare spawn flashes a console over the splash. The start-at-login
388/// reconcile runs `schtasks /Query` on every startup.
389#[cfg(target_os = "windows")]
390fn schtasks_command() -> std::process::Command {
391    let mut cmd = std::process::Command::new("schtasks");
392    cmd.no_window();
393    cmd
394}
395
396/// Is auto-start currently registered?
397///
398/// Half of the WS4 uninstall contract: an uninstall path is only
399/// "independently testable" if something can answer this without trusting
400/// whatever wrote it. So this inspects the real system state (the Task
401/// Scheduler store, or the artifact file) rather than any bookkeeping of our
402/// own.
403/// Is the Scheduled Task (every install but the Store package's login entry) registered? `/Query` fails if not.
404#[cfg(target_os = "windows")]
405fn scheduled_task_exists() -> bool {
406    schtasks_command()
407        .args(["/Query", "/TN", AUTOSTART_ID])
408        .stdout(std::process::Stdio::null())
409        .stderr(std::process::Stdio::null())
410        .status()
411        .map(|s| s.success())
412        .unwrap_or(false)
413}
414
415pub fn is_enabled() -> bool {
416    #[cfg(target_os = "windows")]
417    {
418        // The Store package's login entry is its startup task, which Windows owns.
419        if packaged::is_packaged() {
420            return packaged::state().map(packaged::TaskState::is_on).unwrap_or(false);
421        }
422        scheduled_task_exists()
423    }
424    #[cfg(not(target_os = "windows"))]
425    {
426        // A login item waiting for the person's approval is registered too: switching it on twice must not
427        // register it twice, and an uninstaller must find it.
428        artifact_path().map(|p| p.exists()).unwrap_or(false) || login_item::registration().is_some_and(|r| r.is_registered())
429    }
430}
431
432/// Register auto-start for `exe`. Idempotent: re-registering an existing
433/// entry replaces it, which is also how an upgrade repoints the artifact at a
434/// new install path.
435pub fn enable(exe: &Path, channel: &str) -> Result<(), String> {
436    #[cfg(target_os = "windows")]
437    {
438        if packaged::is_packaged() {
439            // The package's task runs no file AgentMux picks: `exe` and `channel` are written nowhere. A person's
440            // "off" in Windows stays off, and the error says so.
441            let _ = (exe, channel);
442            // A copy installed with the setup program has its own login entry, the Scheduled Task. Single
443            // instance is per version, so with both on, two versions start at login and show two tray icons.
444            // The other direction cannot be seen from outside the package, so only this one is checked.
445            if scheduled_task_exists() {
446                return Err(
447                    "start at login is already on for the AgentMux installed with the setup program: turn it off there first, so AgentMux does not start twice".to_string(),
448                );
449            }
450            return match packaged::request_enable()? {
451                s if s.is_on() => Ok(()),
452                packaged::TaskState::DisabledByUser => Err(
453                    "Windows has start at login turned off for AgentMux: turn it on in Settings > Apps > Startup".to_string(),
454                ),
455                packaged::TaskState::DisabledByPolicy => {
456                    Err("start at login is turned off for AgentMux by your organisation's policy".to_string())
457                }
458                _ => Err("Windows did not turn start at login on".to_string()),
459            };
460        }
461        // Register from XML — the only way to set LogonType/battery settings;
462        // the flag-based `schtasks /Create /SC ONLOGON` form cannot express
463        // them. The XML must be UTF-16 per the Task Scheduler schema
464        // declaration, so it is written as UTF-16LE with a BOM.
465        let xml = scheduled_task_xml(exe, channel);
466        let dir = std::env::temp_dir();
467        let path = dir.join(format!("agentmux-autostart-{}.xml", std::process::id()));
468        let mut bytes: Vec<u8> = vec![0xFF, 0xFE]; // UTF-16LE BOM
469        for unit in xml.encode_utf16() {
470            bytes.extend_from_slice(&unit.to_le_bytes());
471        }
472        std::fs::write(&path, &bytes).map_err(|e| format!("write task xml: {}", e))?;
473
474        // Capture output rather than discarding it: schtasks reports schema
475        // and permission problems on stderr, and an autostart registration
476        // that fails with only "exit code 1" is undiagnosable for a user or
477        // in a bug report.
478        let out = schtasks_command()
479            .args(["/Create", "/TN", AUTOSTART_ID, "/XML"])
480            .arg(&path)
481            .arg("/F") // replace an existing registration
482            .output();
483        // Best-effort cleanup; the temp file is harmless if it survives.
484        let _ = std::fs::remove_file(&path);
485
486        match out {
487            Ok(o) if o.status.success() => Ok(()),
488            Ok(o) => Err(format!(
489                "schtasks /Create failed ({}): {}{}",
490                o.status,
491                String::from_utf8_lossy(&o.stderr).trim(),
492                String::from_utf8_lossy(&o.stdout).trim()
493            )),
494            Err(e) => Err(format!("run schtasks: {}", e)),
495        }
496    }
497    #[cfg(not(target_os = "windows"))]
498    {
499        // A bundle that ships a login agent registers it with the system (`SMAppService`): the entry shows in Login
500        // Items, and the LaunchAgent plist an earlier build wrote is removed so AgentMux does not start twice.
501        if login_item::available() {
502            let _ = (exe, channel);
503            login_item::register()?;
504            return remove_launch_agent_plist();
505        }
506        let path = artifact_path().ok_or_else(|| "unsupported platform".to_string())?;
507        let contents = if cfg!(target_os = "macos") {
508            launch_agent_plist(exe, channel)
509        } else {
510            xdg_desktop_entry(exe, channel)
511        };
512        if let Some(parent) = path.parent() {
513            std::fs::create_dir_all(parent)
514                .map_err(|e| format!("create {}: {}", parent.display(), e))?;
515        }
516        std::fs::write(&path, contents).map_err(|e| format!("write {}: {}", path.display(), e))
517    }
518}
519
520/// Remove auto-start registration. **Idempotent** — succeeds when nothing was
521/// registered, so an uninstaller can call it unconditionally without first
522/// asking whether the feature was ever turned on.
523///
524/// This is the WS4 "complete uninstall path": it removes the actual
525/// Scheduled Task / LaunchAgent / desktop entry, not merely some internal
526/// flag. `is_enabled()` afterwards is the independent check that it worked.
527pub fn disable() -> Result<(), String> {
528    #[cfg(target_os = "windows")]
529    {
530        if packaged::is_packaged() {
531            return packaged::disable();
532        }
533        if !is_enabled() {
534            return Ok(());
535        }
536        match schtasks_command()
537            .args(["/Delete", "/TN", AUTOSTART_ID, "/F"])
538            .stdout(std::process::Stdio::null())
539            .stderr(std::process::Stdio::null())
540            .status()
541        {
542            Ok(s) if s.success() => Ok(()),
543            Ok(s) => Err(format!("schtasks /Delete failed: {}", s)),
544            Err(e) => Err(format!("run schtasks: {}", e)),
545        }
546    }
547    #[cfg(not(target_os = "windows"))]
548    {
549        // Both: the registration of a build that ships a login agent, and the plist an earlier build wrote.
550        login_item::unregister()?;
551        remove_launch_agent_plist()
552    }
553}
554
555/// Remove the login entry written as a file (the LaunchAgent plist, the XDG desktop entry). Succeeds when it is not
556/// there, which is what makes [`disable`] safe to call unconditionally from an uninstaller.
557#[cfg(not(target_os = "windows"))]
558fn remove_launch_agent_plist() -> Result<(), String> {
559    let Some(path) = artifact_path() else {
560        return Ok(());
561    };
562    match std::fs::remove_file(&path) {
563        Ok(()) => Ok(()),
564        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
565        Err(e) => Err(format!("remove {}: {}", path.display(), e)),
566    }
567}
568
569/// Handle the auto-start CLI verbs, if present. Returns `true` when one was
570/// handled and the process should exit.
571///
572/// Without this the module would be unreachable in a shipped build — nothing
573/// could opt in, query, or remove the registration (Codex P1 on PR #2999).
574/// A CLI surface rather than only a UI toggle is deliberate: it gives an
575/// **uninstaller** something to call, which is precisely what Workstream 4's
576/// "one complete, independently-testable uninstall path" needs. A GUI toggle
577/// can be layered on later and should call the same functions.
578///
579/// Verbs (checked before any heavy startup work, so they are cheap and cannot
580/// disturb a running instance):
581/// - `--enable-autostart`  — register, using this executable's own path
582/// - `--disable-autostart` — remove; idempotent, safe to run unconditionally
583/// - `--remove-autostart-for-this-install` — remove only an entry that runs a file from this
584///   executable's own folder (what an uninstaller calls)
585/// - `--autostart-status`  — print `enabled` / `disabled`, exit 0 either way;
586///   with `--json`, print the [`Status`] object instead
587/// The channel this launcher belongs to, which owns any entry it writes
588/// (`SPEC_START_WITH_OS_2026_09_25.md` §3.5). Resolved the same way as the
589/// data dir; `"unknown"` only if that resolution fails.
590pub fn current_channel() -> String {
591    std::env::current_exe()
592        .ok()
593        .and_then(|exe| {
594            let dir = exe.parent()?.to_path_buf();
595            crate::data_dir::resolve_paths(&dir, env!("CARGO_PKG_VERSION")).ok()
596        })
597        .map(|p| p.common.channel)
598        .unwrap_or_else(|| "unknown".to_string())
599}
600
601/// Env var the Linux AppRun and wrappers set to their own path right before
602/// they exec the launcher.
603const STABLE_EXE_ENV: &str = "AGENTMUX_STABLE_EXE";
604
605static STABLE_EXE: std::sync::OnceLock<Option<std::ffi::OsString>> = std::sync::OnceLock::new();
606
607/// Read `AGENTMUX_STABLE_EXE` and remove it from this process's env, so no
608/// child (host, srv, agent shells, a dev build started from a pane) inherits
609/// a path that belongs to this launch. `APPIMAGE` is not used for the same
610/// reason: the AppImage runtime's copy leaks into every agent shell.
611///
612/// MUST be called from `main` before any thread exists (`remove_var`).
613pub fn take_stable_exe_env() {
614    let value = std::env::var_os(STABLE_EXE_ENV).filter(|v| !v.is_empty());
615    std::env::remove_var(STABLE_EXE_ENV);
616    let _ = STABLE_EXE.set(value);
617}
618
619/// What the login entry should run: something that survives updates
620/// (`SPEC_START_WITH_OS_2026_09_25.md` §3.1), not this process's own path.
621///
622/// 1. `AGENTMUX_STABLE_EXE` as captured by `take_stable_exe_env`: the
623///    AppImage file (set by AppRun), or the deb/rpm/tarball wrapper that sets
624///    the `LD_LIBRARY_PATH` the raw launcher cannot run without.
625/// 2. `current_exe()`: Windows and macOS installs, portable and dev builds.
626pub fn stable_target() -> Result<std::path::PathBuf, String> {
627    stable_target_from(
628        STABLE_EXE.get().cloned().flatten(),
629        std::env::current_exe().map_err(|e| e.to_string()),
630    )
631}
632
633fn stable_target_from(
634    stable: Option<std::ffi::OsString>,
635    current: Result<std::path::PathBuf, String>,
636) -> Result<std::path::PathBuf, String> {
637    match stable.map(std::path::PathBuf::from) {
638        Some(p) if p.is_file() => Ok(p),
639        _ => current,
640    }
641}
642
643/// The login entry as it stands on this machine.
644#[derive(Debug, Clone, PartialEq, Eq)]
645pub struct Entry {
646    /// What it runs, if readable.
647    pub target: Option<String>,
648    /// Which channel wrote it. `None` for an entry from before ownership was
649    /// recorded.
650    pub channel: Option<String>,
651    /// Whether it is written the way this build writes it. `false` for an AppImage's entry from before it ran
652    /// with AppImageLauncher switched off: it is rewritten even when it already runs the right file.
653    pub current: bool,
654}
655
656/// Read the current entry back from the platform. `None` when there is none.
657pub fn read_entry() -> Option<Entry> {
658    #[cfg(target_os = "windows")]
659    {
660        // The package's task runs this package's launcher and belongs to this channel by construction.
661        if packaged::is_packaged() {
662            return packaged::state().ok().filter(|s| s.is_on()).map(|_| Entry {
663                target: std::env::current_exe().ok().map(|e| e.display().to_string()),
664                channel: Some(current_channel()),
665                current: true,
666            });
667        }
668        let out = schtasks_command()
669            .args(["/Query", "/TN", AUTOSTART_ID, "/XML"])
670            .stderr(std::process::Stdio::null())
671            .output()
672            .ok()?;
673        if !out.status.success() {
674            return None;
675        }
676        Some(parse_task_xml(&decode_console_output(&out.stdout)))
677    }
678    #[cfg(not(target_os = "windows"))]
679    {
680        // A registered login item is this build's own entry, whatever else is on the machine.
681        if login_item::registration().is_some_and(|r| r.is_registered()) {
682            return Some(Entry {
683                target: std::env::current_exe().ok().map(|p| p.display().to_string()),
684                channel: Some(current_channel()),
685                current: true,
686            });
687        }
688        let text = std::fs::read_to_string(artifact_path()?).ok()?;
689        let mut entry = if cfg!(target_os = "macos") {
690            parse_plist(&text)
691        } else {
692            parse_desktop_entry(&text)
693        };
694        // An earlier build's LaunchAgent plist, read by a build that registers a login item: out of date, so
695        // the reconcile rewrites it as the login item (`plan` writes for an entry that is not current).
696        if login_item::available() {
697            entry.current = false;
698        }
699        Some(entry)
700    }
701}
702
703/// `schtasks /XML` writes UTF-16LE when its output is redirected.
704#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
705fn decode_console_output(bytes: &[u8]) -> String {
706    let body = bytes.strip_prefix(&[0xFF, 0xFE]).unwrap_or(bytes);
707    if body.len() >= 2 && body.len() % 2 == 0 && body.iter().skip(1).step_by(2).take(64).all(|b| *b == 0) {
708        let units: Vec<u16> = body.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).collect();
709        return String::from_utf16_lossy(&units);
710    }
711    String::from_utf8_lossy(body).into_owned()
712}
713
714fn between<'a>(s: &'a str, start: &str, end: &str) -> Option<&'a str> {
715    let from = s.find(start)? + start.len();
716    let len = s[from..].find(end)?;
717    Some(&s[from..from + len])
718}
719
720fn xml_unescape(s: &str) -> String {
721    s.replace("&lt;", "<")
722        .replace("&gt;", ">")
723        .replace("&quot;", "\"")
724        .replace("&apos;", "'")
725        .replace("&amp;", "&")
726}
727
728#[cfg_attr(not(target_os = "windows"), allow(dead_code))]
729fn parse_task_xml(xml: &str) -> Entry {
730    let target = between(xml, "<Command>", "</Command>")
731        .map(|c| xml_unescape(c.trim()).trim_matches('"').to_string());
732    let channel = between(xml, "<Description>", "</Description>")
733        .and_then(|d| between(d, TASK_CHANNEL_MARKER, "]"))
734        .map(xml_unescape);
735    Entry { target, channel, current: true }
736}
737
738#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
739fn parse_plist(text: &str) -> Entry {
740    let target = between(text, "<key>ProgramArguments</key>", "</array>")
741        .and_then(|a| between(a, "<string>", "</string>"))
742        .map(xml_unescape);
743    let channel = between(text, &format!("<key>{PLIST_CHANNEL_KEY}</key>"), "</string>")
744        .and_then(|rest| rest.split_once("<string>").map(|(_, v)| xml_unescape(v)));
745    Entry { target, channel, current: true }
746}
747
748#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
749fn parse_desktop_entry(text: &str) -> Entry {
750    let value = |key: &str| {
751        text.lines()
752            .find_map(|l| l.strip_prefix(key).and_then(|r| r.strip_prefix('=')))
753            .map(desktop_string_unescape)
754    };
755    // `TryExec` is the plain path; an entry from before it existed has none,
756    // reads as "target unknown", and gets rewritten.
757    let target = value("TryExec");
758    // An AppImage's entry that doesn't start it with AppImageLauncher switched off is an older one.
759    let current = match (&target, value("Exec")) {
760        (Some(t), Some(exec)) if is_appimage(Path::new(t)) => exec.starts_with(APPIMAGELAUNCHER_OFF_PREFIX),
761        _ => true,
762    };
763    Entry { target, channel: value(XDG_CHANNEL_KEY), current }
764}
765
766/// What to do to bring the login entry in line with `app:startatlogin`
767/// (`SPEC_START_WITH_OS_2026_09_25.md` §3.9).
768#[derive(Debug, Clone, PartialEq, Eq)]
769pub enum Plan {
770    /// Already right, or not ours to touch.
771    Nothing,
772    /// Write (or rewrite) the entry for this channel and target.
773    Write,
774    /// Remove this channel's entry.
775    Remove,
776    /// An entry from before the setting existed, and the setting was never
777    /// set: the user turned start-at-login on with the old toggle, so record
778    /// that as `app:startatlogin = true` instead of removing it.
779    Adopt,
780    /// The entry runs this very file from where it was before it was moved or
781    /// renamed (AppImageLauncher's Integrate): point it at where the file is
782    /// now, keeping the channel that owns it.
783    Repoint,
784}
785
786/// Where the AppImage this launcher runs from was before it was moved or renamed, when it was
787/// (`agentmux_common::appimage_record::reconcile`, at start).
788static MOVED_FROM: std::sync::OnceLock<Option<String>> = std::sync::OnceLock::new();
789
790/// Remember where this launcher's AppImage came from, once per run.
791pub fn set_moved_from(from: Option<String>) {
792    let _ = MOVED_FROM.set(from);
793}
794
795pub(crate) fn moved_from() -> Option<String> {
796    MOVED_FROM.get().cloned().flatten()
797}
798
799/// What the launcher does first, before anything reads either: takes `AGENTMUX_STABLE_EXE` out of the
800/// environment ([`take_stable_exe_env`]), and notes where an AppImage has been moved from ([`note_appimage_start`]).
801pub fn startup() {
802    take_stable_exe_env();
803    note_appimage_start();
804    // How Windows started a packaged copy, so a bug report about a login start that opened a window or showed
805    // no tray says whether the package's startup task was recognised (`startup_task`) or not.
806    #[cfg(target_os = "windows")]
807    if packaged::is_packaged() {
808        crate::log(&format!("packaged start: activation {}", packaged::activation_name()));
809    }
810}
811
812/// At start, for an AppImage: put its channel record back beside it if a move or a rename left that behind, and
813/// keep where it is now (`agentmux_common::appimage_record`). Remembers where it was, for the login entry to follow.
814pub fn note_appimage_start() {
815    let moved = std::env::current_exe().ok().and_then(|exe| {
816        let appimage = agentmux_common::runtime_mode::running_appimage(&exe)?;
817        let record = agentmux_common::appimage_record::record_path()?;
818        let done = agentmux_common::appimage_record::reconcile(&record, &appimage);
819        if let Some(from) = &done.moved_from {
820            crate::log(&format!("appimage: moved or renamed since it last started (from {from}); channel {:?} kept", done.channel));
821        }
822        done.moved_from
823    });
824    set_moved_from(moved);
825}
826
827/// The file a login entry runs, when it isn't there: the session skips such an entry without a word
828/// (the desktop entry's `TryExec`), so AgentMux silently stops starting at login.
829pub fn missing_target(entry: &Entry) -> Option<&str> {
830    entry.target.as_deref().filter(|t| !t.is_empty() && !Path::new(t).exists())
831}
832
833/// How the login entry stands (`SPEC_START_WITH_OS_2026_09_25.md` §3.8).
834#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
835#[serde(rename_all = "snake_case")]
836pub enum State {
837    /// No login entry.
838    Off,
839    /// An entry that runs a file that is there.
840    On,
841    /// An entry whose file is gone: the session skips it without a word.
842    Broken,
843    /// Registered, but the system waits for the user's approval (macOS Login Items): `current_status` says so for a
844    /// login item whose registration is `RequiresApproval`.
845    NeedsApproval,
846}
847
848/// `--autostart-status --json`: what Settings shows next to the switch.
849#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
850pub struct Status {
851    pub state: State,
852    /// What the entry runs, when readable.
853    pub target: Option<String>,
854    /// The channel that wrote the entry; `None` for no entry or one from before ownership was recorded.
855    pub owner_channel: Option<String>,
856    pub this_channel: String,
857    /// The entry belongs to another channel (or to none) and this build can take it over.
858    pub movable: bool,
859    /// The Store package's startup task, as Windows says it now (`enabled`, `disabled`, `disabled_by_user`,
860    /// `disabled_by_policy`, `enabled_by_policy`); `None` anywhere that is not a packaged install.
861    #[serde(skip_serializing_if = "Option::is_none")]
862    pub package: Option<String>,
863    /// How Windows activated this process (`launch`, `startup_task`, `unknown`), packaged installs only.
864    #[serde(skip_serializing_if = "Option::is_none")]
865    pub activation: Option<String>,
866}
867
868/// Pure: the status from what is on the machine. `registered` is [`is_enabled`], which can say yes when
869/// `entry` could not be read (an entry this build cannot parse still starts something at login).
870/// `can_write` is whether this build has a target to point an entry at.
871pub fn status(entry: Option<&Entry>, registered: bool, this_channel: &str, can_write: bool) -> Status {
872    let state = match entry {
873        Some(e) if missing_target(e).is_some() => State::Broken,
874        Some(_) => State::On,
875        None if registered => State::On,
876        None => State::Off,
877    };
878    let owner_channel = entry.and_then(|e| e.channel.clone());
879    let movable = entry.is_some() && owner_channel.as_deref() != Some(this_channel) && can_write;
880    Status { state, target: entry.and_then(|e| e.target.clone()), owner_channel, this_channel: this_channel.to_string(), movable, package: None, activation: None }
881}
882
883/// Pure decision. `setting` is `app:startatlogin`, `None` when never set.
884/// `target` is `stable_target()`, `None` when it could not be resolved: only
885/// writing needs it, so removing or adopting never waits on it (ReAgent P1 on
886/// #3788).
887///
888/// - On: write unless the entry already runs `target` for this channel. This
889///   also re-points an entry after an update or a move, and takes ownership
890///   from another channel (last enabled wins).
891/// - Off: remove only an entry this channel owns. Another build's entry, or
892///   one from before ownership was recorded, is not this build's to remove.
893/// - Never set: off, except that an unowned (pre-setting) entry is adopted.
894pub fn plan(setting: Option<bool>, entry: Option<&Entry>, channel: &str, target: Option<&str>, moved_from: Option<&str>) -> Plan {
895    let owned = |e: &Entry| e.channel.as_deref() == Some(channel);
896    match (setting, entry) {
897        (Some(true), Some(e)) if owned(e) && e.current && target.is_some() && e.target.as_deref() == target => Plan::Nothing,
898        (Some(true), _) => Plan::Write,
899        (Some(false), Some(e)) if owned(e) => Plan::Remove,
900        (None, Some(e)) if e.channel.is_none() => Plan::Adopt,
901        // An entry that runs this very file from where it was follows the file, whichever channel wrote it
902        // and whatever this channel's setting is: it is the same install, moved.
903        (_, Some(e)) if target.is_some() && e.target.is_some() && e.target.as_deref() == moved_from && e.target.as_deref() != target => Plan::Repoint,
904        _ => Plan::Nothing,
905    }
906}
907
908/// [`status`] of this machine, with the login item's approval: a registration the person has not allowed (or has
909/// switched off) in System Settings is `needs_approval`, not `on` (`SPEC_START_WITH_OS_2026_09_25.md` §3.8).
910pub fn current_status() -> Status {
911    let mut s = status(read_entry().as_ref(), is_enabled(), &current_channel(), stable_target().is_ok());
912    if login_item::registration() == Some(login_item::Registration::RequiresApproval) {
913        s.state = State::NeedsApproval;
914    }
915    // The Store package's login entry is its startup task, which Windows owns: say what Windows says. A person's
916    // "off" there is not `needs_approval` (that is macOS' Login Items, with a button that opens it): the state
917    // stays off and Settings reads `package`.
918    #[cfg(target_os = "windows")]
919    if packaged::is_packaged() {
920        s.package = packaged::state().ok().map(|task| task.as_str().to_string());
921        s.activation = Some(packaged::activation_name());
922        s.movable = false;
923    }
924    s
925}
926
927/// Does the login entry run a file inside `dir`? An uninstaller asks this with its own install folder, so it
928/// removes the entry that would be left pointing at nothing (`SPEC_START_WITH_OS_2026_09_25.md` G6, G7) and
929/// leaves an entry that another install or channel owns alone. Windows paths compare without case.
930pub fn entry_runs_from(entry: &Entry, dir: &Path) -> bool {
931    fn norm(p: &str) -> String {
932        let p = p.trim_end_matches(|c| c == '\\' || c == '/');
933        if cfg!(target_os = "windows") { p.replace('/', "\\").to_lowercase() } else { p.to_string() }
934    }
935    let Some(target) = entry.target.as_deref().filter(|t| !t.is_empty()) else { return false };
936    let dir = norm(&dir.to_string_lossy());
937    let target = norm(target);
938    let sep = if cfg!(target_os = "windows") { '\\' } else { '/' };
939    !dir.is_empty() && target.len() > dir.len() && target.starts_with(&dir) && target[dir.len()..].starts_with(sep)
940}
941
942pub fn handle_cli(args: &[String]) -> bool {
943    let has = |v: &str| args.iter().any(|a| a == v);
944
945    // The login job of a build that registers a login item (`login_item`): open AgentMux and leave.
946    if has(login_item::LOGIN_START_FLAG) {
947        std::process::exit(login_item::login_start());
948    }
949    if has(login_item::OPEN_LOGIN_ITEMS_FLAG) {
950        match login_item::open_settings() {
951            Ok(()) => println!("opened Login Items"),
952            Err(e) => {
953                eprintln!("failed to open Login Items: {}", e);
954                std::process::exit(1);
955            }
956        }
957        return true;
958    }
959    if has("--autostart-status") {
960        if has("--json") {
961            let s = current_status();
962            println!("{}", serde_json::to_string(&s).unwrap_or_else(|_| "{}".to_string()));
963        } else {
964            println!("{}", if is_enabled() { "enabled" } else { "disabled" });
965        }
966        return true;
967    }
968    if has("--enable-autostart") {
969        match stable_target() {
970            Ok(exe) => match enable(&exe, &current_channel()) {
971                Ok(()) => println!("auto-start enabled ({})", exe.display()),
972                Err(e) => {
973                    eprintln!("failed to enable auto-start: {}", e);
974                    std::process::exit(1);
975                }
976            },
977            Err(e) => {
978                eprintln!("failed to resolve the auto-start target: {}", e);
979                std::process::exit(1);
980            }
981        }
982        return true;
983    }
984    if has("--disable-autostart") {
985        match disable() {
986            Ok(()) => println!("auto-start disabled"),
987            Err(e) => {
988                eprintln!("failed to disable auto-start: {}", e);
989                std::process::exit(1);
990            }
991        }
992        return true;
993    }
994    if has("--remove-autostart-for-this-install") {
995        // What an uninstaller runs (Inno's `[UninstallRun]`): remove the login entry only when it runs a file
996        // from this install's folder. Another build's entry stays; no entry is a success.
997        let dir = std::env::current_exe().ok().and_then(|e| e.parent().map(Path::to_path_buf));
998        match (read_entry(), dir) {
999            (Some(entry), Some(dir)) if entry_runs_from(&entry, &dir) => match disable() {
1000                Ok(()) => println!("auto-start entry for this install removed"),
1001                Err(e) => {
1002                    eprintln!("failed to remove the auto-start entry: {}", e);
1003                    std::process::exit(1);
1004                }
1005            },
1006            _ => println!("no auto-start entry runs from this install; left alone"),
1007        }
1008        return true;
1009    }
1010    false
1011}
1012
1013#[cfg(test)]
1014mod autostart_tests {
1015    use super::*;
1016    use std::path::PathBuf;
1017
1018    fn exe() -> PathBuf {
1019        PathBuf::from(r"C:\Program Files\AgentMux\agentmux.exe")
1020    }
1021
1022    /// `plan` for a file that wasn't moved.
1023    fn plan(setting: Option<bool>, entry: Option<&Entry>, channel: &str, target: Option<&str>) -> Plan {
1024        super::plan(setting, entry, channel, target, None)
1025    }
1026
1027    #[test]
1028    fn scheduled_task_uses_interactive_token_not_a_service_account() {
1029        // The whole reason WS2 specifies a Scheduled Task over a Windows
1030        // Service: Session-0 isolation means a service can never own a tray
1031        // icon or show a window. InteractiveToken is what puts it in the
1032        // user's own session.
1033        let xml = scheduled_task_xml(&exe(), "test");
1034        assert!(xml.contains("<LogonType>InteractiveToken</LogonType>"));
1035        assert!(
1036            xml.contains("<RunLevel>LeastPrivilege</RunLevel>"),
1037            "auto-start must never require elevation"
1038        );
1039    }
1040
1041    /// A logon trigger with no user is the any-user form, which only an elevated token may create. Naming the
1042    /// user in the trigger and the principal makes it this user's alone.
1043    #[test]
1044    fn scheduled_task_names_the_user_so_a_normal_token_can_create_it() {
1045        let xml = task_xml::scheduled_task_xml_for(&exe(), "test", Some(r"PC\Ann & Bo"));
1046        assert_eq!(xml.matches(r"<UserId>PC\Ann &amp; Bo</UserId>").count(), 2, "{xml}");
1047        let trigger = xml.split("<LogonTrigger>").nth(1).unwrap().split("</LogonTrigger>").next().unwrap();
1048        assert!(trigger.contains("<UserId>"));
1049        let principal = xml.split("<Principal id=\"Author\">").nth(1).unwrap().split("</Principal>").next().unwrap();
1050        assert!(principal.contains("<UserId>"));
1051        // Without a user it stays the form it was.
1052        assert!(!task_xml::scheduled_task_xml_for(&exe(), "test", None).contains("<UserId>"));
1053    }
1054
1055    #[test]
1056    fn scheduled_task_survives_battery_power() {
1057        // Task Scheduler defaults BOTH of these to true, which would make a
1058        // laptop user's "background service" silently fail to start on
1059        // battery, or die mid-turn on unplug — the unreliable-indicator
1060        // failure WS4 exists to prevent.
1061        let xml = scheduled_task_xml(&exe(), "test");
1062        assert!(xml.contains("<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>"));
1063        assert!(xml.contains("<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>"));
1064    }
1065
1066    #[test]
1067    fn scheduled_task_has_no_execution_time_limit() {
1068        // PT0S = unlimited. The default is 72 hours, after which Task
1069        // Scheduler would terminate a long-running background service.
1070        let xml = scheduled_task_xml(&exe(), "test");
1071        assert!(xml.contains("<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>"));
1072    }
1073
1074    #[test]
1075    fn generated_xml_escapes_paths() {
1076        // Install paths can contain `&` (and on Unix, quotes/angle brackets).
1077        // Unescaped, that produces XML that Task Scheduler rejects — or worse,
1078        // silently misparses.
1079        let xml = scheduled_task_xml(Path::new(r"C:\Tools & Apps\<agentmux>.exe"), "test");
1080        assert!(xml.contains("Tools &amp; Apps"));
1081        assert!(xml.contains("&lt;agentmux&gt;"));
1082        assert!(
1083            !xml.contains("Tools & Apps"),
1084            "raw ampersand would make the document invalid"
1085        );
1086    }
1087
1088    #[test]
1089    fn launch_agent_does_not_let_launchd_resurrect_a_user_quit() {
1090        // KeepAlive=false is deliberate: the launcher owns its own restart
1091        // policy, and a tray Quit that launchd immediately undid would be
1092        // worse than having no Quit at all.
1093        let plist = launch_agent_plist(Path::new("/Applications/AgentMux.app/Contents/MacOS/agentmux"), "test");
1094        assert!(plist.contains("<key>RunAtLoad</key>\n    <true/>"));
1095        assert!(plist.contains("<key>KeepAlive</key>\n    <false/>"));
1096        assert!(plist.contains(MACOS_LABEL));
1097    }
1098
1099    #[test]
1100    fn xdg_entry_is_a_valid_autostart_desktop_file() {
1101        let d = xdg_desktop_entry(Path::new("/opt/agentmux/agentmux"), "test");
1102        assert!(d.starts_with("[Desktop Entry]\n"));
1103        assert!(d.contains("Type=Application\n"));
1104        assert!(d.contains("X-GNOME-Autostart-enabled=true\n"));
1105        assert!(
1106            d.contains("Exec=\"/opt/agentmux/agentmux\" --background\n"),
1107            "Exec must quote the path so spaces don't split the command"
1108        );
1109    }
1110
1111    #[test]
1112    fn xdg_entry_cannot_be_injected_with_extra_keys_via_the_path() {
1113        // A newline in the path would otherwise terminate the Exec= line and
1114        // let the rest be parsed as further desktop-entry keys.
1115        let d = xdg_desktop_entry(Path::new("/opt/x\nHidden=true"), "test");
1116        assert!(!d.contains("\nHidden=true\n"), "newline must not survive into the file");
1117    }
1118
1119    /// Full enable → is_enabled → disable → is_enabled round trip against the
1120    /// REAL platform registry (Task Scheduler / LaunchAgents / XDG autostart).
1121    ///
1122    /// `#[ignore]` on purpose: it mutates the machine's actual login
1123    /// configuration, which is not something a plain `cargo test` — least of
1124    /// all one on a shared CI runner — should ever do as a side effect. Run it
1125    /// deliberately:
1126    ///
1127    /// ```text
1128    /// cargo test -p agentmux-launcher --release -- --ignored autostart_round_trip
1129    /// ```
1130    ///
1131    /// This is the WS4 "independently-testable uninstall path" made literal:
1132    /// it verifies removal by asking the platform, not by trusting our own
1133    /// bookkeeping. Self-cleaning — it disables at the end, and asserts the
1134    /// artifact is actually gone.
1135    #[test]
1136    #[ignore = "mutates real login configuration; run explicitly with --ignored"]
1137    fn autostart_round_trip_against_the_real_platform_registry() {
1138        // Refuse to run if the user already has autostart configured, rather
1139        // than clobbering (and then deleting) their real registration.
1140        assert!(
1141            !is_enabled(),
1142            "autostart already enabled on this machine — refusing to overwrite a real registration"
1143        );
1144
1145        let exe = std::env::current_exe().expect("current_exe");
1146        enable(&exe, "test").expect("enable should succeed");
1147        assert!(is_enabled(), "enable() must be observable through the platform");
1148
1149        // Idempotent re-enable (the upgrade path: repoint at a new exe).
1150        enable(&exe, "test").expect("re-enable should replace, not fail");
1151        assert!(is_enabled());
1152
1153        disable().expect("disable should succeed");
1154        assert!(!is_enabled(), "disable() must actually remove the artifact");
1155
1156        // Safe to call unconditionally — the property an uninstaller needs.
1157        disable().expect("disable must be idempotent");
1158    }
1159
1160    /// Codex P1 on PR #2999: `--background` was forwarded but interpreted
1161    /// nowhere, so an auto-started instance would open an ordinary foreground
1162    /// window and still quit on last-window-close. The flag must map onto the
1163    /// env the host actually reads.
1164    #[test]
1165    fn the_background_flag_maps_onto_the_env_the_host_actually_reads() {
1166        let args = vec!["agentmux.exe".to_string(), BACKGROUND_FLAG.to_string()];
1167        assert!(background_requested(&args));
1168        let env = background_env_for(&args);
1169        assert!(
1170            env.contains(&("AGENTMUX_BACKGROUND_SERVICE", "1")),
1171            "without this the auto-start entry is inert"
1172        );
1173    }
1174
1175    /// Auto-start is the one context where the indicator is not optional:
1176    /// a process that starts itself at login and runs with no window and no
1177    /// icon is exactly the invisible-background-agent pattern WS4 exists to
1178    /// prevent. So `--background` implies the tray.
1179    #[test]
1180    fn background_mode_also_forces_the_visible_indicator_on() {
1181        let args = vec![BACKGROUND_FLAG.to_string()];
1182        assert!(background_env_for(&args).contains(&("AGENTMUX_TRAY", "1")));
1183    }
1184
1185    #[test]
1186    fn a_normal_launch_sets_no_background_env() {
1187        let args = vec!["agentmux.exe".to_string(), "--url=http://x".to_string()];
1188        assert!(!background_requested(&args));
1189        assert!(
1190            background_env_for(&args).is_empty(),
1191            "an ordinary launch must be completely unaffected"
1192        );
1193    }
1194
1195    #[test]
1196    fn exec_escaping_covers_the_desktop_entry_grammar() {
1197        // Every one of these is legal in a Unix path and each changes how the
1198        // Exec value tokenizes if left raw.
1199        let d = xdg_desktop_entry(Path::new(r#"/opt/a"b\c`d$e%f/agentmux"#), "test");
1200        assert!(d.contains(r#"\"b"#), "quote must be escaped, not end the argument");
1201        assert!(d.contains(r"\\c"), "backslash must be escaped");
1202        assert!(d.contains(r"\`d"), "backtick must be escaped");
1203        assert!(d.contains(r"\$e"), "dollar must be escaped");
1204        assert!(d.contains("%%f"), "percent must be doubled or it reads as a field code");
1205    }
1206
1207    #[test]
1208    fn every_platform_artifact_launches_with_the_background_flag() {
1209        // All three must start the app in background mode; a plain launch
1210        // would pop a window in the user's face at every login, which is the
1211        // opposite of what auto-start is for.
1212        assert!(scheduled_task_xml(&exe(), "test").contains("--background"));
1213        assert!(launch_agent_plist(&exe(), "test").contains("<string>--background</string>"));
1214        assert!(xdg_desktop_entry(&exe(), "test").contains("--background"));
1215    }
1216
1217    // ── SPEC_START_WITH_OS_2026_09_25 ─────────────────────────────────────
1218
1219    #[test]
1220    fn a_login_start_that_finds_agentmux_running_opens_no_window() {
1221        let manual = vec!["agentmux".to_string()];
1222        let login = vec!["agentmux".to_string(), BACKGROUND_FLAG.to_string()];
1223        assert!(second_instance_opens_window(&manual));
1224        assert!(!second_instance_opens_window(&login));
1225    }
1226
1227    fn entry(target: &str, channel: Option<&str>) -> Entry {
1228        Entry { target: Some(target.to_string()), channel: channel.map(str::to_string), current: true }
1229    }
1230
1231    /// An uninstaller removes the entry that runs from its own folder, and nothing else.
1232    #[test]
1233    fn an_uninstall_removes_only_an_entry_that_runs_from_its_own_folder() {
1234        let (dir, ours, other) = if cfg!(target_os = "windows") {
1235            (
1236                r"C:\Users\a\AppData\Local\Programs\AgentMux",
1237                r"C:\Users\a\AppData\Local\Programs\AgentMux\agentmux.exe",
1238                r"C:\dev\agentmux\agentmux.exe",
1239            )
1240        } else {
1241            ("/opt/agentmux", "/opt/agentmux/agentmux", "/home/a/dev/agentmux/agentmux")
1242        };
1243        assert!(entry_runs_from(&entry(ours, Some("stable")), Path::new(dir)));
1244        // Another build's entry stays, whoever owns it.
1245        assert!(!entry_runs_from(&entry(other, Some("stable")), Path::new(dir)));
1246        // A folder whose name only starts the same is not inside it.
1247        let sibling = format!("{}-dev{}agentmux.exe", dir, std::path::MAIN_SEPARATOR);
1248        assert!(!entry_runs_from(&entry(&sibling, None), Path::new(dir)));
1249        // No target, or no folder: nothing to remove.
1250        assert!(!entry_runs_from(&Entry { target: None, channel: None, current: true }, Path::new(dir)));
1251        assert!(!entry_runs_from(&entry(ours, None), Path::new("")));
1252    }
1253
1254    #[cfg(target_os = "windows")]
1255    #[test]
1256    fn windows_paths_compare_without_case_or_slash_direction() {
1257        let e = entry(r"c:\users\a\appdata\local\programs\agentmux\AGENTMUX.EXE", None);
1258        assert!(entry_runs_from(&e, Path::new("C:/Users/A/AppData/Local/Programs/AgentMux/")));
1259    }
1260
1261    #[test]
1262    fn plan_on_writes_unless_the_entry_is_already_ours_and_current() {
1263        let t = "/home/u/Desktop/AgentMux.AppImage";
1264        assert_eq!(plan(Some(true), None, "stable", Some(t)), Plan::Write);
1265        assert_eq!(plan(Some(true), Some(&entry(t, Some("stable"))), "stable", Some(t)), Plan::Nothing);
1266        // An update or a move: same owner, old path.
1267        assert_eq!(plan(Some(true), Some(&entry("/old/path", Some("stable"))), "stable", Some(t)), Plan::Write);
1268        // Another build's entry: turning it on here takes it over.
1269        assert_eq!(plan(Some(true), Some(&entry(t, Some("local-main-x"))), "stable", Some(t)), Plan::Write);
1270    }
1271
1272    #[test]
1273    fn plan_off_removes_only_this_channels_entry() {
1274        let t = "/opt/agentmux/agentmux";
1275        assert_eq!(plan(Some(false), Some(&entry(t, Some("stable"))), "stable", Some(t)), Plan::Remove);
1276        assert_eq!(plan(Some(false), Some(&entry(t, Some("local-main-x"))), "stable", Some(t)), Plan::Nothing);
1277        assert_eq!(plan(Some(false), Some(&entry(t, None)), "stable", Some(t)), Plan::Nothing);
1278        assert_eq!(plan(Some(false), None, "stable", Some(t)), Plan::Nothing);
1279    }
1280
1281    /// ReAgent P1 on #3788: an unresolvable target must not block turning it off.
1282    #[test]
1283    fn plan_needs_the_target_only_to_write() {
1284        let mine = entry("/x", Some("stable"));
1285        assert_eq!(plan(Some(false), Some(&mine), "stable", None), Plan::Remove);
1286        assert_eq!(plan(None, Some(&entry("/x", None)), "stable", None), Plan::Adopt);
1287        // On with no target: still a write, which then reports the missing target.
1288        assert_eq!(plan(Some(true), Some(&mine), "stable", None), Plan::Write);
1289    }
1290
1291    /// Off by default, but a user who turned it on with the old toggle keeps it.
1292    #[test]
1293    fn plan_never_set_is_off_but_adopts_an_entry_from_before_the_setting() {
1294        let t = "/x";
1295        assert_eq!(plan(None, None, "stable", Some(t)), Plan::Nothing);
1296        assert_eq!(plan(None, Some(&entry(t, None)), "stable", Some(t)), Plan::Adopt);
1297        assert_eq!(plan(None, Some(&entry(t, Some("local-main-x"))), "stable", Some(t)), Plan::Nothing);
1298    }
1299
1300    #[test]
1301    fn every_artifact_reads_back_its_own_target_and_channel() {
1302        let exe = Path::new("/home/u/My Apps/Agent&Mux.AppImage");
1303        let want = Entry { target: Some(exe.display().to_string()), channel: Some("local-main-b28b7a".into()), current: true };
1304        assert_eq!(parse_desktop_entry(&xdg_desktop_entry(exe, "local-main-b28b7a")), want);
1305        assert_eq!(parse_plist(&launch_agent_plist(exe, "local-main-b28b7a")), want);
1306        let win = Path::new(r"C:\Users\u\AppData\Local\Programs\AgentMux & Co\agentmux.exe");
1307        assert_eq!(
1308            parse_task_xml(&scheduled_task_xml(win, "stable")),
1309            Entry { target: Some(win.display().to_string()), channel: Some("stable".into()), current: true }
1310        );
1311    }
1312
1313    /// An entry written before ownership existed has no channel and no TryExec.
1314    #[test]
1315    fn a_pre_ownership_desktop_entry_reads_as_unowned_with_no_target() {
1316        let old = "[Desktop Entry]\nType=Application\nExec=\"/x/agentmux-launcher\" --background\n";
1317        assert_eq!(parse_desktop_entry(old), Entry { target: None, channel: None, current: true });
1318    }
1319
1320    #[test]
1321    fn the_desktop_entry_goes_inert_without_its_target_and_waits_for_the_session() {
1322        let d = xdg_desktop_entry(Path::new("/opt/agentmux/agentmux"), "stable");
1323        assert!(d.contains("\nTryExec=/opt/agentmux/agentmux\n"), "{d}");
1324        assert!(d.contains("\nX-GNOME-Autostart-Delay=10\n"), "{d}");
1325        assert!(d.contains("\nX-AgentMux-Channel=stable\n"), "{d}");
1326    }
1327
1328    #[test]
1329    fn a_login_entry_follows_its_file_when_the_file_is_moved_or_renamed_whichever_channel_wrote_it() {
1330        let old = "/home/user/Desktop/AgentMux_0.60.29_amd64.AppImage";
1331        let new = "/home/user/Applications/AgentMux_0.60.29_amd64_9f8e7d.AppImage";
1332        let moved = |setting, entry: &Entry, channel| super::plan(setting, Some(entry), channel, Some(new), Some(old));
1333        // The channel that wrote the entry runs the file: its own setting rewrites it (as before).
1334        assert_eq!(moved(Some(true), &entry(old, Some("local-x")), "local-x"), Plan::Write);
1335        // Another channel is running the moved file, or this channel's setting is off or never set: the entry
1336        // still follows the file.
1337        for setting in [Some(true), Some(false), None] {
1338            assert_eq!(moved(setting, &entry(old, Some("local-x")), "stable"), if setting == Some(true) { Plan::Write } else { Plan::Repoint }, "{setting:?}");
1339        }
1340        // Only an entry that runs this very file's old path follows it.
1341        assert_eq!(moved(Some(false), &entry("/opt/other/agentmux", Some("local-x")), "stable"), Plan::Nothing);
1342        // Already pointing at the file: nothing to do. Nothing moved: nothing to follow.
1343        assert_eq!(moved(Some(false), &entry(new, Some("local-x")), "stable"), Plan::Nothing);
1344        assert_eq!(super::plan(Some(false), Some(&entry(old, Some("local-x"))), "stable", Some(new), None), Plan::Nothing);
1345        // No target to point it at: no repoint.
1346        assert_eq!(super::plan(Some(false), Some(&entry(old, Some("local-x"))), "stable", None, Some(old)), Plan::Nothing);
1347    }
1348
1349    #[test]
1350    fn status_says_off_on_or_broken_and_who_owns_the_entry() {
1351        let dir = tempfile::tempdir().unwrap();
1352        let there = dir.path().join("AgentMux.AppImage");
1353        std::fs::write(&there, b"x").unwrap();
1354        let there = there.display().to_string();
1355        let gone = dir.path().join("Gone.AppImage").display().to_string();
1356
1357        let none = status(None, false, "stable", true);
1358        assert_eq!((none.state, none.movable, none.owner_channel.as_deref(), none.target.as_deref()), (State::Off, false, None, None));
1359
1360        let ours = status(Some(&entry(&there, Some("stable"))), true, "stable", true);
1361        assert_eq!((ours.state, ours.movable, ours.owner_channel.as_deref()), (State::On, false, Some("stable")));
1362        assert_eq!(ours.target.as_deref(), Some(there.as_str()));
1363
1364        let broken = status(Some(&entry(&gone, Some("stable"))), true, "stable", true);
1365        assert_eq!((broken.state, broken.movable), (State::Broken, false), "ours but its file is gone: Repair, not a move");
1366
1367        let theirs = status(Some(&entry(&there, Some("local-x"))), true, "stable", true);
1368        assert_eq!((theirs.state, theirs.movable, theirs.owner_channel.as_deref()), (State::On, true, Some("local-x")));
1369        assert!(!status(Some(&entry(&there, Some("local-x"))), true, "stable", false).movable, "no target to point it at: not movable");
1370
1371        let unowned = status(Some(&entry(&there, None)), true, "stable", true);
1372        assert_eq!((unowned.state, unowned.movable, unowned.owner_channel), (State::On, true, None), "from before ownership was recorded");
1373
1374        let unreadable = status(None, true, "stable", true);
1375        assert_eq!((unreadable.state, unreadable.movable), (State::On, false), "registered but unparsed still starts something at login");
1376    }
1377
1378    #[test]
1379    fn status_json_has_the_keys_settings_reads() {
1380        let s = status(Some(&entry("/x/AgentMux.AppImage", Some("local-x"))), true, "stable", true);
1381        let v: serde_json::Value = serde_json::to_value(&s).unwrap();
1382        assert_eq!(
1383            v,
1384            serde_json::json!({ "state": "broken", "target": "/x/AgentMux.AppImage", "owner_channel": "local-x", "this_channel": "stable", "movable": true })
1385        );
1386        assert_eq!(serde_json::to_value(State::NeedsApproval).unwrap(), "needs_approval");
1387    }
1388
1389    #[test]
1390    fn a_login_entry_that_runs_a_file_that_is_gone_is_noticed() {
1391        let dir = tempfile::tempdir().unwrap();
1392        let there = dir.path().join("AgentMux.AppImage");
1393        std::fs::write(&there, b"x").unwrap();
1394        let gone = dir.path().join("Desktop").join("AgentMux.AppImage");
1395        assert_eq!(missing_target(&entry(&there.display().to_string(), Some("stable"))), None);
1396        let gone_text = gone.display().to_string();
1397        assert_eq!(missing_target(&entry(&gone_text, Some("local-x"))), Some(gone_text.as_str()));
1398        assert_eq!(missing_target(&Entry { target: None, channel: None, current: true }), None, "an entry with no target is rewritten, not reported");
1399    }
1400
1401    #[test]
1402    fn the_login_entry_runs_an_appimage_with_appimagelauncher_switched_off_and_nothing_else_that_way() {
1403        let image = xdg_desktop_entry(Path::new("/home/user/Applications/AgentMux_0.60.29_amd64_9f8e7d.AppImage"), "stable");
1404        assert!(
1405            image.contains("\nExec=env APPIMAGELAUNCHER_DISABLE=1 \"/home/user/Applications/AgentMux_0.60.29_amd64_9f8e7d.AppImage\" --background\n"),
1406            "{image}"
1407        );
1408        // The program the entry is read back from is still the file, not `env`.
1409        assert_eq!(parse_desktop_entry(&image).target.as_deref(), Some("/home/user/Applications/AgentMux_0.60.29_amd64_9f8e7d.AppImage"));
1410        // Another extension's case doesn't matter; a package install's wrapper is run directly.
1411        assert!(xdg_desktop_entry(Path::new("/home/user/a.appimage"), "stable").contains("Exec=env APPIMAGELAUNCHER_DISABLE=1 "));
1412        let wrapper = xdg_desktop_entry(Path::new("/usr/bin/agentmux"), "stable");
1413        assert!(wrapper.contains("\nExec=\"/usr/bin/agentmux\" --background\n"), "{wrapper}");
1414    }
1415
1416    #[test]
1417    fn an_appimage_login_entry_from_before_the_bypass_is_rewritten_even_when_it_runs_the_right_file() {
1418        let file = "/home/user/Applications/AgentMux_0.60.30_amd64.AppImage";
1419        let old = format!(
1420            "[Desktop Entry]\nType=Application\nTryExec={file}\nExec=\"{file}\" --background\nX-AgentMux-Channel=stable\n"
1421        );
1422        let read = parse_desktop_entry(&old);
1423        assert_eq!(read.target.as_deref(), Some(file));
1424        assert!(!read.current, "an AppImage entry that starts it with AppImageLauncher on");
1425        assert_eq!(plan(Some(true), Some(&read), "stable", Some(file)), Plan::Write);
1426        // What this build writes reads back as current and is left alone.
1427        let new = parse_desktop_entry(&xdg_desktop_entry(Path::new(file), "stable"));
1428        assert!(new.current);
1429        assert_eq!(plan(Some(true), Some(&new), "stable", Some(file)), Plan::Nothing);
1430        // A package install's wrapper never had the bypass and is current without it.
1431        assert!(parse_desktop_entry(&xdg_desktop_entry(Path::new("/usr/bin/agentmux"), "stable")).current);
1432    }
1433
1434    #[test]
1435    fn try_exec_cannot_be_used_to_inject_keys() {
1436        let d = xdg_desktop_entry(Path::new("/opt/x\nHidden=true"), "stable");
1437        assert!(!d.lines().any(|l| l == "Hidden=true"), "{d}");
1438    }
1439
1440    #[test]
1441    fn schtasks_utf16_output_is_decoded() {
1442        let mut bytes = vec![0xFF, 0xFE];
1443        for u in "<Command>\"C:\\a.exe\"</Command>".encode_utf16() {
1444            bytes.extend_from_slice(&u.to_le_bytes());
1445        }
1446        assert_eq!(decode_console_output(&bytes), "<Command>\"C:\\a.exe\"</Command>");
1447        assert_eq!(decode_console_output(b"plain"), "plain");
1448    }
1449
1450    #[test]
1451    fn the_stable_target_prefers_the_wrapper_path_then_this_exe() {
1452        let dir = std::env::temp_dir().join(format!("agentmux-stable-{}", std::process::id()));
1453        std::fs::create_dir_all(&dir).unwrap();
1454        let wrapper = dir.join("agentmux");
1455        std::fs::write(&wrapper, "").unwrap();
1456        let cur = || Ok(PathBuf::from("/cache/agentmux-launcher"));
1457
1458        assert_eq!(stable_target_from(Some(wrapper.clone().into()), cur()), Ok(wrapper.clone()));
1459        // A value pointing nowhere is skipped, not written.
1460        assert_eq!(stable_target_from(Some(dir.join("gone").into()), cur()), cur());
1461        assert_eq!(stable_target_from(None, cur()), cur());
1462        let _ = std::fs::remove_dir_all(&dir);
1463    }
1464}