Skip to main content

agentmux_launcher/
host_spawn.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::logging::log;
5
6/// Background mode without a tray icon is a resident process nobody can see
7/// or quit. When the tray was requested but failed to start, take both
8/// switches back out of the host's environment, whether they came from the
9/// launcher's own env (the setting) or from `--background`. Must run after
10/// every `.env`/`.envs` that could set them: later `Command` env calls win.
11fn drop_background_if_no_tray(cmd: &mut tokio::process::Command, tray_unavailable: bool) {
12    if tray_unavailable {
13        cmd.env_remove("AGENTMUX_BACKGROUND_SERVICE").env_remove("AGENTMUX_TRAY");
14    }
15}
16
17/// Tell the host to hold its "main" window hidden, or make sure it is not
18/// told so by an inherited env.
19fn set_start_hidden(cmd: &mut tokio::process::Command) {
20    if start_hidden(crate::autostart::login_start(), crate::tray::unavailable()) {
21        cmd.env("AGENTMUX_START_HIDDEN", "1");
22    } else {
23        cmd.env_remove("AGENTMUX_START_HIDDEN");
24    }
25}
26
27/// What this launch asks of the host it starts: to start hidden, and the deep link it was started with.
28fn set_launch_env(cmd: &mut tokio::process::Command) {
29    set_start_hidden(cmd);
30    crate::launch_link::set_host_env(cmd);
31}
32
33/// Set once the first host has been spawned, hidden or not.
34static FIRST_HOST_SPAWNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
35
36/// Should this host hold its "main" window hidden
37/// (`SPEC_START_WITH_OS_2026_09_25.md` §3.3)? Only for a login start, only when
38/// the tray is up (no tray means a normal window, never an invisible process),
39/// and only for the first host: a host restarted after a crash must come back
40/// visible, since the user may already have been using it.
41fn start_hidden(login_start: bool, tray_unavailable: bool) -> bool {
42    let first = !FIRST_HOST_SPAWNED.swap(true, std::sync::atomic::Ordering::SeqCst);
43    start_hidden_decision(login_start, tray_unavailable, first)
44}
45
46fn start_hidden_decision(login_start: bool, tray_unavailable: bool, first_host: bool) -> bool {
47    login_start && !tray_unavailable && first_host
48}
49
50/// Spawn the CEF host suspended, assign it to the launcher's Job Object, and
51/// resume it. Returns the running child, or `None` if any step failed — the
52/// caller decides (fatal on first launch, give-up on a restart). `splash_event`
53/// is passed on every launch — including restarts — so a relaunched host can
54/// still dismiss a splash left pending by a host that crashed pre-first-frame.
55/// `disable_gpu` is the retry ladder's rung-2 degraded mode (spec §7): when set
56/// the host is launched with `--disable-gpu` (software rendering).
57#[cfg(target_os = "windows")]
58pub(crate) fn spawn_host_supervised(
59    real_exe: &std::path::Path,
60    args: &[String],
61    srv: &crate::srv_spawner::SrvSpawnResult,
62    host_env: &[(&'static str, std::ffi::OsString)],
63    pipe_path: &str,
64    job_present: bool,
65    job_handle: windows_sys::Win32::Foundation::HANDLE,
66    splash_event: Option<&str>,
67    disable_gpu: bool,
68) -> Option<tokio::process::Child> {
69    use windows_sys::Win32::System::Threading::CREATE_SUSPENDED;
70
71    // The launcher's resolved `real_exe` lives in `runtime/`; pass its
72    // parent dir as AGENTMUX_HOME so the host can anchor asset lookups
73    // (frontend/index.html, etc.) on something stable rather than
74    // `std::env::current_exe()`. Windows's GetModuleFileName keeps
75    // returning the original load-time path even after the parent dir
76    // is renamed or unlinked out from under it — the 2026-05-28
77    // incident pattern. AGENTMUX_HOME is whatever path *we* (the
78    // launcher) successfully resolved real_exe through, so it always
79    // points at the runtime dir that actually contains the binaries.
80    // See docs/retro/retro-portable-rm-running-install-2026-05-28.md.
81    let host_runtime_dir = real_exe.parent().map(|p| p.to_path_buf());
82
83    let mut host_cmd = tokio::process::Command::new(real_exe);
84    host_cmd
85        .args(args)
86        .env("AGENTMUX_BACKEND_WS", &srv.ws_endpoint)
87        .env("AGENTMUX_BACKEND_WEB", &srv.web_endpoint)
88        .env("AGENTMUX_BACKEND_PID", srv.pid.to_string())
89        .env("AGENTMUX_PENDING_MIGRATIONS", srv.pending_migrations.to_string())
90        .env("AGENTMUX_AUTH_KEY", &srv.auth_key)
91        .env("AGENTMUX_HOST_REG_SECRET", &srv.host_reg_secret)
92        .env("AGENTMUX_INSTANCE_ID", &srv.instance_id)
93        // Parent-identity stamp, as on Unix: lets a dev-build host verify
94        // this hand-off is from its real parent THIS run and adopt our srv.
95        // Without it a Windows `task dev` host ignored the env hand-off and
96        // spawned a second srv on the same data dir (#3868 follow-up). See
97        // crates/cef/src/lib.rs::launcher_is_genuine_parent.
98        .env("AGENTMUX_LAUNCHER_PID", std::process::id().to_string())
99        // This launcher quits the host over the host pipe (host_quit.rs): the host
100        // then refuses `quit_app` on the port-file token.
101        .env("AGENTMUX_LAUNCHER_QUIT_PIPE", "1")
102        .envs(host_env.iter().cloned())
103        // Auto-start (issue #2977 WS2): translate the launcher's own
104        // `--background` flag into the env the HOST actually reads. The flag
105        // is forwarded to the host in `args` too, but nothing there consumes
106        // it — `AGENTMUX_BACKGROUND_SERVICE` is the real switch, so without
107        // this an auto-started instance would open a normal foreground window
108        // and still quit on last-window-close (Codex P1 on PR #2999).
109        // `background_env_for` also sets `AGENTMUX_TRAY`; see its doc for why
110        // the indicator is not optional in this particular context.
111        .envs(crate::autostart::background_env_for(args))
112        // Lets the host run launcher CLI verbs (`--autostart-status` etc.)
113        // for the Settings UI. SPEC_OS_NOTIFICATIONS_SYSTEM_2026_09_24.md §4.1.
114        .envs(launcher_exe_env())
115        .env("AGENTMUX_LAUNCHER_PIPE", pipe_path)
116        // Explicit stdio instead of inheriting the launcher's own —
117        // `CreateProcess(..., CREATE_SUSPENDED, ...)` for this GUI-subsystem
118        // target fails outright with ERROR_NOT_SUPPORTED (os error 50) when
119        // it inherits stdio handles that trace back through an MSYS/Git-Bash
120        // process chain (e.g. this launcher itself spawned from an agent's
121        // own Bash tool call) — confirmed by direct experiment: the same
122        // binary starts cleanly when given real Win32 file handles instead
123        // of inherited MSYS ones. `Stdio::null()`, not `::piped()`: the host
124        // has no stdout/stderr protocol the launcher parses (contrast
125        // `srv_spawner`'s piped handles, which ARE consumed — the ESTART
126        // readiness signal and log forwarding) — piping without ever
127        // reading would risk a silent hang if the host wrote enough output
128        // to fill the pipe buffer. See docs/retro/retro-cef-host-spawn-
129        // fails-under-inherited-nonstandard-stdio-2026-08-17.md.
130        .stdin(std::process::Stdio::null())
131        .stdout(std::process::Stdio::null())
132        .stderr(std::process::Stdio::null())
133        .creation_flags(CREATE_SUSPENDED)
134        .kill_on_drop(false); // J0 handles cleanup.
135    drop_background_if_no_tray(&mut host_cmd, crate::tray::unavailable());
136    set_launch_env(&mut host_cmd);
137    if let Some(dir) = host_runtime_dir {
138        host_cmd.env("AGENTMUX_HOME", dir);
139    }
140    if let Some(name) = splash_event {
141        host_cmd.env("AGENTMUX_SPLASH_EVENT", name);
142    }
143    // Retry-ladder rung 2 (spec §7): software rendering — no GPU process to
144    // crash. A Chromium switch the host forwards to CEF.
145    if disable_gpu {
146        host_cmd.arg("--disable-gpu");
147    }
148
149    let mut host_child = match host_cmd.spawn() {
150        Ok(c) => c,
151        Err(e) => {
152            log(&format!("failed to spawn CEF host: {}", e));
153            return None;
154        }
155    };
156    let host_pid = host_child.id().unwrap_or(0);
157    log(&format!("spawned CEF host pid={} (suspended)", host_pid));
158
159    // Assign to J0 BEFORE resuming so CEF render children inherit the job.
160    if job_present && host_pid != 0 {
161        match crate::srv_spawner::assign_pid_to_job(host_pid, job_handle) {
162            Ok(()) => log(&format!(
163                "Job Object assigned to host pid={}, KILL_ON_JOB_CLOSE active",
164                host_pid
165            )),
166            Err(e) => log(&format!(
167                "WARN: AssignProcessToJobObject(host) failed: {} — host children may escape job",
168                e
169            )),
170        }
171    }
172
173    // Resume the suspended main thread.
174    if let Err(e) = agentmux_common::win32::resume_main_thread(host_pid) {
175        log(&format!("failed to resume host pid={}: {}", host_pid, e));
176        let _ = host_child.start_kill();
177        return None;
178    }
179    Some(host_child)
180}
181
182/// Spawn the CEF host on Unix with the srv endpoints + canonical
183/// data-dir env handed off, mirroring `spawn_host_supervised` minus the
184/// Windows-only machinery (Job Object assignment, CREATE_SUSPENDED /
185/// resume, named-pipe handle, splash event). `disable_gpu` is the retry
186/// ladder's degraded rung (software rendering). Returns the running
187/// child or `None` if spawn failed.
188///
189/// AGENTMUX_HOME is intentionally NOT set: on the flat dev layout the
190/// host's `current_exe().parent()` fallback resolves to the same dir the
191/// launcher would export, so omitting it keeps asset + framework lookup
192/// byte-identical to the legacy direct-invoke (`task dev:standalone`)
193/// path. Phase 2 will set it once the production runtime/ layout lands
194/// on macOS.
195#[cfg(not(target_os = "windows"))]
196pub(crate) fn spawn_host_unix(
197    real_exe: &std::path::Path,
198    args: &[String],
199    srv: &crate::srv_spawner::SrvSpawnResult,
200    host_env: &[(&'static str, std::ffi::OsString)],
201    disable_gpu: bool,
202) -> Option<tokio::process::Child> {
203    let mut host_cmd = tokio::process::Command::new(real_exe);
204    host_cmd
205        .args(args)
206        .env("AGENTMUX_BACKEND_WS", &srv.ws_endpoint)
207        .env("AGENTMUX_BACKEND_WEB", &srv.web_endpoint)
208        .env("AGENTMUX_BACKEND_PID", srv.pid.to_string())
209        .env("AGENTMUX_PENDING_MIGRATIONS", srv.pending_migrations.to_string())
210        .env("AGENTMUX_AUTH_KEY", &srv.auth_key)
211        .env("AGENTMUX_HOST_REG_SECRET", &srv.host_reg_secret)
212        .env("AGENTMUX_INSTANCE_ID", &srv.instance_id)
213        // Parent-identity stamp: our pid == the host's getppid (we spawn it
214        // directly). A dev-build host normally ignores AGENTMUX_BACKEND_WS
215        // (it could be a stale value inherited from a parent agentmux pane);
216        // this lets the host verify the hand-off is genuinely ours THIS run
217        // and adopt our launcher-owned srv instead of double-spawning. See
218        // crates/cef/src/main.rs::launcher_is_genuine_parent.
219        .env("AGENTMUX_LAUNCHER_PID", std::process::id().to_string())
220        // This launcher quits the host over the host pipe (host_quit.rs): the host
221        // then refuses `quit_app` on the port-file token.
222        .env("AGENTMUX_LAUNCHER_QUIT_PIPE", "1")
223        .envs(host_env.iter().cloned())
224        // Auto-start (issue #2977 WS2) — same translation as the Windows
225        // spawn path. macOS and Linux are the platforms whose generated
226        // artifacts (LaunchAgent, XDG .desktop) actually pass `--background`,
227        // so omitting it here left two of the three shipped platforms with an
228        // inert flag (ReAgent P1 on PR #2999, catching that my first fix for
229        // this was wired into the Windows spawn only).
230        .envs(crate::autostart::background_env_for(args))
231        // Lets the host run launcher CLI verbs (`--autostart-status` etc.)
232        // for the Settings UI. SPEC_OS_NOTIFICATIONS_SYSTEM_2026_09_24.md §4.1.
233        .envs(launcher_exe_env())
234        // We reap children ourselves on shutdown (SIGTERM, then SIGKILL
235        // backstop) — kill_on_drop would SIGKILL the host the moment the
236        // Child is dropped, robbing CEF of the chance to reap its render
237        // subprocesses cleanly.
238        .kill_on_drop(false)
239        // SPEC_LAUNCHER_TEARDOWN_BACKSTOP_2026_07_11 unix parity — make the
240        // host its own process-group leader (pgid == its own pid) instead of
241        // inheriting the launcher's group. This is the prerequisite for
242        // `kill_process_group_forcefully`'s `kill(-pgid, SIGKILL)`: without
243        // an explicit group, the host and any CEF subprocesses it forks
244        // (renderer/GPU/zygote) sit in the launcher's OWN group, and a
245        // group-kill from the teardown backstop would take the launcher
246        // down with it mid-cleanup. Scoped exactly to what this call spawns
247        // — the same blast-radius bound Windows gets for free from owning
248        // its Job Object.
249        .process_group(0);
250    drop_background_if_no_tray(&mut host_cmd, crate::tray::unavailable());
251    set_launch_env(&mut host_cmd);
252    if disable_gpu {
253        host_cmd.arg("--disable-gpu");
254    }
255    // Linux process-tree reap: PR_SET_PDEATHSIG asks the kernel to SIGKILL
256    // this child the moment its parent (the launcher) dies, even abnormally
257    // (e.g. launcher panic, OOM, SIGKILL from outside). This is the Linux
258    // analogue of Windows' Job Object KILL_ON_JOB_CLOSE that A0 wires up
259    // (SPEC_LAUNCHER_LINUX_PACKAGED_AND_SPLASH_2026_06_05 §3 step 3 and
260    // §A1.4). Without it, a launcher crash orphans the CEF host onto PID 1
261    // and the user is left with a zombie tree until manual cleanup.
262    //
263    // The closure runs between fork() and execve() in the child; per
264    // POSIX it MUST NOT allocate, take locks, or call async-signal-unsafe
265    // functions. `prctl(2)` is async-signal-safe. macOS lacks prctl, so
266    // this is gated to Linux; macOS uses NSTask's auto-reap behavior.
267    #[cfg(target_os = "linux")]
268    {
269        // Safety: prctl is async-signal-safe. No allocation, no syscalls
270        // beyond prctl itself. Errors from prctl are non-fatal — the host
271        // still spawns; we just lose the auto-reap guarantee.
272        unsafe {
273            host_cmd.pre_exec(|| {
274                libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL, 0, 0, 0);
275                Ok(())
276            });
277        }
278    }
279    match host_cmd.spawn() {
280        Ok(c) => {
281            let pid = c.id().unwrap_or(0);
282            log(&format!("spawned CEF host pid={} (unix)", pid));
283            Some(c)
284        }
285        Err(e) => {
286            log(&format!("failed to spawn CEF host: {}", e));
287            None
288        }
289    }
290}
291
292/// Send SIGTERM to a child so it can shut down gracefully — for the CEF
293/// host that means reaping its render subprocesses (a tokio `start_kill`
294/// SIGKILL would orphan them); for srv it's a clean shutdown. No-op if the
295/// child has already exited (its pid may have been reaped). Best-effort:
296/// the SIGKILL grace-window backstop in `run_unix` catches anything that
297/// ignores SIGTERM.
298#[cfg(not(target_os = "windows"))]
299pub(crate) fn terminate_child_gracefully(child: &tokio::process::Child) {
300    if let Some(pid) = child.id() {
301        // SAFETY: kill(2) with a process-scoped pid + a constant signal —
302        // no memory is touched. A stale pid just returns ESRCH (ignored).
303        unsafe {
304            libc::kill(pid as libc::pid_t, libc::SIGTERM);
305        }
306    }
307}
308
309/// Send `signal` to an entire process group in one shot (negated pid — see
310/// the two public wrappers below for why this targets a whole group, not
311/// just one process). Shared by both so the return-value handling — a
312/// silently-ignored failure would otherwise let a genuinely-failed kill
313/// (anything but the expected "already empty" ESRCH) read as a successful
314/// teardown — lives in exactly one place. Logs on any failure OTHER than
315/// ESRCH (the routine no-op case: the group was already empty, e.g. a prior
316/// SIGTERM's own graceful shutdown already reaped it).
317#[cfg(not(target_os = "windows"))]
318fn kill_process_group(child: &tokio::process::Child, signal: libc::c_int, signal_name: &str) {
319    if let Some(pid) = child.id() {
320        kill_group(pid, signal, signal_name);
321    }
322}
323
324/// The signal itself goes through `agentmux_common::process::signal_process_group`,
325/// which refuses a pgid of 0 or 1 (the launcher's own group, or the
326/// broadcast) rather than signalling it.
327#[cfg(not(target_os = "windows"))]
328fn kill_group(pid: u32, signal: libc::c_int, signal_name: &str) {
329    if let Err(err) = agentmux_common::process::signal_process_group(pid, signal) {
330        if err.raw_os_error() != Some(libc::ESRCH) {
331            crate::logging::log(&format!(
332                "WARN: kill(-{}, {}) failed: {}",
333                pid, signal_name, err
334            ));
335        }
336    }
337}
338
339/// SIGTERM an entire process group, before the harder
340/// `kill_process_group_forcefully` follows. The teardown backstop uses it
341/// on the host's group; srv is never group-signalled first, since its own
342/// SIGTERM/stdin-EOF shutdown closes its agents (`upgrade::quiesce_srv`).
343#[cfg(not(target_os = "windows"))]
344pub(crate) fn kill_process_group_gracefully(child: &tokio::process::Child) {
345    kill_process_group(child, libc::SIGTERM, "SIGTERM");
346}
347
348/// SIGKILL an entire process group in one shot — the unix analogue of
349/// Windows' `TerminateJobObject`. `child` must have been spawned with
350/// `.process_group(0)` (both `spawn_host_unix` and `srv_spawner::spawn_srv`
351/// do this) so its pgid equals its own pid; negating the pid targets the
352/// whole group instead of just the one process, reaping any descendants
353/// (e.g. CEF's forked renderer/GPU subprocesses) the launcher never tracks
354/// individually. Used by the teardown backstop
355/// (SPEC_LAUNCHER_TEARDOWN_BACKSTOP_2026_07_11) as the hard backstop after
356/// `kill_process_group_gracefully`'s brief grace window — reserved for
357/// whatever a graceful SIGTERM didn't reap (a wedged-or-dead srv, or shells
358/// its own `stop_all()` couldn't finish in time). No-op if the child has
359/// already exited (its pid may have been reaped; a stale pid's negated kill
360/// returns ESRCH, ignored).
361#[cfg(not(target_os = "windows"))]
362pub(crate) fn kill_process_group_forcefully(child: &tokio::process::Child) {
363    kill_process_group(child, libc::SIGKILL, "SIGKILL");
364}
365
366#[cfg(all(test, not(target_os = "windows")))]
367mod tests {
368    //! `kill_process_group_forcefully` and the `.process_group(0)` calls in
369    //! this file / `srv_spawner.rs` are the prerequisite the SPEC_LAUNCHER_
370    //! TEARDOWN_BACKSTOP_2026_07_11 unix teardown backstop depends on — a
371    //! survey ahead of this change (issue #2188) confirmed NO unix child of
372    //! the launcher was ever placed in its own process group, so
373    //! `kill(-pgid, SIGKILL)` had no safe target. These exercise the two
374    //! real invariants against actually-spawned processes rather than
375    //! asserting on the builder call alone, since a wrong signature (e.g.
376    //! `.process_group(pid)` instead of `.process_group(0)`) would compile
377    //! fine and silently fail to create a new group.
378
379    use super::{kill_process_group_forcefully, kill_process_group_gracefully};
380
381    /// `.process_group(0)` makes the spawned child its own group leader —
382    /// pgid must equal its own pid, not the test process's pgid.
383    #[tokio::test]
384    async fn process_group_zero_makes_the_child_its_own_group_leader() {
385        let mut cmd = tokio::process::Command::new("sleep");
386        cmd.arg("5").kill_on_drop(true).process_group(0);
387        let mut child = cmd.spawn().expect("spawn sleep");
388        let pid = child.id().expect("child has a pid") as libc::pid_t;
389
390        // SAFETY: getpgid with process-scoped pids; no memory touched.
391        let pgid = unsafe { libc::getpgid(pid) };
392        let our_pgid = unsafe { libc::getpgid(0) };
393        assert_eq!(pgid, pid, "process_group(0) must make pgid == pid");
394        // The behavioral half of the invariant (reagent P1, PR #2200): the
395        // child must NOT be in our own group, since that's exactly what
396        // makes it stop receiving a group-directed signal (e.g. a terminal
397        // Ctrl+C, which the shell delivers to its whole foreground group) —
398        // the tradeoff this change makes host/srv exit via the launcher's
399        // explicit terminate_child_gracefully instead of direct propagation.
400        assert_ne!(
401            pgid, our_pgid,
402            "process_group(0) must isolate the child from our own group, \
403             or a group-directed signal (e.g. terminal Ctrl+C) would still reach it"
404        );
405
406        let _ = child.kill().await;
407    }
408
409    /// The kill actually reaches the process (signal-terminated, not a
410    /// silent no-op) — the behavioral half of the prerequisite, mirroring
411    /// what the teardown backstop's live-fire path depends on.
412    #[tokio::test]
413    async fn kill_process_group_forcefully_terminates_a_real_child() {
414        use std::os::unix::process::ExitStatusExt;
415
416        let mut cmd = tokio::process::Command::new("sleep");
417        cmd.arg("5").kill_on_drop(false).process_group(0);
418        let mut child = cmd.spawn().expect("spawn sleep");
419
420        kill_process_group_forcefully(&child);
421
422        let status = tokio::time::timeout(std::time::Duration::from_secs(2), child.wait())
423            .await
424            .expect("child did not exit after group kill")
425            .expect("wait succeeded");
426        assert_eq!(status.signal(), Some(libc::SIGKILL));
427    }
428
429    /// A child that already exited (pid reaped) must not panic or error —
430    /// the teardown arm calls this unconditionally on both host and srv
431    /// without checking liveness first.
432    #[tokio::test]
433    async fn kill_process_group_forcefully_is_a_noop_on_an_already_exited_child() {
434        let mut cmd = tokio::process::Command::new("true");
435        cmd.kill_on_drop(false).process_group(0);
436        let mut child = cmd.spawn().expect("spawn true");
437        let _ = child.wait().await; // let it exit and get reaped
438
439        kill_process_group_forcefully(&child); // must not panic
440    }
441
442    /// `kill_process_group_gracefully` sends SIGTERM, not SIGKILL — the
443    /// half of the two-phase teardown a process WITH a signal handler (srv)
444    /// gets a real chance to act on.
445    #[tokio::test]
446    async fn kill_process_group_gracefully_sends_sigterm_not_sigkill() {
447        use std::os::unix::process::ExitStatusExt;
448
449        let mut cmd = tokio::process::Command::new("sleep");
450        cmd.arg("5").kill_on_drop(false).process_group(0);
451        let mut child = cmd.spawn().expect("spawn sleep");
452
453        kill_process_group_gracefully(&child);
454
455        let status = tokio::time::timeout(std::time::Duration::from_secs(2), child.wait())
456            .await
457            .expect("child did not exit after graceful group kill")
458            .expect("wait succeeded");
459        assert_eq!(status.signal(), Some(libc::SIGTERM));
460    }
461
462    /// Same no-op-on-already-exited guarantee as the forceful variant — the
463    /// teardown arm calls both unconditionally.
464    #[tokio::test]
465    async fn kill_process_group_gracefully_is_a_noop_on_an_already_exited_child() {
466        let mut cmd = tokio::process::Command::new("true");
467        cmd.kill_on_drop(false).process_group(0);
468        let mut child = cmd.spawn().expect("spawn true");
469        let _ = child.wait().await; // let it exit and get reaped
470
471        kill_process_group_gracefully(&child); // must not panic
472    }
473}
474
475/// `AGENTMUX_LAUNCHER_EXE` for the host: this launcher's own executable, so
476/// the host can invoke launcher CLI verbs (`--autostart-status`,
477/// `--enable-autostart`, `--disable-autostart`) on the user's behalf. Empty
478/// when `current_exe` fails — the host then reports auto-start as unavailable.
479fn launcher_exe_env() -> Vec<(&'static str, std::ffi::OsString)> {
480    std::env::current_exe()
481        .map(|p| vec![("AGENTMUX_LAUNCHER_EXE", p.into_os_string())])
482        .unwrap_or_default()
483}
484
485#[cfg(test)]
486mod tray_fallback_tests {
487    fn host_env(tray_unavailable: bool, args: &[String]) -> Vec<(String, Option<String>)> {
488        let mut cmd = tokio::process::Command::new("agentmux-host");
489        cmd.env("AGENTMUX_BACKGROUND_SERVICE", "1")
490            .env("AGENTMUX_TRAY", "1")
491            .envs(crate::autostart::background_env_for(args));
492        super::drop_background_if_no_tray(&mut cmd, tray_unavailable);
493        cmd.as_std()
494            .get_envs()
495            .filter(|(k, _)| k.to_str().is_some_and(|k| k == "AGENTMUX_BACKGROUND_SERVICE" || k == "AGENTMUX_TRAY"))
496            .map(|(k, v)| (k.to_string_lossy().into_owned(), v.map(|v| v.to_string_lossy().into_owned())))
497            .collect()
498    }
499
500    /// A tray that failed to start must not leave the host in background
501    /// mode: closing the last window would leave a process with no icon.
502    /// Covers both sources, the launcher's env (the setting) and `--background`.
503    #[test]
504    fn a_failed_tray_removes_background_mode_from_the_host() {
505        let args = vec!["agentmux".to_string(), crate::autostart::BACKGROUND_FLAG.to_string()];
506        let env = host_env(true, &args);
507        assert_eq!(env.len(), 2, "{env:?}");
508        assert!(env.iter().all(|(_, v)| v.is_none()), "both switches removed: {env:?}");
509    }
510
511    #[test]
512    fn a_working_tray_leaves_background_mode_alone() {
513        let env = host_env(false, &["agentmux".to_string()]);
514        assert_eq!(env.len(), 2, "{env:?}");
515        assert!(env.iter().all(|(_, v)| v.is_some()), "{env:?}");
516    }
517
518    #[test]
519    fn only_the_first_host_of_a_login_start_with_a_tray_starts_hidden() {
520        assert!(super::start_hidden_decision(true, false, true));
521        assert!(!super::start_hidden_decision(false, false, true), "a manual start shows its window");
522        assert!(!super::start_hidden_decision(true, true, true), "no tray: a window, never an invisible process");
523        assert!(!super::start_hidden_decision(true, false, false), "a restarted host comes back visible");
524    }
525}