Skip to main content

vtcode_desktop_protocol/
update.rs

1//! Cached updater-status DTOs.
2
3use serde::{Deserialize, Serialize};
4
5/// Cached updater status for the desktop client. The service owns update
6/// policy (channel, pin, check interval); this snapshot never triggers
7/// network I/O, it only reports the last cached check.
8#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
9#[serde(rename_all = "camelCase")]
10pub struct UpdateStatusSnapshot {
11    /// Version of the running service binary.
12    pub current_version: String,
13    /// Newest release the service's update cache knows about that is *newer*
14    /// than `current_version`; it names the update offer, not a readable
15    /// changelog. Never the running or an older release, so a row cannot label
16    /// a back-version "latest". Only [`Self::update_available`] means an update
17    /// is actually offered (a dismissed update keeps this version known so its
18    /// notes remain available to consumers that want to preview the offer).
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub latest_version: Option<String>,
21    /// Whether `latest_version` is newer than `current_version` and not dismissed.
22    #[serde(default)]
23    pub update_available: bool,
24    /// HTTPS release page for `latest_version`, when known.
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub release_url: Option<String>,
27    /// Parsed `### Highlights` bullets for `latest_version`, taken from the
28    /// cached release notes. Empty when the cache holds notes without a
29    /// Highlights section. These describe the offered release; the desktop
30    /// reader only presents [`Self::current_release_highlights`], so a
31    /// not-yet-installed release is never advertised as readable notes.
32    #[serde(default, skip_serializing_if = "Vec::is_empty")]
33    pub release_highlights: Vec<String>,
34    /// Parsed `### Highlights` bullets for the running `current_version`,
35    /// for the post-update "what's new" moment. Empty unless the cache holds
36    /// notes describing exactly the running version.
37    #[serde(default, skip_serializing_if = "Vec::is_empty")]
38    pub current_release_highlights: Vec<String>,
39    /// HTTPS release page for the running version, sent alongside
40    /// `current_release_highlights` so the "what's new" viewer can link out.
41    #[serde(default, skip_serializing_if = "Option::is_none")]
42    pub current_release_url: Option<String>,
43    /// Whether the running version's notes were already announced by any VT
44    /// Code surface. The marker lives in the shared update cache, so notes
45    /// shown by the CLI are not repeated by the desktop app and vice versa.
46    #[serde(default)]
47    pub current_release_seen: bool,
48    /// Release channel the service follows (stable/beta/nightly).
49    #[serde(default, skip_serializing_if = "Option::is_none")]
50    pub channel: Option<String>,
51    /// Whether the configured check interval has elapsed since the last check.
52    #[serde(default)]
53    pub check_due: bool,
54    /// State of an in-app update install. The service owns install policy and
55    /// the download itself; clients render this and never derive progress from
56    /// anything else, so a re-render cannot disagree with the install.
57    #[serde(default)]
58    pub install: UpdateInstallState,
59}
60
61/// Phase of an in-app update install, carried by [`UpdateStatusSnapshot`] and
62/// the `update/installProgress` notification.
63///
64/// Internally tagged so the wire form names its own phase
65/// (`{"phase":"downloading","downloaded":10,"total":100}`), which keeps a
66/// client from mislabeling a phase it did not expect.
67#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
68#[serde(rename_all = "camelCase", tag = "phase", rename_all_fields = "camelCase")]
69pub enum UpdateInstallState {
70    /// No install has run, or the last one was superseded by a newer check.
71    #[default]
72    Idle,
73    /// Downloading the release archive.
74    Downloading {
75        /// Bytes written so far.
76        downloaded: u64,
77        /// Total archive size when the server sent `Content-Length`; `None`
78        /// otherwise, which renders as a byte count rather than a percentage.
79        total: Option<u64>,
80    },
81    /// Checksum metadata resolved; hashing the downloaded archive.
82    Verifying,
83    /// Unpacking the archive and staging the new bundle.
84    Extracting,
85    /// Replacing the installed bundle on disk.
86    Installing,
87    /// The install finished.
88    Completed {
89        /// Version now on disk.
90        version: String,
91        /// The replaced bundle needs a one-time Gatekeeper approval before
92        /// macOS launches it (ad hoc-signed builds): the client must say so
93        /// instead of only prompting a restart. `#[serde(default)]` keeps
94        /// older services decodable.
95        #[serde(default)]
96        needs_gatekeeper_approval: bool,
97    },
98    /// The install failed.
99    Failed {
100        /// Sanitized reason; never a raw path or URL.
101        message: String,
102    },
103}
104
105impl UpdateInstallState {
106    /// Whether an install is currently in flight, so a client can disable the
107    /// install action instead of starting a second concurrent one.
108    pub fn is_in_flight(&self) -> bool {
109        matches!(self, Self::Downloading { .. } | Self::Verifying | Self::Extracting | Self::Installing)
110    }
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    #[test]
118    fn update_status_snapshot_round_trips_and_older_payloads_decode() {
119        let snapshot = UpdateStatusSnapshot {
120            current_version: "0.180.5".into(),
121            latest_version: Some("0.181.0".into()),
122            update_available: true,
123            release_url: Some("https://github.com/vinhnx/vtcode/releases/tag/v0.181.0".into()),
124            release_highlights: vec!["Faster startup".into(), "New model picker".into()],
125            current_release_highlights: vec!["Older highlight".into()],
126            current_release_url: Some("https://github.com/vinhnx/vtcode/releases/tag/v0.180.5".into()),
127            current_release_seen: true,
128            channel: Some("stable".into()),
129            check_due: false,
130            install: UpdateInstallState::Downloading { downloaded: 1024, total: Some(2048) },
131        };
132        let decoded: UpdateStatusSnapshot = serde_json::from_value(serde_json::to_value(&snapshot).unwrap()).unwrap();
133        assert_eq!(decoded, snapshot);
134
135        // Asymmetric fixtures: the post-update shape carries current-version
136        // notes with no update available, and a legacy payload carries only
137        // the running version.
138        let quiet = UpdateStatusSnapshot {
139            current_version: "0.181.0".into(),
140            latest_version: None,
141            update_available: false,
142            release_url: None,
143            release_highlights: Vec::new(),
144            current_release_highlights: vec!["Freshly installed".into()],
145            current_release_url: Some("https://github.com/vinhnx/vtcode/releases/tag/v0.181.0".into()),
146            current_release_seen: false,
147            channel: None,
148            check_due: true,
149            install: UpdateInstallState::Idle,
150        };
151        let decoded_quiet: UpdateStatusSnapshot =
152            serde_json::from_value(serde_json::to_value(&quiet).unwrap()).unwrap();
153        assert_eq!(decoded_quiet, quiet);
154
155        let legacy: UpdateStatusSnapshot =
156            serde_json::from_value(serde_json::json!({ "currentVersion": "0.179.0" })).unwrap();
157        assert_eq!(legacy.current_version, "0.179.0");
158        assert!(legacy.latest_version.is_none());
159        assert!(!legacy.update_available);
160        assert!(legacy.release_url.is_none());
161        assert!(legacy.release_highlights.is_empty());
162        assert!(legacy.current_release_highlights.is_empty());
163        assert!(legacy.current_release_url.is_none());
164        assert!(!legacy.current_release_seen);
165        assert!(legacy.channel.is_none());
166        assert!(!legacy.check_due);
167        assert_eq!(legacy.install, UpdateInstallState::Idle);
168    }
169
170    /// The install state is internally tagged, so the wire form names its own
171    /// phase and a client cannot mislabel one it did not expect.
172    #[test]
173    fn install_state_round_trips_with_a_named_phase() {
174        let states = [
175            UpdateInstallState::Idle,
176            UpdateInstallState::Downloading { downloaded: 1846, total: Some(18462109) },
177            // Asymmetric input: a missing Content-Length must survive as null
178            // rather than collapsing to a zero total that renders 0%.
179            UpdateInstallState::Downloading { downloaded: 4096, total: None },
180            UpdateInstallState::Verifying,
181            UpdateInstallState::Extracting,
182            UpdateInstallState::Installing,
183            UpdateInstallState::Completed {
184                version: "0.181.8".into(),
185                needs_gatekeeper_approval: false,
186            },
187            UpdateInstallState::Failed { message: "network unreachable".into() },
188        ];
189
190        for state in states {
191            let encoded = serde_json::to_value(&state).unwrap();
192            let decoded: UpdateInstallState = serde_json::from_value(encoded.clone()).unwrap();
193            assert_eq!(decoded, state);
194            assert!(encoded.get("phase").is_some_and(|phase| phase.is_string()), "{encoded}");
195        }
196
197        // An ad hoc-signed bundle needs its approval flag to survive the wire.
198        let gated = UpdateInstallState::Completed {
199            version: "0.181.8".into(),
200            needs_gatekeeper_approval: true,
201        };
202        let decoded: UpdateInstallState = serde_json::from_value(serde_json::to_value(&gated).unwrap()).unwrap();
203        assert_eq!(decoded, gated);
204
205        // Older services send no approval flag at all; that must read as a
206        // build that needs no extra step, not as a decode failure.
207        let legacy: UpdateInstallState =
208            serde_json::from_value(serde_json::json!({ "phase": "completed", "version": "0.181.8" })).unwrap();
209        assert_eq!(
210            legacy,
211            UpdateInstallState::Completed {
212                version: "0.181.8".into(),
213                needs_gatekeeper_approval: false
214            }
215        );
216
217        assert_eq!(
218            serde_json::to_value(UpdateInstallState::Downloading { downloaded: 7, total: None }).unwrap(),
219            serde_json::json!({ "phase": "downloading", "downloaded": 7, "total": null })
220        );
221    }
222
223    /// An older service sends no install field at all; a newer client must
224    /// read that as "nothing running" rather than failing to decode.
225    #[test]
226    fn a_payload_without_install_decodes_as_idle() {
227        let decoded: UpdateStatusSnapshot =
228            serde_json::from_value(serde_json::json!({ "currentVersion": "0.181.7" })).unwrap();
229
230        assert_eq!(decoded.install, UpdateInstallState::Idle);
231    }
232
233    #[test]
234    fn only_active_phases_report_an_install_in_flight() {
235        assert!(!UpdateInstallState::Idle.is_in_flight());
236        assert!(
237            !UpdateInstallState::Completed {
238                version: "0.181.8".into(),
239                needs_gatekeeper_approval: true
240            }
241            .is_in_flight()
242        );
243        assert!(!UpdateInstallState::Failed { message: "boom".into() }.is_in_flight());
244        assert!(UpdateInstallState::Downloading { downloaded: 1, total: Some(2) }.is_in_flight());
245        assert!(UpdateInstallState::Verifying.is_in_flight());
246        assert!(UpdateInstallState::Extracting.is_in_flight());
247        assert!(UpdateInstallState::Installing.is_in_flight());
248    }
249}