Skip to main content

agentmux_launcher/
quit_ask.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The tray's Quit asks first when it would stop agents that are working.
5//!
6//! Quitting stops every agent. A window's own close warns before it stops agents in the middle of
7//! a turn; the tray's Quit went straight to the host. It is also the Quit used with no window
8//! open, when the agents running are the ones nobody is looking at. So the launcher asks srv who
9//! is working (`GET /agentmux/quit-question`) and, when srv says to ask, puts the question in a
10//! native dialog of its own: one that needs no window and that no page or agent can answer.
11//!
12//! Quitting must always work. No answer from srv in time (srv is gone, hung or
13//! from a version without the question), or no way to show a dialog, quits as before. Only an
14//! explicit "keep running" stops the quit.
15//!
16//! The restart into a new version is not asked here: it has its own question
17//! (`upgrade_restart`), and goes to `host_quit::quit_host` directly.
18
19use std::path::Path;
20use std::sync::atomic::{AtomicBool, Ordering};
21use std::sync::Mutex;
22
23use agentmux_common::quit_question::{ask_srv, goes_ahead};
24#[cfg(any(target_os = "windows", target_os = "linux"))]
25use agentmux_common::quit_question::DIALOG_TITLE;
26#[cfg(target_os = "linux")]
27use agentmux_common::quit_question::{KEEP_RUNNING, QUIT};
28
29/// srv's web endpoint (`host:port`) and its key, from the last srv this launcher started.
30static SRV: Mutex<Option<(String, String)>> = Mutex::new(None);
31
32/// srv is up at `web_endpoint` (`srv_spawner::spawn_srv`, on every start of it).
33pub fn srv_is_at(web_endpoint: &str, auth_key: &str) {
34    *SRV.lock().unwrap_or_else(|e| e.into_inner()) = Some((web_endpoint.to_string(), auth_key.to_string()));
35}
36
37/// The tray's "Quit AgentMux". Asks on a thread of its own, so the tray's other items keep working
38/// while the dialog is open; a second Quit while one is being asked about is dropped.
39pub fn quit_from_tray(data_dir: &Path, dir_hash: &str) {
40    static ASKING: AtomicBool = AtomicBool::new(false);
41    if ASKING.swap(true, Ordering::SeqCst) {
42        crate::log("quit: already asking about a quit");
43        return;
44    }
45    let (dir, hash) = (data_dir.to_path_buf(), dir_hash.to_string());
46    let spawned = std::thread::Builder::new().name("agentmux-quit-ask".into()).spawn(move || {
47        let srv = SRV.lock().unwrap_or_else(|e| e.into_inner()).clone();
48        let question = srv.and_then(|(endpoint, key)| ask_srv(&endpoint, &key));
49        if let Some(q) = &question {
50            crate::log(&format!("quit: {} of {} agents working; asking", q.working.len(), q.agents));
51        }
52        let go = goes_ahead(question.as_ref(), confirm);
53        ASKING.store(false, Ordering::SeqCst);
54        if go {
55            crate::host_quit::quit_host(&dir, &hash);
56        } else {
57            crate::log("quit: the person chose to keep running");
58        }
59    });
60    if spawned.is_err() {
61        ASKING.store(false, Ordering::SeqCst);
62        crate::host_quit::quit_host(data_dir, dir_hash);
63    }
64}
65
66/// Ask in a native dialog whose default is to keep running. `Some(true)`: quit. `Some(false)`:
67/// keep running. `None`: no dialog could be shown.
68#[cfg(target_os = "windows")]
69fn confirm(body: &str) -> Option<bool> {
70    use std::os::windows::ffi::OsStrExt;
71    use windows_sys::Win32::UI::WindowsAndMessaging::{
72        MessageBoxW, IDYES, MB_DEFBUTTON2, MB_ICONWARNING, MB_SETFOREGROUND, MB_TOPMOST, MB_YESNO,
73    };
74    let wide = |s: &str| std::ffi::OsStr::new(s).encode_wide().chain(Some(0)).collect::<Vec<u16>>();
75    let (title, body) = (wide(DIALOG_TITLE), wide(body));
76    // A window of this process, answered by the person: nothing a page or an agent can reach.
77    let answer = unsafe {
78        MessageBoxW(
79            std::ptr::null_mut(),
80            body.as_ptr(),
81            title.as_ptr(),
82            MB_YESNO | MB_ICONWARNING | MB_DEFBUTTON2 | MB_SETFOREGROUND | MB_TOPMOST,
83        )
84    };
85    (answer != 0).then_some(answer == IDYES)
86}
87
88/// What `zenity` or `kdialog` said, from its exit code and what it wrote to stderr. Both exit 0
89/// for the first button (Quit) and 1 for the other one or a closed dialog (keep running). Anything
90/// else is a dialog that was never answered: `None`. So is an exit of 1 from a dialog that could
91/// not reach the display, which it says on stderr.
92#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
93fn linux_answer(exit_code: Option<i32>, stderr: &str) -> Option<bool> {
94    // How GTK and Qt say they have no display to draw on.
95    const NO_DISPLAY: [&str; 5] = ["open display", "connect to display", "x display", "wl_display", "init server"];
96    let said = stderr.to_ascii_lowercase();
97    match exit_code {
98        Some(0) => Some(true),
99        Some(1) if !NO_DISPLAY.iter().any(|phrase| said.contains(phrase)) => Some(false),
100        _ => None,
101    }
102}
103
104/// Linux: `zenity`, or else `kdialog`, as the upgrade question uses. With neither installed there
105/// is no dialog.
106#[cfg(target_os = "linux")]
107fn confirm(body: &str) -> Option<bool> {
108    let zenity_title = format!("--title={DIALOG_TITLE}");
109    let zenity_text = format!("--text={}", crate::upgrade_linux::pango_escape(body));
110    let zenity_ok = format!("--ok-label={QUIT}");
111    let zenity_cancel = format!("--cancel-label={KEEP_RUNNING}");
112    let dialogs: [(&str, Vec<&str>); 2] = [
113        ("zenity", vec!["--question", &zenity_title, &zenity_text, &zenity_ok, &zenity_cancel, "--default-cancel", "--width=460"]),
114        ("kdialog", vec!["--title", DIALOG_TITLE, "--yes-label", QUIT, "--no-label", KEEP_RUNNING, "--warningyesno", body]),
115    ];
116    for (program, args) in dialogs {
117        let mut cmd = std::process::Command::new(program);
118        cmd.args(&args).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null());
119        // Not this version's libraries: they could break the dialog's own.
120        for key in crate::upgrade_linux::NOT_INHERITED {
121            cmd.env_remove(key);
122        }
123        cmd.stderr(std::process::Stdio::piped());
124        match cmd.output() {
125            Ok(out) => {
126                let answer = linux_answer(out.status.code(), &String::from_utf8_lossy(&out.stderr));
127                if answer.is_none() {
128                    crate::log(&format!("quit: {program} did not show the question ({}); quitting", out.status));
129                }
130                return answer;
131            }
132            Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
133            Err(e) => {
134                crate::log(&format!("quit: couldn't open {program} to ask: {e}"));
135                return None;
136            }
137        }
138    }
139    crate::log("quit: neither zenity nor kdialog is installed to ask with");
140    None
141}
142
143/// macOS: the dialog the host's own Quit uses too (`agentmux_common::quit_question`).
144#[cfg(target_os = "macos")]
145fn confirm(body: &str) -> Option<bool> {
146    match agentmux_common::quit_question::confirm_macos(body) {
147        Ok(answer) => Some(answer),
148        Err(why) => {
149            crate::log(&format!("quit: {why}; quitting"));
150            None
151        }
152    }
153}
154
155#[cfg(not(any(target_os = "windows", target_os = "linux", target_os = "macos")))]
156fn confirm(_body: &str) -> Option<bool> {
157    None
158}
159
160#[cfg(test)]
161mod tests {
162    use super::*;
163
164    #[test]
165    fn a_dialog_that_failed_is_not_an_answer_to_keep_running() {
166        // Linux: 0 is Quit, 1 is the other button or a closed dialog.
167        assert_eq!(linux_answer(Some(0), ""), Some(true));
168        assert_eq!(linux_answer(Some(1), ""), Some(false));
169        assert_eq!(linux_answer(Some(1), "Gtk-Message: GtkDialog mapped without a transient parent"), Some(false));
170        // It never reached the screen: no answer, so the quit goes ahead.
171        assert_eq!(linux_answer(Some(1), "(zenity:4242): Gtk-WARNING **: cannot open display: "), None);
172        assert_eq!(linux_answer(Some(1), "qt.qpa.xcb: could not connect to display"), None);
173        assert_eq!(linux_answer(Some(5), ""), None, "zenity's timeout");
174        assert_eq!(linux_answer(Some(255), ""), None);
175        assert_eq!(linux_answer(None, ""), None, "ended by a signal");
176    }
177}