Skip to main content

agentmux_launcher/
host_quit.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Quitting the host: the tray's "Quit AgentMux" and the restart into a new
5//! version the user agreed to.
6//!
7//! These used to send `quit_app` to the host's HTTP port with the token from
8//! the port file, which made that token able to quit the app. They now go over
9//! the launcher's own pipe to the host (`Command::QuitApp`), so the token only
10//! opens and raises windows.
11//!
12//! A host from another version may not know `QuitApp` (it would drop it
13//! without a word), so for one the launcher falls back to the HTTP command
14//! that host still takes. A host that has not registered yet is waited for, as
15//! the tray always did.
16
17use 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
33/// Called by the supervisor once it has the host pipe and the launcher state,
34/// from inside its runtime.
35pub fn install(pipe: Arc<HostPipe>, state: Arc<Mutex<State>>) {
36    let _ = INSTALLED.set(Installed { pipe, state, runtime: tokio::runtime::Handle::current() });
37}
38
39/// What to try next, given what the launcher knows of the host.
40#[derive(Debug, PartialEq, Eq)]
41enum Step {
42    /// The host has not registered: try again shortly.
43    Wait,
44    /// The host is this version: send `QuitApp` down the pipe.
45    Pipe,
46    /// The host is another version: use the HTTP command it knows.
47    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
58/// Quits the host. Blocking: runs on the tray's thread or a blocking task,
59/// never on the async runtime.
60pub 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}