Skip to main content

paper/core/
update_state.rs

1//! Shared auto-update contract: opt-out check, version order, `update.state`.
2
3use super::config::Config;
4use super::remote_config::{write_atomic, RemoteConfig};
5use serde::{Deserialize, Serialize};
6use std::io;
7use std::path::Path;
8
9const STATE_FILE: &str = "update.state";
10
11/// False when `PAPER_NO_AUTO_UPDATE` is set (non-empty, not "0") or `auto_update = false`.
12pub fn auto_update_enabled(config: &Config) -> bool {
13    let env_off = std::env::var("PAPER_NO_AUTO_UPDATE").is_ok_and(|v| !v.is_empty() && v != "0");
14    !env_off && config.auto_update != Some(false)
15}
16
17/// Numeric comparison of `major.minor.patch`; a pre-release suffix sorts low.
18pub fn version_newer(candidate: &str, current: &str) -> bool {
19    let parse = |value: &str| -> (u64, u64, u64, bool) {
20        let (core, pre) = match value.split_once('-') {
21            Some((core, _)) => (core, true),
22            None => (value, false),
23        };
24        let mut parts = core.split('.').map(|part| part.parse::<u64>().unwrap_or(0));
25        (
26            parts.next().unwrap_or(0),
27            parts.next().unwrap_or(0),
28            parts.next().unwrap_or(0),
29            pre,
30        )
31    };
32    let (a, b) = (parse(candidate), parse(current));
33    (a.0, a.1, a.2) > (b.0, b.1, b.2) || ((a.0, a.1, a.2) == (b.0, b.1, b.2) && b.3 && !a.3)
34}
35
36/// Last auto-update outcome, written by the daemon and read by doctor, CLI and MCP.
37/// `outcome` is "updated" | "up_to_date" | "unavailable" | "failed" | "opted_out" | "offline".
38#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
39pub struct UpdateState {
40    pub outcome: String,
41    pub approved: Option<String>,
42    pub method: String,
43    #[serde(default)]
44    pub manual_command: Option<String>,
45    #[serde(default)]
46    pub detail: Option<String>,
47    /// RFC 3339 timestamp.
48    pub at: String,
49}
50
51/// Best effort: missing or garbled means `None`.
52pub fn read_update_state(dir: &Path) -> Option<UpdateState> {
53    toml::from_str(&std::fs::read_to_string(dir.join(STATE_FILE)).ok()?).ok()
54}
55
56pub fn write_update_state(dir: &Path, s: &UpdateState) -> io::Result<()> {
57    std::fs::create_dir_all(dir)?;
58    let body = toml::to_string(s).map_err(io::Error::other)?;
59    write_atomic(dir, STATE_FILE, body.as_bytes())
60}
61
62/// What the surfaces (doctor, CLI note, MCP) say about updates; reads local files only.
63pub struct UpdateSummary {
64    pub current: &'static str,
65    /// The signed-approved version, only when newer than `current`.
66    pub approved: Option<String>,
67    /// Outcome recorded for that approved version.
68    pub state: Option<UpdateState>,
69    pub auto_update: bool,
70}
71
72impl UpdateSummary {
73    pub fn load(dir: &Path, config: &Config, remote: Option<&RemoteConfig>) -> Self {
74        let current = env!("CARGO_PKG_VERSION");
75        let approved = remote
76            .and_then(|r| r.update.as_ref())
77            .map(|u| u.version.clone())
78            .filter(|v| version_newer(v, current));
79        let state =
80            read_update_state(dir).filter(|s| s.approved.is_some() && s.approved == approved);
81        Self {
82            current,
83            approved,
84            state,
85            auto_update: auto_update_enabled(config),
86        }
87    }
88
89    pub fn outcome(&self) -> Option<&str> {
90        self.state.as_ref().map(|s| s.outcome.as_str())
91    }
92
93    /// Recorded manual command, else the generic one.
94    pub fn manual_command(&self) -> &str {
95        self.state
96            .as_ref()
97            .and_then(|s| s.manual_command.as_deref())
98            .unwrap_or("paper update")
99    }
100
101    /// The one stderr line CLI search and answer print, if any.
102    pub fn cli_note(&self) -> Option<String> {
103        let approved = self.approved.as_deref()?;
104        if self.outcome() == Some("updated") {
105            return Some(format!(
106                "note: Paper was updated to {approved}; restart this command or your MCP client to use it"
107            ));
108        }
109        let stuck = matches!(self.outcome(), Some("failed" | "unavailable"));
110        (stuck || !self.auto_update).then(|| {
111            format!(
112                "note: Paper {approved} is available \u{2014} run: {}",
113                self.manual_command()
114            )
115        })
116    }
117
118    /// Doctor lines (the second only for a stuck update with a manual command).
119    pub fn doctor_lines(&self) -> Vec<String> {
120        let off = if self.auto_update {
121            ""
122        } else {
123            " (auto-update off)"
124        };
125        let Some(approved) = &self.approved else {
126            return vec![format!("  update:     {} (up to date){off}", self.current)];
127        };
128        let text = match self.outcome() {
129            Some("updated") => "updated; restart to use it",
130            Some("failed") => "update failed",
131            Some("unavailable") => "not yet available for your install method",
132            _ => "available",
133        };
134        let mut lines = vec![format!(
135            "  update:     {} \u{2192} {approved} {text}{off}",
136            self.current
137        )];
138        if let (Some("failed" | "unavailable"), Some(cmd)) = (
139            self.outcome(),
140            self.state.as_ref().and_then(|s| s.manual_command.as_ref()),
141        ) {
142            lines.push(format!("              run: {cmd}"));
143        }
144        lines
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    #[test]
153    fn version_newer_orders_semver() {
154        assert!(version_newer("0.2.10", "0.2.9"));
155        assert!(version_newer("0.3.0", "0.2.99"));
156        assert!(!version_newer("0.2.7", "0.2.7"));
157        assert!(!version_newer("0.2.6", "0.2.7"));
158        assert!(version_newer("0.2.7", "0.2.7-beta.1"));
159    }
160
161    // One test: it mutates a process-wide env var.
162    #[test]
163    fn auto_update_enabled_respects_env_and_config() {
164        let on = Config::default();
165        let off = Config {
166            auto_update: Some(false),
167            ..Config::default()
168        };
169        let explicit = Config {
170            auto_update: Some(true),
171            ..Config::default()
172        };
173        std::env::remove_var("PAPER_NO_AUTO_UPDATE");
174        assert!(auto_update_enabled(&on));
175        assert!(auto_update_enabled(&explicit));
176        assert!(!auto_update_enabled(&off));
177        for (v, enabled) in [("1", false), ("yes", false), ("0", true), ("", true)] {
178            std::env::set_var("PAPER_NO_AUTO_UPDATE", v);
179            assert_eq!(auto_update_enabled(&on), enabled, "env={v:?}");
180        }
181        std::env::remove_var("PAPER_NO_AUTO_UPDATE");
182    }
183
184    #[test]
185    fn update_state_round_trips_and_garbage_is_none() {
186        let dir = tempfile::tempdir().unwrap();
187        assert_eq!(read_update_state(dir.path()), None);
188        let st = UpdateState {
189            outcome: "failed".into(),
190            approved: Some("0.4.2".into()),
191            method: "npm".into(),
192            manual_command: Some("npm install -g paperscope@0.4.2".into()),
193            detail: Some("EACCES".into()),
194            at: "2026-11-26T10:00:00+00:00".into(),
195        };
196        write_update_state(dir.path(), &st).unwrap();
197        assert_eq!(read_update_state(dir.path()), Some(st));
198        std::fs::write(dir.path().join(STATE_FILE), "not [ toml").unwrap();
199        assert_eq!(read_update_state(dir.path()), None);
200    }
201}