agentmux_launcher/
host_quit.rs1use std::sync::{Arc, OnceLock};
18
19use agentmux_common::ipc::{ClientKind, Command};
20use tokio::sync::Mutex;
21
22use crate::host_pipe::HostPipe;
23use crate::state::State;
24
25struct Installed {
26 pipe: Arc<HostPipe>,
27 state: Arc<Mutex<State>>,
28 runtime: tokio::runtime::Handle,
29}
30
31static INSTALLED: OnceLock<Installed> = OnceLock::new();
32
33pub fn install(pipe: Arc<HostPipe>, state: Arc<Mutex<State>>) {
36 let _ = INSTALLED.set(Installed { pipe, state, runtime: tokio::runtime::Handle::current() });
37}
38
39#[derive(Debug, PartialEq, Eq)]
41enum Step {
42 Wait,
44 Pipe,
46 Http,
48}
49
50fn step(host_version: Option<&str>, own_version: &str) -> Step {
51 match host_version {
52 None => Step::Wait,
53 Some(v) if v == own_version => Step::Pipe,
54 Some(_) => Step::Http,
55 }
56}
57
58pub fn quit_host(data_dir: &std::path::Path, dir_hash: &str) {
61 const MAX_ATTEMPTS: u32 = 30;
62 const DELAY: std::time::Duration = std::time::Duration::from_secs(1);
63 let Some(ctx) = INSTALLED.get() else {
64 crate::tray::forward_tray_cmd(data_dir, dir_hash, "quit_app");
65 return;
66 };
67 for attempt in 1..=MAX_ATTEMPTS {
68 let host_version = ctx.runtime.block_on(async {
69 let st = ctx.state.lock().await;
70 st.processes.values().find(|p| p.kind == ClientKind::Host).map(|p| p.version.clone())
71 });
72 match step(host_version.as_deref(), env!("CARGO_PKG_VERSION")) {
73 Step::Http => return crate::tray::forward_tray_cmd(data_dir, dir_hash, "quit_app"),
74 Step::Pipe => {
75 match ctx.runtime.block_on(ctx.pipe.try_send_command_no_buffer(&Command::QuitApp)) {
76 Ok(()) => {
77 crate::log(&format!("quit: sent to the host over its pipe (attempt {attempt})"));
78 return;
79 }
80 Err(e) => crate::log(&format!("quit: the host pipe refused it (attempt {attempt}): {e:?}")),
81 }
82 }
83 Step::Wait => {}
84 }
85 std::thread::sleep(DELAY);
86 }
87 crate::log("quit: gave up; the host never took the request");
88}
89
90#[cfg(test)]
91mod tests {
92 use super::*;
93
94 #[test]
95 fn a_host_that_has_not_registered_is_waited_for() {
96 assert_eq!(step(None, "1.2.3"), Step::Wait);
97 }
98
99 #[test]
100 fn a_host_of_this_version_gets_the_pipe_command() {
101 assert_eq!(step(Some("1.2.3"), "1.2.3"), Step::Pipe);
102 }
103
104 #[test]
105 fn a_host_of_another_version_gets_the_http_command_it_knows() {
106 assert_eq!(step(Some("1.2.2"), "1.2.3"), Step::Http);
107 assert_eq!(step(Some("1.2.4"), "1.2.3"), Step::Http);
108 assert_eq!(step(Some(""), "1.2.3"), Step::Http);
109 }
110}