1use std::io::{Read, Write};
20use std::net::{TcpStream, ToSocketAddrs};
21use std::time::Duration;
22
23const QUESTION_PATH: &str = "/agentmux/quit-question";
25
26const 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#[derive(Debug, PartialEq, Eq)]
37pub struct Question {
38 pub working: Vec<String>,
40 pub agents: u64,
42}
43
44fn 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
59fn 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
69pub 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
83fn 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
94pub 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
105pub 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#[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#[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#[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#[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 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 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 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 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 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 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 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 assert_eq!(ask_srv(&endpoint, "the-key"), None);
320 }
321}