Skip to main content

agentmux_common/
quit_question.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The question asked before a quit that would stop agents in the middle of a turn.
5//!
6//! Quitting stops every agent. A window's own close warns first (`frontend/app/window/window-close.ts`);
7//! a quit that comes from outside a window does not pass a page. So whoever starts such a quit asks
8//! srv who is working (`GET /agentmux/quit-question`) and, when srv says to ask, puts the question in
9//! a native dialog of its own: one that needs no window and that no page or agent can answer.
10//!
11//! The launcher asks for the tray's Quit (`crates/launcher/src/quit_ask.rs`); the host asks for the
12//! macOS app menu's Quit and Cmd+Q (`crates/cef/src/macos_menu.rs`). They share this: the question,
13//! the text, and the macOS dialog.
14//!
15//! Quitting must always work. No answer from srv within [`ANSWER_WITHIN`] (srv is gone, hung or from
16//! a version without the question), or no way to show a dialog, quits as before. Only an explicit
17//! "keep running" stops the quit.
18
19use std::io::{Read, Write};
20use std::net::{TcpStream, ToSocketAddrs};
21use std::time::Duration;
22
23/// srv's route (`crates/srv/src/server/quit_question.rs`).
24const QUESTION_PATH: &str = "/agentmux/quit-question";
25
26/// How long srv has to answer, for the connection and for each read.
27const ANSWER_WITHIN: Duration = Duration::from_millis(1500);
28
29pub const DIALOG_TITLE: &str = "Quit AgentMux";
30#[cfg_attr(not(any(target_os = "linux", target_os = "macos", test)), allow(dead_code))]
31pub const QUIT: &str = "Quit";
32#[cfg_attr(not(any(target_os = "linux", target_os = "macos", test)), allow(dead_code))]
33pub const KEEP_RUNNING: &str = "Keep running";
34
35/// What srv said when it said to ask.
36#[derive(Debug, PartialEq, Eq)]
37pub struct Question {
38    /// The agents in the middle of a turn, by name.
39    pub working: Vec<String>,
40    /// How many agents the quit stops.
41    pub agents: u64,
42}
43
44/// srv's answer as a question to put, or `None` when it says not to ask or says nothing usable.
45fn parse(json: &str) -> Option<Question> {
46    let answer: serde_json::Value = serde_json::from_str(json).ok()?;
47    if !answer.get("ask")?.as_bool()? {
48        return None;
49    }
50    let working: Vec<String> =
51        answer.get("working")?.as_array()?.iter().filter_map(|n| n.as_str()).map(str::to_string).collect();
52    if working.is_empty() {
53        return None;
54    }
55    let agents = answer.get("agents").and_then(|n| n.as_u64()).unwrap_or(0).max(working.len() as u64);
56    Some(Question { working, agents })
57}
58
59/// The JSON object in an HTTP response with status 200, whatever the body's framing.
60fn json_of(response: &str) -> Option<&str> {
61    let (head, body) = response.split_once("\r\n\r\n")?;
62    if !head.starts_with("HTTP/1.1 200") {
63        return None;
64    }
65    let (start, end) = (body.find('{')?, body.rfind('}')?);
66    (start < end).then(|| &body[start..=end])
67}
68
69/// Ask srv. Blocking, bounded by [`ANSWER_WITHIN`] for the connection and for each read.
70pub fn ask_srv(web_endpoint: &str, auth_key: &str) -> Option<Question> {
71    let addr = web_endpoint.to_socket_addrs().ok()?.next()?;
72    let mut stream = TcpStream::connect_timeout(&addr, ANSWER_WITHIN).ok()?;
73    stream.set_read_timeout(Some(ANSWER_WITHIN)).ok()?;
74    stream.set_write_timeout(Some(ANSWER_WITHIN)).ok()?;
75    let request =
76        format!("GET {QUESTION_PATH} HTTP/1.1\r\nHost: {web_endpoint}\r\nX-AuthKey: {auth_key}\r\nConnection: close\r\n\r\n");
77    stream.write_all(request.as_bytes()).ok()?;
78    let mut response = String::new();
79    stream.read_to_string(&mut response).ok()?;
80    parse(json_of(&response)?)
81}
82
83/// "Alpha, Beta and 3 more", as the window's close warning names them.
84fn names_line(names: &[String]) -> String {
85    const MAX: usize = 4;
86    match names {
87        [] => String::new(),
88        [one] => one.clone(),
89        _ if names.len() <= MAX => format!("{} and {}", names[..names.len() - 1].join(", "), names[names.len() - 1]),
90        _ => format!("{} and {} more", names[..MAX].join(", "), names.len() - MAX),
91    }
92}
93
94/// The dialog's text.
95pub fn text(q: &Question) -> String {
96    let verb = if q.working.len() == 1 { "is" } else { "are" };
97    let agents = if q.agents == 1 { "1 agent".to_string() } else { format!("{} agents", q.agents) };
98    format!(
99        "{} {verb} working. Quit AgentMux?\n\n\
100         This stops {agents}. Your windows open again at the next launch.",
101        names_line(&q.working)
102    )
103}
104
105/// Whether the quit goes ahead: always, unless there is a question and the person answers it with
106/// "keep running". `confirm` is `None` when no dialog could be shown.
107pub fn goes_ahead(question: Option<&Question>, confirm: impl FnOnce(&str) -> Option<bool>) -> bool {
108    match question {
109        None => true,
110        Some(q) => confirm(&text(q)).unwrap_or(true),
111    }
112}
113
114/// What `osascript` said. The alert ([`MACOS_ALERT`]) exits 0 and prints `button returned:` and the
115/// title of the button clicked: Quit, or Keep running. The "User canceled" error, -128, is what a
116/// `display dialog` with a cancel button gives for Keep running; it is read as Keep running too.
117/// Any other failure is an alert that was never answered: `None`, and the quit goes ahead.
118#[cfg_attr(not(any(target_os = "macos", test)), allow(dead_code))]
119pub fn macos_answer(success: bool, stdout: &str, stderr: &str) -> Option<bool> {
120    if success && stdout.contains(&format!("button returned:{QUIT}")) {
121        Some(true)
122    } else if stderr.contains("(-128)") || (success && stdout.contains(&format!("button returned:{KEEP_RUNNING}"))) {
123        Some(false)
124    } else {
125        None
126    }
127}
128
129/// The macOS question as an alert, for `osascript -l JavaScript`: the arguments are the text, the Quit
130/// and Keep running titles and the icon's path (empty for none), and it prints `button returned:<title>`
131/// as `display dialog` did, so [`macos_answer`] reads either. Keep running is the first button: the
132/// default (Return), and the answer for anything that is not a click on Quit. It is an alert and not
133/// `display dialog` so that it carries the app's own icon. Its keys are the ones `display dialog` had:
134/// Return, and the mouse (Tab and Space reach Quit only with the system's Full Keyboard Access on).
135/// Escape, and a key for Quit, do not work in an alert shown by `osascript` (tried on macOS 26: no key
136/// equivalent on the Quit button fires, and a button titled Cancel gets Escape only now and then and
137/// loses Return and the default highlight).
138#[cfg(any(target_os = "macos", test))]
139const MACOS_ALERT: &str = r#"ObjC.import('AppKit');
140function run(argv) {
141  var body = argv[0], quitTitle = argv[1], keepTitle = argv[2], iconPath = argv[3] || '';
142  var app = $.NSApplication.sharedApplication;
143  app.setActivationPolicy($.NSApplicationActivationPolicyAccessory);
144  var alert = $.NSAlert.alloc.init;
145  alert.alertStyle = $.NSAlertStyleWarning;
146  var parts = body.split('\n\n');
147  alert.messageText = parts[0];
148  alert.informativeText = parts.slice(1).join('\n\n');
149  if (iconPath !== '') {
150    try {
151      var img = $.NSImage.alloc.initWithContentsOfFile(iconPath);
152      if (img) { alert.icon = img; }
153    } catch (e) { }
154  }
155  alert.addButtonWithTitle(keepTitle);
156  alert.addButtonWithTitle(quitTitle);
157  app.activateIgnoringOtherApps(true);
158  var response = (typeof alert.runModal === 'function') ? alert.runModal() : alert.runModal;
159  return 'button returned:' + (response == 1001 ? quitTitle : keepTitle);
160}"#;
161
162/// The app's icon, for the alert: `Contents/Resources/AgentMux.icns` of the `.app` that `exe` is in
163/// (`package-macos.sh` writes it there), when `exists` says it is there. A build run from a folder has
164/// none, and the alert then carries the system's default icon.
165#[cfg(any(target_os = "macos", test))]
166fn app_icon(exe: &std::path::Path, exists: impl Fn(&std::path::Path) -> bool) -> Option<std::path::PathBuf> {
167    let mut bundle = std::path::PathBuf::new();
168    for part in exe.components() {
169        bundle.push(part);
170        if part.as_os_str().to_string_lossy().ends_with(".app") {
171            let icon = bundle.join("Contents").join("Resources").join("AgentMux.icns");
172            return exists(&icon).then_some(icon);
173        }
174    }
175    None
176}
177
178/// macOS: ask in a native alert whose default is to keep running, through `osascript` (as the
179/// upgrade question does). The text goes to it as arguments, never into the script, so nothing in
180/// it is parsed. `Ok(true)`: quit. `Ok(false)`: keep running. `Err`: no dialog was answered, and
181/// why, for the caller's log; the quit then goes ahead.
182#[cfg(target_os = "macos")]
183pub fn confirm_macos(body: &str) -> Result<bool, String> {
184    let icon = std::env::current_exe()
185        .ok()
186        .and_then(|exe| app_icon(&exe, |p| p.is_file()))
187        .map(|p| p.to_string_lossy().into_owned())
188        .unwrap_or_default();
189    let out = std::process::Command::new("/usr/bin/osascript")
190        .args(["-l", "JavaScript", "-e", MACOS_ALERT])
191        .arg(body)
192        .arg(QUIT)
193        .arg(KEEP_RUNNING)
194        .arg(icon)
195        .stdin(std::process::Stdio::null())
196        .output()
197        .map_err(|e| format!("couldn't open osascript to ask: {e}"))?;
198    macos_answer(
199        out.status.success(),
200        &String::from_utf8_lossy(&out.stdout),
201        &String::from_utf8_lossy(&out.stderr),
202    )
203    .ok_or_else(|| format!("osascript did not show the question ({})", out.status))
204}
205
206#[cfg(test)]
207mod tests {
208    use super::*;
209
210    fn names(list: &[&str]) -> Vec<String> {
211        list.iter().map(|n| n.to_string()).collect()
212    }
213
214    #[test]
215    fn srvs_answer_is_a_question_only_when_it_says_to_ask_and_names_someone() {
216        assert_eq!(
217            parse(r#"{"ask":true,"working":["Korp","Loap"],"agents":5}"#),
218            Some(Question { working: names(&["Korp", "Loap"]), agents: 5 })
219        );
220        assert_eq!(parse(r#"{"ask":false,"working":["Korp"],"agents":1}"#), None, "the warning is off");
221        assert_eq!(parse(r#"{"ask":false,"working":[],"agents":3}"#), None, "nobody is mid-turn");
222        assert_eq!(parse(r#"{"ask":true,"working":[],"agents":3}"#), None);
223        assert_eq!(parse(r#"{"error":"not found"}"#), None, "a srv without the question");
224        assert_eq!(parse("not json"), None);
225        // A count that is missing or too small never says fewer agents than are named.
226        assert_eq!(parse(r#"{"ask":true,"working":["Korp","Loap"]}"#).map(|q| q.agents), Some(2));
227    }
228
229    #[test]
230    fn the_json_is_taken_from_a_200_whatever_the_framing() {
231        let plain = "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: 14\r\n\r\n{\"ask\":false}";
232        assert_eq!(json_of(plain), Some("{\"ask\":false}"));
233        let chunked = "HTTP/1.1 200 OK\r\ntransfer-encoding: chunked\r\n\r\nd\r\n{\"ask\":false}\r\n0\r\n\r\n";
234        assert_eq!(json_of(chunked), Some("{\"ask\":false}"));
235        assert_eq!(json_of("HTTP/1.1 404 Not Found\r\n\r\n{\"error\":\"x\"}"), None);
236        assert_eq!(json_of("HTTP/1.1 200 OK\r\n\r\n"), None);
237        assert_eq!(json_of("garbage"), None);
238        assert_eq!(json_of("HTTP/1.1 200 OK\r\n\r\n}{"), None);
239    }
240
241    #[test]
242    fn the_text_names_who_is_working_and_how_many_agents_stop() {
243        let one = text(&Question { working: names(&["Korp"]), agents: 1 });
244        assert!(one.starts_with("Korp is working. Quit AgentMux?\n\nThis stops 1 agent. "), "{one}");
245        let two = text(&Question { working: names(&["Korp", "Loap"]), agents: 5 });
246        assert!(two.starts_with("Korp and Loap are working. Quit AgentMux?\n\nThis stops 5 agents. "), "{two}");
247        assert_eq!(names_line(&names(&["A", "B", "C"])), "A, B and C");
248        assert_eq!(names_line(&names(&["A", "B", "C", "D", "E", "F"])), "A, B, C, D and 2 more");
249    }
250
251    #[test]
252    fn only_an_explicit_keep_running_stops_the_quit() {
253        let q = Question { working: names(&["Korp"]), agents: 2 };
254        assert!(goes_ahead(None, |_| panic!("nothing to ask: no dialog")), "srv gave no question");
255        assert!(goes_ahead(Some(&q), |_| Some(true)));
256        assert!(!goes_ahead(Some(&q), |_| Some(false)));
257        assert!(goes_ahead(Some(&q), |_| None), "no dialog could be shown: quitting still works");
258    }
259
260    #[test]
261    fn a_macos_dialog_that_failed_is_not_an_answer_to_keep_running() {
262        // The Quit button, the cancel button (error -128), and everything else.
263        assert_eq!(macos_answer(true, "button returned:Quit\n", ""), Some(true));
264        let cancelled = "0:140: execution error: User canceled. (-128)";
265        assert_eq!(macos_answer(false, "", cancelled), Some(false));
266        assert_eq!(macos_answer(true, "button returned:Keep running\n", ""), Some(false));
267        assert_eq!(macos_answer(false, "", "execution error: No user interaction allowed. (-1713)"), None);
268        assert_eq!(macos_answer(false, "", ""), None);
269        assert_eq!(macos_answer(true, "", ""), None);
270    }
271
272    #[test]
273    fn the_alert_prints_what_display_dialog_printed_and_keeps_running_unless_quit_was_clicked() {
274        // `macos_answer` reads the alert's output as it read the old dialog's.
275        assert!(MACOS_ALERT.contains("'button returned:' + (response == 1001 ? quitTitle : keepTitle)"));
276        let printed = format!("button returned:{QUIT}\n");
277        assert_eq!(macos_answer(true, &printed, ""), Some(true));
278        // The first button (Keep running) is the default, the second is Quit.
279        let keep_at = MACOS_ALERT.find("addButtonWithTitle(keepTitle)").expect("keep button");
280        let quit_at = MACOS_ALERT.find("addButtonWithTitle(quitTitle)").expect("quit button");
281        assert!(keep_at < quit_at, "Return must pick Keep running");
282        // The text, the titles and the icon come as arguments, never as script text.
283        assert!(!MACOS_ALERT.contains(KEEP_RUNNING) && !MACOS_ALERT.contains("AgentMux"), "no text in the script");
284    }
285
286    #[test]
287    fn the_icon_is_the_one_in_the_app_the_program_runs_from() {
288        use std::path::{Path, PathBuf};
289        let in_app = Path::new("/Applications/AgentMux.app/Contents/MacOS/agentmux-launcher");
290        let icon = PathBuf::from("/Applications/AgentMux.app/Contents/Resources/AgentMux.icns");
291        assert_eq!(app_icon(in_app, |p| p == icon), Some(icon.clone()));
292        assert_eq!(app_icon(in_app, |_| false), None, "an icon that is not there is not offered");
293        // Inside a helper app of the bundle, the outer app's icon is still the one.
294        let helper = Path::new("/Applications/AgentMux.app/Contents/Frameworks/AgentMux Helper.app/Contents/MacOS/AgentMux Helper");
295        assert_eq!(app_icon(helper, |p| p == icon), Some(icon.clone()));
296        // A build run from a folder has no app, so the system's icon stays.
297        assert_eq!(app_icon(Path::new("/Users/me/agentmux/target/debug/agentmux-launcher"), |_| true), None);
298    }
299
300    #[test]
301    fn srv_is_asked_over_http_with_the_key_and_no_answer_is_no_question() {
302        use std::net::TcpListener;
303        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
304        let endpoint = listener.local_addr().unwrap().to_string();
305        let server = std::thread::spawn(move || {
306            let (mut conn, _) = listener.accept().unwrap();
307            let mut request = [0u8; 1024];
308            let n = conn.read(&mut request).unwrap();
309            let request = String::from_utf8_lossy(&request[..n]).to_string();
310            let body = r#"{"ask":true,"working":["Korp"],"agents":2}"#;
311            let _ = write!(conn, "HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len());
312            request
313        });
314        assert_eq!(ask_srv(&endpoint, "the-key"), Some(Question { working: names(&["Korp"]), agents: 2 }));
315        let request = server.join().unwrap();
316        assert!(request.starts_with("GET /agentmux/quit-question HTTP/1.1\r\n"), "{request}");
317        assert!(request.contains("X-AuthKey: the-key\r\n"), "{request}");
318        // Nothing listens there any more: no question, so the quit goes ahead.
319        assert_eq!(ask_srv(&endpoint, "the-key"), None);
320    }
321}