Skip to main content

lean_ctx/core/
version_check.rs

1use serde::{Deserialize, Serialize};
2use std::path::PathBuf;
3use std::time::{SystemTime, UNIX_EPOCH};
4
5const GITHUB_API_RELEASES: &str = "https://api.github.com/repos/yvgude/lean-ctx/releases/latest";
6const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");
7const CACHE_TTL_SECS: u64 = 24 * 60 * 60;
8
9#[derive(Serialize, Deserialize)]
10struct VersionCache {
11    latest: String,
12    checked_at: u64,
13}
14
15fn cache_path() -> Option<PathBuf> {
16    crate::core::paths::cache_dir()
17        .ok()
18        .map(|d| d.join("latest-version.json"))
19}
20
21fn now_secs() -> u64 {
22    SystemTime::now()
23        .duration_since(UNIX_EPOCH)
24        .map_or(0, |d| d.as_secs())
25}
26
27fn read_cache() -> Option<VersionCache> {
28    let path = cache_path()?;
29    let content = std::fs::read_to_string(path).ok()?;
30    serde_json::from_str(&content).ok()
31}
32
33fn write_cache(latest: &str) {
34    if let Some(path) = cache_path() {
35        let cache = VersionCache {
36            latest: latest.to_string(),
37            checked_at: now_secs(),
38        };
39        if let Ok(json) = serde_json::to_string(&cache) {
40            let _ = std::fs::write(path, json);
41        }
42    }
43}
44
45fn is_cache_stale(cache: &VersionCache) -> bool {
46    let age = now_secs().saturating_sub(cache.checked_at);
47    age > CACHE_TTL_SECS
48}
49
50fn fetch_latest_version() -> Result<String, String> {
51    let agent = crate::core::http_client::ureq_agent(
52        ureq::config::Config::builder()
53            .tls_config(crate::core::http_client::platform_tls_config())
54            .timeout_global(Some(std::time::Duration::from_secs(5)))
55            .build(),
56    );
57
58    let body = agent
59        .get(GITHUB_API_RELEASES)
60        .header("User-Agent", &format!("lean-ctx/{CURRENT_VERSION}"))
61        .header("Accept", "application/vnd.github.v3+json")
62        .call()
63        .map_err(|e| e.to_string())?
64        .into_body()
65        .read_to_string()
66        .map_err(|e| e.to_string())?;
67
68    let release: serde_json::Value = serde_json::from_str(&body).map_err(|e| e.to_string())?;
69    let tag = release["tag_name"]
70        .as_str()
71        .ok_or_else(|| "missing tag_name in GitHub releases response".to_string())?;
72
73    let version = tag.trim().trim_start_matches('v').to_string();
74    if version.is_empty() || !version.contains('.') {
75        return Err("invalid version format".to_string());
76    }
77    Ok(version)
78}
79
80fn is_newer(latest: &str, current: &str) -> bool {
81    let parse =
82        |v: &str| -> Vec<u32> { v.split('.').filter_map(|p| p.parse::<u32>().ok()).collect() };
83    parse(latest) > parse(current)
84}
85
86/// Spawn a background thread to fetch latest version from GitHub Releases
87/// and write the result to the lean-ctx data dir (`latest-version.json`).
88/// Non-blocking, fire-and-forget. Skips if cache is fresh (<24h).
89/// Respects `update_check_disabled` config and `LEAN_CTX_NO_UPDATE_CHECK` env var.
90pub fn check_background() {
91    let cfg = super::config::Config::load();
92    if cfg.update_check_disabled_effective() {
93        return;
94    }
95
96    let cache = read_cache();
97    if let Some(ref c) = cache
98        && !is_cache_stale(c)
99    {
100        return;
101    }
102
103    std::thread::spawn(|| {
104        if let Ok(latest) = fetch_latest_version() {
105            write_cache(&latest);
106        }
107    });
108}
109
110/// Returns a formatted yellow update banner if a newer version is available.
111/// Reads only the local cache file — zero network calls, zero delay.
112pub fn get_update_banner() -> Option<String> {
113    let cache = read_cache()?;
114    if is_newer(&cache.latest, CURRENT_VERSION) {
115        Some(format!(
116            "  \x1b[33m\x1b[1m\u{27F3} Update available: v{CURRENT_VERSION} \u{2192} v{}\x1b[0m  \x1b[2m\u{2014} run:\x1b[0m \x1b[1mlean-ctx update\x1b[0m",
117            cache.latest
118        ))
119    } else {
120        None
121    }
122}
123
124/// Returns version info as JSON for the dashboard /api/version endpoint.
125/// Includes the cache age so the UI can be honest about staleness (#563).
126pub fn version_info_json() -> String {
127    let cache = read_cache();
128    let (latest, update_available, age_secs) = match cache {
129        Some(c) => {
130            let newer = is_newer(&c.latest, CURRENT_VERSION);
131            let age = now_secs().saturating_sub(c.checked_at);
132            (c.latest, newer, Some(age))
133        }
134        None => (CURRENT_VERSION.to_string(), false, None),
135    };
136
137    let age_json = age_secs.map_or("null".to_string(), |a| a.to_string());
138    format!(
139        r#"{{"current":"{CURRENT_VERSION}","latest":"{latest}","update_available":{update_available},"checked_age_secs":{age_json}}}"#
140    )
141}
142
143use std::sync::atomic::{AtomicBool, Ordering};
144
145static NOTIFIED_THIS_SESSION: AtomicBool = AtomicBool::new(false);
146
147/// Returns a one-line update notification if available, exactly once per session.
148/// Safe to call from any tool — returns None after first notification.
149pub fn session_update_hint() -> Option<String> {
150    if NOTIFIED_THIS_SESSION.swap(true, Ordering::Relaxed) {
151        return None;
152    }
153
154    let cache = read_cache()?;
155    if !is_newer(&cache.latest, CURRENT_VERSION) {
156        return None;
157    }
158
159    Some(format!(
160        "[lean-ctx] Update available: v{CURRENT_VERSION} → v{} (run: lean-ctx update)",
161        cache.latest
162    ))
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168
169    #[test]
170    fn newer_version_detected() {
171        assert!(is_newer("2.9.14", "2.9.13"));
172        assert!(is_newer("3.0.0", "2.9.99"));
173        assert!(is_newer("2.10.0", "2.9.14"));
174    }
175
176    #[test]
177    fn same_or_older_not_newer() {
178        assert!(!is_newer("2.9.13", "2.9.13"));
179        assert!(!is_newer("2.9.12", "2.9.13"));
180        assert!(!is_newer("1.0.0", "2.9.13"));
181    }
182
183    #[test]
184    fn cache_fresh_within_ttl() {
185        let fresh = VersionCache {
186            latest: "2.9.14".to_string(),
187            checked_at: now_secs(),
188        };
189        assert!(!is_cache_stale(&fresh));
190    }
191
192    #[test]
193    fn cache_stale_after_ttl() {
194        let old = VersionCache {
195            latest: "2.9.14".to_string(),
196            checked_at: now_secs() - CACHE_TTL_SECS - 1,
197        };
198        assert!(is_cache_stale(&old));
199    }
200
201    #[test]
202    fn version_json_has_required_fields() {
203        let json = version_info_json();
204        assert!(json.contains("current"));
205        assert!(json.contains("latest"));
206        assert!(json.contains("update_available"));
207        assert!(json.contains("checked_age_secs"));
208    }
209
210    #[test]
211    fn banner_none_for_current_version() {
212        assert!(!is_newer(CURRENT_VERSION, CURRENT_VERSION));
213    }
214
215    #[test]
216    fn session_hint_returns_once() {
217        NOTIFIED_THIS_SESSION.store(false, Ordering::Relaxed);
218        // No cache file in test env, so we verify the atomic gate directly
219        NOTIFIED_THIS_SESSION.store(false, Ordering::Relaxed);
220        let first_swap = NOTIFIED_THIS_SESSION.swap(true, Ordering::Relaxed);
221        assert!(
222            !first_swap,
223            "First call should get false (not yet notified)"
224        );
225        let second_swap = NOTIFIED_THIS_SESSION.swap(true, Ordering::Relaxed);
226        assert!(
227            second_swap,
228            "Second call should get true (already notified)"
229        );
230    }
231}