Skip to main content

agentmux_srv_core/backend/remote/
remotes.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Connectors → Remotes list (SPEC_REMOTES_PANE_2026_10_05.md §4.6): every remote
5//! machine AgentMux knows about, one record each, built from what srv already
6//! keeps:
7//! - the hosts named in `~/.ssh/config` (`ssh_config`);
8//! - the per-connection settings (`settings.json` → `connections`);
9//! - recent connections (`remote-recent.json`, kept here, §4.5);
10//! - WSL distributions (`wsl`);
11//! - each connection's status (`status`);
12//! - where the helper is, and each host's platform (`helper_hosts`);
13//! - which agents may use a host (`agent_access`);
14//! - the last count of durable sessions seen on a host (kept here).
15//!
16//! Building the list never opens an ssh connection.
17
18use std::collections::{BTreeMap, HashMap};
19use std::path::{Path, PathBuf};
20use std::sync::{Mutex, OnceLock};
21
22use serde::{Deserialize, Serialize};
23
24use super::helper_hosts::HostInfo;
25use super::ConnTarget;
26use crate::backend::mps::Broker;
27use crate::backend::rpc_types::{ConnStatus, RemoteHelper, RemotePlatform, RemoteRecord, RemoteStatus};
28use crate::backend::wconfig::ConnKeywords;
29
30// ── Recent connections (§4.5) ───────────────────────────────────────────────
31
32const RECENT_FILE: &str = "remote-recent.json";
33/// Recent connections kept; the least recently used goes first.
34pub const MAX_RECENT: usize = 20;
35/// A connection already recent is re-written at most this often.
36const TOUCH_EVERY_MS: u64 = 60_000;
37
38#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
39struct RecentFile {
40    #[serde(default)]
41    recent: Vec<RecentEntry>,
42}
43
44/// One SSH connection that has reached `connected`.
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
46pub struct RecentEntry {
47    /// Its canonical name (`ConnTarget::name`).
48    pub name: String,
49    pub first_used_ms: u64,
50    pub last_used_ms: u64,
51}
52
53static RECENT_LOCK: Mutex<()> = Mutex::new(());
54
55fn recent_path(config_home: &Path) -> PathBuf {
56    config_home.join(RECENT_FILE)
57}
58
59fn read_recent(path: &Path) -> RecentFile {
60    std::fs::read_to_string(path)
61        .ok()
62        .and_then(|s| serde_json::from_str(&s).ok())
63        .unwrap_or_default()
64}
65
66fn write_recent(config_home: &Path, file: &RecentFile) -> std::io::Result<()> {
67    use crate::backend::json_keep::{carry_unknown_keys, carry_unknown_keys_in_list, read_old, set_aside_if_unreadable};
68    let path = recent_path(config_home);
69    std::fs::create_dir_all(config_home)?;
70    // A file this build cannot read is copied aside before it is replaced; a key a newer AgentMux wrote, in the file or on an
71    // entry, is carried over from it.
72    set_aside_if_unreadable::<RecentFile>(&path);
73    let mut out = serde_json::to_value(file).unwrap_or_default();
74    if let Some(old) = read_old(&path) {
75        carry_unknown_keys(&old, &mut out, &["recent"]);
76        if let (Some(before), Some(now)) = (old.get("recent"), out.get_mut("recent")) {
77            carry_unknown_keys_in_list(before, now, "name", &["name", "first_used_ms", "last_used_ms"]);
78        }
79    }
80    let tmp = path.with_extension("json.tmp");
81    std::fs::write(&tmp, serde_json::to_vec_pretty(&out).unwrap_or_default())?;
82    std::fs::rename(&tmp, &path)
83}
84
85fn ssh_name(connection: &str) -> Option<String> {
86    match ConnTarget::parse(connection) {
87        Ok(t @ ConnTarget::Ssh(_)) => Some(t.name()),
88        _ => None,
89    }
90}
91
92/// Record that `connection` (SSH only) was used at `now_ms`. Returns whether the
93/// list changed (a new entry); touching an existing one is written at most
94/// once a minute.
95pub fn record_recent_in(config_home: &Path, connection: &str, now_ms: u64) -> std::io::Result<bool> {
96    let Some(name) = ssh_name(connection) else {
97        return Ok(false);
98    };
99    let _g = RECENT_LOCK.lock().unwrap_or_else(|e| e.into_inner());
100    let mut file = read_recent(&recent_path(config_home));
101    if let Some(entry) = file.recent.iter_mut().find(|e| e.name == name) {
102        if now_ms.saturating_sub(entry.last_used_ms) < TOUCH_EVERY_MS {
103            return Ok(false);
104        }
105        entry.last_used_ms = now_ms;
106        write_recent(config_home, &file)?;
107        return Ok(false);
108    }
109    file.recent.push(RecentEntry {
110        name,
111        first_used_ms: now_ms,
112        last_used_ms: now_ms,
113    });
114    if file.recent.len() > MAX_RECENT {
115        file.recent.sort_by(|a, b| b.last_used_ms.cmp(&a.last_used_ms));
116        file.recent.truncate(MAX_RECENT);
117    }
118    write_recent(config_home, &file)?;
119    Ok(true)
120}
121
122/// Forget `connection` from the recent list. Returns whether it was there.
123pub fn forget_recent_in(config_home: &Path, connection: &str) -> std::io::Result<bool> {
124    let Some(name) = ssh_name(connection) else {
125        return Ok(false);
126    };
127    let _g = RECENT_LOCK.lock().unwrap_or_else(|e| e.into_inner());
128    let mut file = read_recent(&recent_path(config_home));
129    let before = file.recent.len();
130    file.recent.retain(|e| e.name != name);
131    if file.recent.len() == before {
132        return Ok(false);
133    }
134    write_recent(config_home, &file)?;
135    Ok(true)
136}
137
138/// The recent list, most recently used first.
139pub fn recent_in(config_home: &Path) -> Vec<RecentEntry> {
140    let _g = RECENT_LOCK.lock().unwrap_or_else(|e| e.into_inner());
141    let mut recent = read_recent(&recent_path(config_home)).recent;
142    recent.sort_by(|a, b| b.last_used_ms.cmp(&a.last_used_ms));
143    recent
144}
145
146#[cfg(not(any(test, feature = "test-support")))]
147use agentmux_common::time::now_ms_u64 as now_ms;
148
149/// [`record_recent_in`] under this instance's config dir, now. Best effort.
150#[cfg(not(any(test, feature = "test-support")))]
151pub fn record_recent(connection: &str) -> bool {
152    record_recent_in(&crate::backend::base::get_mux_config_dir(), connection, now_ms()).unwrap_or_else(|e| {
153        tracing::warn!(connection = %connection, error = %e, "could not record a recent connection");
154        false
155    })
156}
157
158/// [`forget_recent_in`] under this instance's config dir.
159pub fn forget_recent(connection: &str) -> std::io::Result<bool> {
160    forget_recent_in(&crate::backend::base::get_mux_config_dir(), connection)
161}
162
163// ── Durable session counts (§4.6) ───────────────────────────────────────────
164
165fn session_counts() -> &'static Mutex<HashMap<String, u32>> {
166    static COUNTS: OnceLock<Mutex<HashMap<String, u32>>> = OnceLock::new();
167    COUNTS.get_or_init(|| Mutex::new(HashMap::new()))
168}
169
170/// Remember how many durable sessions `connection`'s host had when last
171/// listed (the list never opens ssh to count them).
172pub fn note_sessions(connection: &str, count: usize) {
173    if let Some(name) = ssh_name(connection) {
174        session_counts()
175            .lock()
176            .unwrap_or_else(|e| e.into_inner())
177            .insert(name, count as u32);
178    }
179}
180
181// ── Settings writes (§4.3) ──────────────────────────────────────────────────
182
183/// Apply `values` to `connection`'s entry in the raw `connections` object of
184/// `settings.json`: a `null` removes a key, an entry left empty is removed.
185/// Works on the raw JSON, so keys AgentMux doesn't know survive untouched.
186pub fn apply_connection_values(
187    connections: &mut serde_json::Map<String, serde_json::Value>,
188    connection: &str,
189    values: &serde_json::Map<String, serde_json::Value>,
190) {
191    let name = connection.trim().to_string();
192    let mut entry = match connections.remove(&name) {
193        Some(serde_json::Value::Object(map)) => map,
194        _ => serde_json::Map::new(),
195    };
196    for (key, value) in values {
197        if value.is_null() {
198            entry.remove(key);
199        } else {
200            entry.insert(key.clone(), value.clone());
201        }
202    }
203    if !entry.is_empty() {
204        connections.insert(name, serde_json::Value::Object(entry));
205    }
206}
207
208/// Refuse an edit that would leave `connection`'s entry unreadable (a string
209/// where `display:pinned` wants a boolean, say): the write would land on disk
210/// while the live config silently kept the old values.
211pub fn check_connection_entry(
212    connections: &serde_json::Map<String, serde_json::Value>,
213    connection: &str,
214) -> Result<(), String> {
215    let name = connection.trim();
216    match connections.get(name) {
217        None => Ok(()),
218        Some(entry) => serde_json::from_value::<ConnKeywords>(entry.clone())
219            .map(|_| ())
220            .map_err(|e| format!("invalid setting for {name}: {e}")),
221    }
222}
223
224/// Tell every open Connectors → Remotes its list changed.
225pub fn publish_change(broker: &Broker) {
226    broker.publish_event::<crate::backend::mps_events::RemotesChanged>(&(), vec![], 0);
227}
228
229// ── The list (§4.6) ─────────────────────────────────────────────────────────
230
231/// Everything [`build`] reads, gathered by [`list`].
232#[derive(Debug, Clone, Default)]
233pub struct Inputs {
234    pub ssh_config_hosts: Vec<String>,
235    pub wsl_distros: Vec<String>,
236    pub settings: HashMap<String, ConnKeywords>,
237    pub recent: Vec<RecentEntry>,
238    pub statuses: Vec<ConnStatus>,
239    pub helper_hosts: Vec<String>,
240    pub host_info: BTreeMap<String, HostInfo>,
241    pub sessions: HashMap<String, u32>,
242    pub grants: Vec<(String, String)>,
243}
244
245/// `uname -sm` → platform.
246pub fn platform_of(uname: &str) -> Option<RemotePlatform> {
247    let mut words = uname.split_whitespace();
248    let os = words.next()?;
249    let arch = words.next().unwrap_or_default();
250    let os = match os {
251        "Linux" => "linux".to_string(),
252        "Darwin" => "macos".to_string(),
253        other => other.to_ascii_lowercase(),
254    };
255    let arch = match arch {
256        "x86_64" | "amd64" => "x86_64".to_string(),
257        "aarch64" | "arm64" => "arm64".to_string(),
258        other => other.to_string(),
259    };
260    Some(RemotePlatform { os, arch })
261}
262
263/// The canonical name and kind of a connection name, or `None` for `local`.
264fn identify(connection: &str) -> Option<(String, &'static str)> {
265    match ConnTarget::parse(connection).ok()? {
266        ConnTarget::Local => None,
267        t @ ConnTarget::Wsl(_) => Some((t.name(), "wsl")),
268        t @ ConnTarget::Ssh(_) => Some((t.name(), "ssh")),
269    }
270}
271
272/// One record per remote, by name (the pane sorts them into sections).
273pub fn build(inputs: &Inputs) -> Vec<RemoteRecord> {
274    // name → (kind, sources)
275    let mut found: BTreeMap<String, (&'static str, Vec<&'static str>)> = BTreeMap::new();
276    let mut add = |connection: &str, source: &'static str| {
277        if let Some((name, kind)) = identify(connection) {
278            let entry = found.entry(name).or_insert((kind, Vec::new()));
279            if !entry.1.contains(&source) {
280                entry.1.push(source);
281            }
282        }
283    };
284    for host in &inputs.ssh_config_hosts {
285        add(host, "ssh_config");
286    }
287    for name in inputs.settings.keys() {
288        add(name, "settings");
289    }
290    for entry in &inputs.recent {
291        add(&entry.name, "recent");
292    }
293    for distro in &inputs.wsl_distros {
294        add(&format!("wsl://{distro}"), "wsl");
295    }
296
297    let same = |a: &str, b: &str| super::conn::same_connection(a, b);
298    found
299        .into_iter()
300        .map(|(name, (kind, sources))| {
301            let status = inputs
302                .statuses
303                .iter()
304                .find(|s| same(&s.connection, &name))
305                .map(|s| RemoteStatus {
306                    state: s.status.clone(),
307                    error: s.error.clone(),
308                })
309                .unwrap_or_else(|| RemoteStatus {
310                    state: super::status::state::DISCONNECTED.to_string(),
311                    error: String::new(),
312                });
313            let settings = inputs.settings.iter().find(|(k, _)| same(k, &name)).map(|(_, v)| v);
314            let info = inputs.host_info.get(&name);
315            let platform = info.and_then(|i| platform_of(&i.uname));
316            let helper = if kind == "wsl" {
317                RemoteHelper { state: "none".to_string(), version: String::new(), installed: false }
318            } else {
319                let version = info.map(|i| i.helper_version.clone()).unwrap_or_default();
320                let state = if settings.is_some_and(|s| s.conn_helper == "never") {
321                    "never"
322                } else if inputs.helper_hosts.contains(&name) {
323                    "installed"
324                } else if info.is_some_and(|i| {
325                    !i.uname.is_empty() && super::helper_install::target_for(&i.uname).is_none()
326                }) {
327                    "unsupported"
328                } else {
329                    "absent"
330                };
331                let installed = inputs.helper_hosts.contains(&name);
332                let version = if installed { version } else { String::new() };
333                RemoteHelper { state: state.to_string(), version, installed }
334            };
335            let mut agents: Vec<String> = inputs
336                .grants
337                .iter()
338                .filter(|(_, conn)| same(conn, &name))
339                .map(|(agent, _)| agent.clone())
340                .collect();
341            agents.sort();
342            agents.dedup();
343            RemoteRecord {
344                sessions: inputs.sessions.get(&name).copied(),
345                last_used_ms: inputs.recent.iter().find(|e| e.name == name).map(|e| e.last_used_ms),
346                settings: settings
347                    .and_then(|s| serde_json::to_value(s).ok())
348                    .unwrap_or_else(|| serde_json::json!({})),
349                name,
350                kind: kind.to_string(),
351                sources: sources.into_iter().map(str::to_string).collect(),
352                status,
353                platform,
354                helper,
355                agents,
356            }
357        })
358        .collect()
359}
360
361/// The list now, for `RemotesList`. `settings` is `FullConfigType::connections`.
362pub async fn list(settings: HashMap<String, ConnKeywords>) -> Vec<RemoteRecord> {
363    let ssh_config_hosts = tokio::task::spawn_blocking(super::ssh_config::hosts)
364        .await
365        .unwrap_or_default();
366    let wsl_distros = super::wsl::list_cached().await;
367    let config_home = crate::backend::base::get_mux_config_dir();
368    let (helper_hosts, host_info) = super::helper_hosts::all_in(&config_home);
369    let inputs = Inputs {
370        ssh_config_hosts,
371        wsl_distros,
372        settings,
373        recent: recent_in(&config_home),
374        statuses: super::status::all(),
375        helper_hosts,
376        host_info,
377        sessions: session_counts().lock().unwrap_or_else(|e| e.into_inner()).clone(),
378        grants: super::agent_access::all_in(&config_home),
379    };
380    build(&inputs)
381}
382
383#[cfg(test)]
384mod tests {
385    use super::*;
386
387    fn status(connection: &str, state: &str) -> ConnStatus {
388        ConnStatus {
389            status: state.to_string(),
390            connection: connection.to_string(),
391            connected: state == "connected",
392            hasconnected: true,
393            activeconnnum: 0,
394            error: String::new(),
395        }
396    }
397
398    fn named<'a>(records: &'a [RemoteRecord], name: &str) -> &'a RemoteRecord {
399        records.iter().find(|r| r.name == name).unwrap_or_else(|| panic!("no record for {name}"))
400    }
401
402    #[test]
403    fn one_record_per_remote_whatever_lists_it() {
404        let mut settings = HashMap::new();
405        settings.insert("db1".to_string(), ConnKeywords::default());
406        settings.insert("local".to_string(), ConnKeywords::default());
407        let inputs = Inputs {
408            ssh_config_hosts: vec!["db1".into(), "web".into()],
409            wsl_distros: vec!["Ubuntu".into()],
410            settings,
411            recent: vec![
412                RecentEntry { name: "db1".into(), first_used_ms: 1, last_used_ms: 5 },
413                RecentEntry { name: "me@10.0.0.7".into(), first_used_ms: 2, last_used_ms: 9 },
414            ],
415            ..Default::default()
416        };
417        let records = build(&inputs);
418        let names: Vec<&str> = records.iter().map(|r| r.name.as_str()).collect();
419        assert_eq!(names, ["db1", "me@10.0.0.7", "web", "wsl://Ubuntu"], "local is never a remote");
420        assert_eq!(named(&records, "db1").sources, ["ssh_config", "settings", "recent"]);
421        assert_eq!(named(&records, "me@10.0.0.7").sources, ["recent"]);
422        assert_eq!(named(&records, "me@10.0.0.7").last_used_ms, Some(9));
423        let wsl = named(&records, "wsl://Ubuntu");
424        assert_eq!((wsl.kind.as_str(), wsl.helper.state.as_str()), ("wsl", "none"));
425        assert_eq!(named(&records, "web").status.state, "disconnected", "no status yet");
426    }
427
428    #[test]
429    fn a_record_carries_status_platform_helper_sessions_and_agents() {
430        let mut host_info = BTreeMap::new();
431        host_info.insert(
432            "db1".to_string(),
433            HostInfo { uname: "Linux aarch64".into(), helper_version: "0.59.9".into(), seen_at_ms: 1 },
434        );
435        host_info.insert("router".to_string(), HostInfo { uname: "FreeBSD amd64".into(), ..Default::default() });
436        let mut sessions = HashMap::new();
437        sessions.insert("db1".to_string(), 2);
438        let inputs = Inputs {
439            ssh_config_hosts: vec!["db1".into(), "router".into(), "web".into()],
440            statuses: vec![status("db1", "connected")],
441            helper_hosts: vec!["db1".into()],
442            host_info,
443            sessions,
444            grants: vec![("korp".into(), "db1".into()), ("camper".into(), " db1".into()), ("korp".into(), "web".into())],
445            ..Default::default()
446        };
447        let records = build(&inputs);
448        let db1 = named(&records, "db1");
449        assert_eq!(db1.status.state, "connected");
450        assert_eq!(db1.platform, Some(RemotePlatform { os: "linux".into(), arch: "arm64".into() }));
451        assert_eq!((db1.helper.state.as_str(), db1.helper.version.as_str()), ("installed", "0.59.9"));
452        assert_eq!(db1.sessions, Some(2));
453        assert_eq!(db1.agents, ["camper", "korp"]);
454        assert_eq!(named(&records, "router").helper.state, "unsupported", "no build for FreeBSD");
455        let web = named(&records, "web");
456        assert_eq!((web.helper.state.as_str(), web.sessions, web.platform.clone()), ("absent", None, None));
457    }
458
459    #[test]
460    fn never_wins_over_an_installed_helper() {
461        let mut settings = HashMap::new();
462        settings.insert("db1".to_string(), ConnKeywords { conn_helper: "never".into(), ..Default::default() });
463        let inputs = Inputs {
464            ssh_config_hosts: vec!["db1".into()],
465            settings,
466            helper_hosts: vec!["db1".into()],
467            ..Default::default()
468        };
469        let db1 = &build(&inputs)[0];
470        assert_eq!(db1.helper.state, "never");
471        assert!(db1.helper.installed, "Never stops new installs; the one there can still be removed");
472    }
473
474    #[test]
475    fn a_records_settings_are_its_stored_keys_only() {
476        let mut settings = HashMap::new();
477        settings.insert(
478            "db1".to_string(),
479            ConnKeywords {
480                display_name: "prod-db".into(),
481                display_color: "#e5484d".into(),
482                display_pinned: Some(true),
483                ..Default::default()
484            },
485        );
486        let inputs = Inputs { settings, ..Default::default() };
487        let db1 = &build(&inputs)[0];
488        assert_eq!(
489            db1.settings,
490            serde_json::json!({ "display:name": "prod-db", "display:color": "#e5484d", "display:pinned": true })
491        );
492    }
493
494    #[test]
495    fn platforms_read_from_uname() {
496        assert_eq!(platform_of("Darwin arm64"), Some(RemotePlatform { os: "macos".into(), arch: "arm64".into() }));
497        assert_eq!(platform_of("Linux x86_64\n"), Some(RemotePlatform { os: "linux".into(), arch: "x86_64".into() }));
498        assert_eq!(platform_of(""), None);
499    }
500
501    #[test]
502    fn recent_keeps_ssh_connections_touched_at_most_once_a_minute() {
503        let dir = tempfile::tempdir().unwrap();
504        let home = dir.path();
505        assert!(record_recent_in(home, "me@box", 1_000).unwrap(), "new");
506        assert!(!record_recent_in(home, " me@box ", 2_000).unwrap(), "same host, same minute");
507        assert_eq!(recent_in(home)[0].last_used_ms, 1_000, "not re-written within a minute");
508        assert!(!record_recent_in(home, "me@box", 70_000).unwrap());
509        assert_eq!(recent_in(home)[0].last_used_ms, 70_000);
510        assert!(!record_recent_in(home, "wsl://Ubuntu", 1).unwrap(), "not SSH");
511        assert!(!record_recent_in(home, "local", 1).unwrap());
512        assert_eq!(recent_in(home).len(), 1);
513
514        assert!(forget_recent_in(home, "me@box").unwrap());
515        assert!(!forget_recent_in(home, "me@box").unwrap());
516        assert!(recent_in(home).is_empty());
517    }
518
519    #[test]
520    fn recent_drops_the_least_recently_used_past_the_limit() {
521        let dir = tempfile::tempdir().unwrap();
522        for i in 0..(MAX_RECENT as u64 + 3) {
523            record_recent_in(dir.path(), &format!("me@host{i}"), 1_000 * (i + 1)).unwrap();
524        }
525        let recent = recent_in(dir.path());
526        assert_eq!(recent.len(), MAX_RECENT);
527        assert_eq!(recent[0].name, format!("me@host{}", MAX_RECENT + 2), "newest first");
528        assert!(!recent.iter().any(|e| e.name == "me@host0"), "oldest dropped");
529    }
530
531    #[test]
532    fn a_settings_write_changes_only_the_keys_given() {
533        let mut connections = serde_json::json!({
534            "db1": { "display:name": "old", "ssh:user": "admin", "custom:key": 7 },
535            "web": { "term:theme": "red" }
536        })
537        .as_object()
538        .unwrap()
539        .clone();
540        let values = serde_json::json!({ "display:name": "prod-db", "display:color": "#e5484d", "term:theme": null })
541            .as_object()
542            .unwrap()
543            .clone();
544        apply_connection_values(&mut connections, " db1 ", &values);
545        assert_eq!(
546            connections["db1"],
547            serde_json::json!({ "display:name": "prod-db", "display:color": "#e5484d", "ssh:user": "admin", "custom:key": 7 }),
548            "keys AgentMux doesn't know are kept"
549        );
550        assert_eq!(connections["web"], serde_json::json!({ "term:theme": "red" }), "other connections untouched");
551
552        // Removing the last key removes the entry.
553        let clear = serde_json::json!({ "term:theme": null }).as_object().unwrap().clone();
554        apply_connection_values(&mut connections, "web", &clear);
555        assert!(!connections.contains_key("web"));
556
557        // A new connection.
558        let pin = serde_json::json!({ "display:pinned": true }).as_object().unwrap().clone();
559        apply_connection_values(&mut connections, "me@box", &pin);
560        assert_eq!(connections["me@box"], serde_json::json!({ "display:pinned": true }));
561    }
562
563    #[test]
564    fn an_edit_that_would_not_parse_is_refused() {
565        let connections = serde_json::json!({
566            "ok": { "display:pinned": true, "custom:key": 7 },
567            "bad": { "display:pinned": "yes" }
568        })
569        .as_object()
570        .unwrap()
571        .clone();
572        assert!(check_connection_entry(&connections, "ok").is_ok(), "unknown keys are fine");
573        assert!(check_connection_entry(&connections, "gone").is_ok(), "a removed entry is fine");
574        let err = check_connection_entry(&connections, " bad ").unwrap_err();
575        assert!(err.contains("bad"), "{err}");
576    }
577}