Skip to main content

agentmux_srv/server/
cli_version.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The version a CLI reports for `--version`, asked once per CLI file instead of once per call.
5//!
6//! `ResolveCli` runs for every agent that opens (and resumes), and each run spawned
7//! `<cli> --version`: a node process that takes 270-300 ms of CPU when the machine is idle
8//! (Area54, `claude --version`, warm; 3.2 s the first time) and more than the 5 s timeout
9//! when it isn't. Resuming a window of agents on a saturated machine spawned them all at once,
10//! most timed out ("get_cli_version timed out after 5s", narko 0.60.6), and every agent waited
11//! on its own probe before it could start. A CLI's version only changes when its file does.
12
13use std::collections::HashMap;
14use std::future::Future;
15use std::sync::{Arc, LazyLock, Mutex};
16use std::time::{Duration, Instant, SystemTime};
17
18/// What a version that couldn't be read reads as.
19pub(crate) const UNKNOWN: &str = "unknown";
20
21/// A read version is asked for again after this long, in case the file changed without its
22/// modified time or size (an in-place update of a shim).
23const TTL: Duration = Duration::from_secs(600);
24/// A probe that failed (timed out, exited non-zero) is not repeated for this long: the callers
25/// that queued behind it share its answer instead of each timing out in turn.
26const RETRY_AFTER_FAILURE: Duration = Duration::from_secs(2);
27
28/// One CLI file as it is now: when it is replaced, it is a different key.
29#[derive(Clone, PartialEq, Eq, Hash)]
30struct Key {
31    path: String,
32    modified: Option<SystemTime>,
33    len: u64,
34}
35
36#[derive(Default)]
37struct Slot {
38    version: Option<(String, Instant)>,
39    failed_at: Option<Instant>,
40}
41
42static SLOTS: LazyLock<Mutex<HashMap<Key, Arc<tokio::sync::Mutex<Slot>>>>> = LazyLock::new(Default::default);
43
44/// The version of the CLI at `cli_path`: cached while the file is unchanged, and asked for by
45/// one `probe` at a time (callers for the same file wait for it). `probe` returns `None` when it
46/// couldn't read one; that answers `UNKNOWN` and is never cached. A path with no file behind it
47/// (a bare command name) is probed every time.
48pub(crate) async fn cached_version<F, Fut>(cli_path: &str, probe: F) -> String
49where
50    F: FnOnce() -> Fut,
51    Fut: Future<Output = Option<String>>,
52{
53    let Ok(meta) = tokio::fs::metadata(cli_path).await else {
54        return probe().await.unwrap_or_else(|| UNKNOWN.to_string());
55    };
56    let key = Key { path: cli_path.to_string(), modified: meta.modified().ok(), len: meta.len() };
57    let slot = {
58        let mut slots = SLOTS.lock().unwrap();
59        // A replaced file leaves its old key behind; drop it.
60        slots.retain(|k, _| k.path != key.path || *k == key);
61        slots.entry(key).or_default().clone()
62    };
63    let mut slot = slot.lock().await;
64    if let Some((version, at)) = &slot.version {
65        if at.elapsed() < TTL {
66            return version.clone();
67        }
68    }
69    if slot.failed_at.is_some_and(|at| at.elapsed() < RETRY_AFTER_FAILURE) {
70        return UNKNOWN.to_string();
71    }
72    match probe().await {
73        Some(version) => {
74            slot.version = Some((version.clone(), Instant::now()));
75            slot.failed_at = None;
76            version
77        }
78        None => {
79            slot.failed_at = Some(Instant::now());
80            UNKNOWN.to_string()
81        }
82    }
83}
84
85#[cfg(test)]
86mod tests {
87    use super::*;
88    use std::sync::atomic::{AtomicUsize, Ordering};
89
90    /// A CLI file to ask about, and a probe that counts how often it is run.
91    fn cli_file(content: &str) -> (tempfile::TempDir, String) {
92        let dir = tempfile::tempdir().unwrap();
93        let path = dir.path().join("cli");
94        std::fs::write(&path, content).unwrap();
95        let path = path.to_string_lossy().into_owned();
96        (dir, path)
97    }
98
99    async fn probe_slowly(runs: &AtomicUsize, answer: Option<&str>) -> Option<String> {
100        runs.fetch_add(1, Ordering::SeqCst);
101        tokio::time::sleep(Duration::from_millis(50)).await;
102        answer.map(str::to_string)
103    }
104
105    /// The agents of a window resuming together, all on one CLI: one probe, not one each (before:
106    /// `get_cli_version` spawned the CLI for every call).
107    #[tokio::test]
108    async fn eight_agents_opening_at_once_run_one_probe() {
109        let (_dir, path) = cli_file("v1");
110        let runs = AtomicUsize::new(0);
111        let versions = futures_util::future::join_all((0..8).map(|_| cached_version(&path, || probe_slowly(&runs, Some("2.1.288"))))).await;
112        assert_eq!(runs.load(Ordering::SeqCst), 1);
113        assert!(versions.iter().all(|v| v == "2.1.288"));
114    }
115
116    #[tokio::test]
117    async fn the_next_agent_to_open_does_not_probe_at_all() {
118        let (_dir, path) = cli_file("v1");
119        let runs = AtomicUsize::new(0);
120        for _ in 0..5 {
121            assert_eq!(cached_version(&path, || probe_slowly(&runs, Some("2.1.288"))).await, "2.1.288");
122        }
123        assert_eq!(runs.load(Ordering::SeqCst), 1);
124    }
125
126    #[tokio::test]
127    async fn a_replaced_cli_file_is_asked_again() {
128        let (_dir, path) = cli_file("v1");
129        let runs = AtomicUsize::new(0);
130        assert_eq!(cached_version(&path, || probe_slowly(&runs, Some("1.0.0"))).await, "1.0.0");
131        std::fs::write(&path, "a longer second version").unwrap();
132        assert_eq!(cached_version(&path, || probe_slowly(&runs, Some("2.0.0"))).await, "2.0.0");
133        assert_eq!(runs.load(Ordering::SeqCst), 2);
134    }
135
136    /// A probe that timed out is not cached as "unknown" forever, and the callers queued behind it
137    /// don't each wait out a probe of their own.
138    #[tokio::test]
139    async fn a_failed_probe_is_shared_then_retried() {
140        let (_dir, path) = cli_file("v1");
141        let runs = AtomicUsize::new(0);
142        let versions = futures_util::future::join_all((0..4).map(|_| cached_version(&path, || probe_slowly(&runs, None)))).await;
143        assert_eq!(runs.load(Ordering::SeqCst), 1);
144        assert!(versions.iter().all(|v| v == UNKNOWN));
145
146        tokio::time::sleep(RETRY_AFTER_FAILURE + Duration::from_millis(50)).await;
147        assert_eq!(cached_version(&path, || probe_slowly(&runs, Some("2.1.288"))).await, "2.1.288");
148        assert_eq!(runs.load(Ordering::SeqCst), 2);
149    }
150
151    #[tokio::test]
152    async fn a_bare_command_name_is_probed_every_time() {
153        let runs = AtomicUsize::new(0);
154        for _ in 0..3 {
155            cached_version("no-such-file-claude", || probe_slowly(&runs, Some("1.0.0"))).await;
156        }
157        assert_eq!(runs.load(Ordering::SeqCst), 3);
158    }
159}