Skip to main content

agentmux_srv_core/backend/remote/
helper_hosts.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The SSH hosts AgentMux's helper has answered on (spec §7.1 of
5//! SPEC_REMOTE_TERMINALS_AND_DURABLE_SESSIONS_2026_10_02.md): on such a host
6//! a new terminal pane is durable unless the pane, the connection's settings
7//! or the global setting say otherwise. Kept in `remote-helper-hosts.json`
8//! under AgentMux's config dir; a host is its canonical connection name
9//! (`ConnTarget::name`), so one host is one entry however it is spelled.
10//!
11//! The same file keeps what AgentMux learned about each host for the Remotes
12//! pane (SPEC_REMOTES_PANE_2026_10_05.md §4.6): its platform (`uname -sm`, from
13//! the helper install's probe) and the AgentMux version whose helper last
14//! answered there.
15
16use std::collections::BTreeMap;
17use std::path::{Path, PathBuf};
18use std::sync::Mutex;
19
20use serde::{Deserialize, Serialize};
21
22const FILE_NAME: &str = "remote-helper-hosts.json";
23
24#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
25struct Hosts {
26    #[serde(default)]
27    hosts: Vec<String>,
28    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
29    info: BTreeMap<String, HostInfo>,
30}
31
32/// What AgentMux learned about one host.
33#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
34pub struct HostInfo {
35    /// `uname -sm` as the host printed it (`Linux x86_64`, `Darwin arm64`).
36    #[serde(default, skip_serializing_if = "String::is_empty")]
37    pub uname: String,
38    /// The AgentMux version whose helper last answered here.
39    #[serde(default, skip_serializing_if = "String::is_empty")]
40    pub helper_version: String,
41    /// When this record last changed, in Unix milliseconds.
42    #[serde(default)]
43    pub seen_at_ms: u64,
44}
45
46/// Serializes read-modify-write of the file within this srv.
47static LOCK: Mutex<()> = Mutex::new(());
48
49fn path_in(config_home: &Path) -> PathBuf {
50    config_home.join(FILE_NAME)
51}
52
53fn read(path: &Path) -> Hosts {
54    std::fs::read_to_string(path)
55        .ok()
56        .and_then(|s| serde_json::from_str(&s).ok())
57        .unwrap_or_default()
58}
59
60fn write(config_home: &Path, hosts: &Hosts) -> std::io::Result<()> {
61    use crate::backend::json_keep::{carry_unknown_keys, read_old, set_aside_if_unreadable};
62    let path = path_in(config_home);
63    std::fs::create_dir_all(config_home)?;
64    // A file this build cannot read is copied aside before it is replaced; a key a newer AgentMux wrote, in the file or about a
65    // host, is carried over from it.
66    set_aside_if_unreadable::<Hosts>(&path);
67    let mut out = serde_json::to_value(hosts).unwrap_or_default();
68    if let Some(old) = read_old(&path) {
69        carry_unknown_keys(&old, &mut out, &["hosts", "info"]);
70        if let (Some(before), Some(now)) = (old.get("info").and_then(|i| i.as_object()), out.get_mut("info").and_then(|i| i.as_object_mut())) {
71            for (host, info) in now.iter_mut() {
72                if let Some(was) = before.get(host) {
73                    carry_unknown_keys(was, info, &["uname", "helper_version", "seen_at_ms"]);
74                }
75            }
76        }
77    }
78    let tmp = path.with_extension("json.tmp");
79    std::fs::write(&tmp, serde_json::to_vec_pretty(&out).unwrap_or_default())?;
80    std::fs::rename(&tmp, &path)
81}
82
83fn canonical(connection: &str) -> Option<String> {
84    match super::ConnTarget::parse(connection) {
85        Ok(t @ super::ConnTarget::Ssh(_)) => Some(t.name()),
86        _ => None,
87    }
88}
89
90use agentmux_common::time::now_ms_u64 as now_ms;
91
92/// Change `connection`'s record (and, with `helper`, mark the helper as there),
93/// writing only when something changed.
94fn change_in(
95    config_home: &Path,
96    connection: &str,
97    helper: bool,
98    edit: impl FnOnce(&mut HostInfo),
99) -> std::io::Result<()> {
100    let Some(name) = canonical(connection) else {
101        return Ok(());
102    };
103    let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
104    let mut hosts = read(&path_in(config_home));
105    let before = hosts.clone();
106    if helper && !hosts.hosts.contains(&name) {
107        hosts.hosts.push(name.clone());
108    }
109    let info = hosts.info.entry(name).or_default();
110    let mut edited = info.clone();
111    edit(&mut edited);
112    if edited != *info {
113        edited.seen_at_ms = now_ms();
114        *info = edited;
115    }
116    if hosts == before {
117        return Ok(());
118    }
119    write(config_home, &hosts)
120}
121
122/// Whether the helper has answered on `connection`'s host.
123pub fn known_in(config_home: &Path, connection: &str) -> bool {
124    let Some(name) = canonical(connection) else {
125        return false;
126    };
127    let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
128    read(&path_in(config_home)).hosts.contains(&name)
129}
130
131/// Remember that the helper of AgentMux `version` answered on `connection`'s host.
132pub fn remember_in(config_home: &Path, connection: &str, version: &str) -> std::io::Result<()> {
133    change_in(config_home, connection, true, |info| info.helper_version = version.to_string())
134}
135
136/// Record `connection`'s platform, as `uname -sm` printed it.
137pub fn record_uname_in(config_home: &Path, connection: &str, uname: &str) -> std::io::Result<()> {
138    let uname = uname.trim();
139    if uname.is_empty() {
140        return Ok(());
141    }
142    change_in(config_home, connection, false, |info| info.uname = uname.to_string())
143}
144
145/// Every host the helper has answered on, and every host's record, by canonical name.
146pub fn all_in(config_home: &Path) -> (Vec<String>, BTreeMap<String, HostInfo>) {
147    let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
148    let hosts = read(&path_in(config_home));
149    (hosts.hosts, hosts.info)
150}
151
152/// [`known_in`] under this instance's config dir.
153pub fn known(connection: &str) -> bool {
154    known_in(&crate::backend::base::get_mux_config_dir(), connection)
155}
156
157/// [`remember_in`] under this instance's config dir, for this AgentMux's
158/// version, then (in the background, when that changed anything) for the
159/// other names of its machine ([`remember_on_machine`]). Best effort: a host
160/// not remembered only means its next pane is not durable by default.
161pub fn remember(connection: &str) {
162    let config_home = crate::backend::base::get_mux_config_dir();
163    let version = env!("CARGO_PKG_VERSION");
164    let had = |c: &str| {
165        let (hosts, info) = all_in(&config_home);
166        canonical(c).is_some_and(|n| hosts.contains(&n) && info.get(&n).is_some_and(|i| i.helper_version == version))
167    };
168    let already = had(connection);
169    if let Err(e) = remember_in(&config_home, connection, version) {
170        tracing::warn!(connection = %connection, error = %e, "could not remember a helper host");
171    }
172    if !already {
173        on_machine_later(connection, true);
174    }
175}
176
177/// Record `connection`'s helper for the other names of its machine, in the
178/// background: `ssh -G` may take a moment, and the callers can't wait.
179fn on_machine_later(connection: &str, installed: bool) {
180    let Ok(rt) = tokio::runtime::Handle::try_current() else {
181        return;
182    };
183    let connection = connection.to_string();
184    rt.spawn(async move {
185        if installed {
186            remember_on_machine(&connection).await;
187        } else if let Err(e) = forget_helper_on_machine(&connection).await {
188            tracing::warn!(connection = %connection, error = %e, "could not forget the helper record");
189        }
190    });
191}
192
193/// [`record_uname_in`] under this instance's config dir. Best effort.
194pub fn record_uname(connection: &str, uname: &str) {
195    if let Err(e) = record_uname_in(&crate::backend::base::get_mux_config_dir(), connection, uname) {
196        tracing::warn!(connection = %connection, error = %e, "could not record a host's platform");
197    }
198}
199
200/// The helper was removed from `connection`'s host: it is no longer a helper
201/// host, and no version is there. Its platform stays known.
202pub fn forget_helper_in(config_home: &Path, connection: &str) -> std::io::Result<()> {
203    let Some(name) = canonical(connection) else {
204        return Ok(());
205    };
206    let _g = LOCK.lock().unwrap_or_else(|e| e.into_inner());
207    let mut hosts = read(&path_in(config_home));
208    let before = hosts.clone();
209    hosts.hosts.retain(|h| h != &name);
210    if let Some(info) = hosts.info.get_mut(&name) {
211        if !info.helper_version.is_empty() {
212            info.helper_version.clear();
213            info.seen_at_ms = now_ms();
214        }
215    }
216    if hosts == before {
217        return Ok(());
218    }
219    write(config_home, &hosts)
220}
221
222/// [`forget_helper_in`] under this instance's config dir, then (in the
223/// background) for the other names of its machine.
224pub fn forget_helper(connection: &str) -> std::io::Result<()> {
225    forget_helper_in(&crate::backend::base::get_mux_config_dir(), connection)?;
226    on_machine_later(connection, false);
227    Ok(())
228}
229
230// ── One machine, many names ────────────────────────────────────────────────
231//
232// The helper lives in the remote account's home, so every name for the same
233// account on the same machine (two ssh config aliases for one
234// `user@host:port`, say) shares one helper. What one name learns about it is
235// recorded for all of them, or each name would show its own guess (#4513).
236
237/// `user@hostname:port` from `ssh -G`'s output, the host name in lower case;
238/// `None` unless all three are there.
239fn machine_from_ssh_g(out: &str) -> Option<String> {
240    let (mut user, mut host, mut port) = (None, None, None);
241    for line in out.lines() {
242        match line.trim_end().split_once(' ') {
243            Some(("user", v)) if !v.trim().is_empty() => user = Some(v.trim().to_string()),
244            Some(("hostname", v)) if !v.trim().is_empty() => host = Some(v.trim().to_ascii_lowercase()),
245            Some(("port", v)) => port = v.trim().parse::<u16>().ok(),
246            _ => {}
247        }
248    }
249    Some(format!("{}@{}:{}", user?, host?, port?))
250}
251
252/// How many `ssh -G` [`same_machine`] runs at once.
253const SSH_G_AT_ONCE: usize = 4;
254
255/// How long a name's machine is kept: `ssh -G` runs at most once in that
256/// time for each name.
257const MACHINE_TTL: std::time::Duration = std::time::Duration::from_secs(300);
258
259/// The account and machine `connection` logs in to, as `ssh -G` says (the
260/// user's ssh config applied); `None` if it can't say.
261async fn machine(connection: &str) -> Option<String> {
262    use std::collections::HashMap;
263    use std::sync::LazyLock;
264    use std::time::Instant;
265    static CACHE: LazyLock<Mutex<HashMap<String, (Instant, Option<String>)>>> = LazyLock::new(Default::default);
266    let name = canonical(connection)?;
267    if let Some((at, found)) = CACHE.lock().unwrap_or_else(|e| e.into_inner()).get(&name) {
268        if at.elapsed() < MACHINE_TTL {
269            return found.clone();
270        }
271    }
272    let found = match super::ConnTarget::parse(&name) {
273        Ok(super::ConnTarget::Ssh(dest)) => super::address::ssh_g(&dest).await.and_then(|out| machine_from_ssh_g(&out)),
274        _ => None,
275    };
276    CACHE.lock().unwrap_or_else(|e| e.into_inner()).insert(name, (Instant::now(), found.clone()));
277    found
278}
279
280/// The other names AgentMux knows (the user's ssh config hosts, and the
281/// hosts recorded here) for the account and machine `connection` logs in to.
282async fn same_machine(connection: &str) -> Vec<String> {
283    let Some(name) = canonical(connection) else {
284        return Vec::new();
285    };
286    let Some(target) = machine(&name).await else {
287        return Vec::new();
288    };
289    let mut names = tokio::task::spawn_blocking(super::ssh_config::hosts).await.unwrap_or_default();
290    let (recorded, info) = all_in(&crate::backend::base::get_mux_config_dir());
291    names.extend(recorded);
292    names.extend(info.into_keys());
293    let mut names: Vec<String> = names.iter().filter_map(|n| canonical(n)).filter(|n| *n != name).collect();
294    names.sort();
295    names.dedup();
296    // A few at a time: a large ssh config would otherwise start dozens of ssh
297    // processes at once.
298    use futures_util::StreamExt;
299    let machines: Vec<Option<String>> = futures_util::stream::iter(names.clone())
300        .map(|n| async move { machine(&n).await })
301        .buffered(SSH_G_AT_ONCE)
302        .collect()
303        .await;
304    names.into_iter().zip(machines).filter(|(_, m)| m.as_deref() == Some(target.as_str())).map(|(n, _)| n).collect()
305}
306
307/// [`remember_in`] for `connection` and each of `same`, its machine's other names.
308fn remember_on_machine_in(config_home: &Path, connection: &str, same: &[String], version: &str) -> std::io::Result<()> {
309    remember_in(config_home, connection, version)?;
310    same.iter().try_for_each(|n| remember_in(config_home, n, version))
311}
312
313/// [`forget_helper_in`] for `connection` and each of `same`, its machine's other names.
314fn forget_on_machine_in(config_home: &Path, connection: &str, same: &[String]) -> std::io::Result<()> {
315    forget_helper_in(config_home, connection)?;
316    same.iter().try_for_each(|n| forget_helper_in(config_home, n))
317}
318
319/// [`remember`], for every name of `connection`'s machine. Best effort.
320pub async fn remember_on_machine(connection: &str) {
321    let same = same_machine(connection).await;
322    if let Err(e) = remember_on_machine_in(
323        &crate::backend::base::get_mux_config_dir(),
324        connection,
325        &same,
326        env!("CARGO_PKG_VERSION"),
327    ) {
328        tracing::warn!(connection = %connection, error = %e, "could not remember a helper host");
329    }
330}
331
332/// [`forget_helper`], for every name of `connection`'s machine.
333pub async fn forget_helper_on_machine(connection: &str) -> std::io::Result<()> {
334    let same = same_machine(connection).await;
335    forget_on_machine_in(&crate::backend::base::get_mux_config_dir(), connection, &same)
336}
337
338#[cfg(test)]
339mod tests {
340    use super::*;
341
342    #[test]
343    fn a_removed_helper_is_forgotten_but_the_platform_kept() {
344        let dir = tempfile::tempdir().unwrap();
345        record_uname_in(dir.path(), "user@box", "Linux x86_64").unwrap();
346        remember_in(dir.path(), "user@box", "0.59.9").unwrap();
347        remember_in(dir.path(), "other@box", "0.59.9").unwrap();
348        forget_helper_in(dir.path(), " user@box ").unwrap();
349        assert!(!known_in(dir.path(), "user@box"));
350        assert!(known_in(dir.path(), "other@box"), "other hosts untouched");
351        let (_, info) = all_in(dir.path());
352        assert_eq!(info["user@box"].uname, "Linux x86_64");
353        assert_eq!(info["user@box"].helper_version, "");
354    }
355
356    #[test]
357    fn a_host_is_remembered_once_however_it_is_spelled() {
358        let dir = tempfile::tempdir().unwrap();
359        assert!(!known_in(dir.path(), "user@box"));
360        remember_in(dir.path(), "user@box", "0.59.9").unwrap();
361        remember_in(dir.path(), " user@box ", "0.59.9").unwrap();
362        assert!(known_in(dir.path(), "user@box"));
363        assert_eq!(read(&path_in(dir.path())).hosts.len(), 1);
364        assert!(!known_in(dir.path(), "other@box"));
365        // Not SSH: never a helper host.
366        remember_in(dir.path(), "wsl://Ubuntu", "0.59.9").unwrap();
367        assert!(!known_in(dir.path(), "wsl://Ubuntu"));
368        assert!(!known_in(dir.path(), "local"));
369    }
370
371    #[test]
372    fn a_hosts_platform_and_helper_version_are_kept_with_it() {
373        let dir = tempfile::tempdir().unwrap();
374        record_uname_in(dir.path(), "user@box", "Linux x86_64\n").unwrap();
375        assert!(!known_in(dir.path(), "user@box"), "a platform alone is not the helper");
376        remember_in(dir.path(), "user@box", "0.59.9").unwrap();
377        let (hosts, info) = all_in(dir.path());
378        assert_eq!(hosts, vec!["user@box".to_string()]);
379        let box_info = &info["user@box"];
380        assert_eq!(box_info.uname, "Linux x86_64");
381        assert_eq!(box_info.helper_version, "0.59.9");
382        assert!(box_info.seen_at_ms > 0);
383
384        // A newer helper replaces the version; a blank uname changes nothing.
385        remember_in(dir.path(), "user@box", "0.60.0").unwrap();
386        record_uname_in(dir.path(), "user@box", "  ").unwrap();
387        let (_, info) = all_in(dir.path());
388        assert_eq!(info["user@box"].helper_version, "0.60.0");
389        assert_eq!(info["user@box"].uname, "Linux x86_64");
390    }
391
392    #[test]
393    fn a_file_from_before_the_records_still_reads() {
394        let dir = tempfile::tempdir().unwrap();
395        std::fs::write(path_in(dir.path()), r#"{ "hosts": ["user@box"] }"#).unwrap();
396        assert!(known_in(dir.path(), "user@box"));
397        let (_, info) = all_in(dir.path());
398        assert!(info.is_empty());
399    }
400
401    /// One helper serves every name for the same account on the same machine:
402    /// installing through one name, or removing through another, says so for
403    /// all of them (#4513).
404    #[test]
405    fn a_helper_is_recorded_for_every_name_of_its_machine() {
406        let dir = tempfile::tempdir().unwrap();
407        let same = |n: &str| vec![if n == "box-key" { "box-pw" } else { "box-key" }.to_string()];
408        remember_on_machine_in(dir.path(), "box-key", &same("box-key"), "0.59.24").unwrap();
409        assert!(known_in(dir.path(), "box-key") && known_in(dir.path(), "box-pw"));
410        let (_, info) = all_in(dir.path());
411        assert_eq!(info["box-pw"].helper_version, "0.59.24");
412
413        forget_on_machine_in(dir.path(), "box-pw", &same("box-pw")).unwrap();
414        assert!(!known_in(dir.path(), "box-key") && !known_in(dir.path(), "box-pw"));
415
416        // Another machine's name is left alone.
417        remember_on_machine_in(dir.path(), "other", &[], "0.59.24").unwrap();
418        forget_on_machine_in(dir.path(), "box-key", &same("box-key")).unwrap();
419        assert!(known_in(dir.path(), "other"));
420    }
421
422    #[test]
423    fn a_machine_is_the_account_host_and_port_ssh_connects_to() {
424        let g = "user tester\nhostname 127.0.0.1\nport 2222\npubkeyauthentication no\n";
425        assert_eq!(machine_from_ssh_g(g).as_deref(), Some("tester@127.0.0.1:2222"));
426        // Host names compare without case; a missing part is no machine.
427        assert_eq!(machine_from_ssh_g("user me\nhostname Box.LAN\nport 22\n").as_deref(), Some("me@box.lan:22"));
428        assert_eq!(machine_from_ssh_g("hostname box\nport 22\n"), None);
429    }
430}