1mod update_notification;
2
3use anyhow::{anyhow, Context, Result};
4use client::{Client, TelemetrySettings, ZED_APP_PATH, ZED_APP_VERSION};
5use db::kvp::KEY_VALUE_STORE;
6use db::RELEASE_CHANNEL;
7use gpui::{
8 actions, AppContext, AsyncAppContext, Context as _, Global, Model, ModelContext,
9 SemanticVersion, Task, ViewContext, VisualContext, WindowContext,
10};
11use isahc::AsyncBody;
12
13use schemars::JsonSchema;
14use serde::Deserialize;
15use serde_derive::Serialize;
16use smol::io::AsyncReadExt;
17
18use settings::{Settings, SettingsStore};
19use smol::{fs::File, process::Command};
20
21use release_channel::{AppCommitSha, ReleaseChannel};
22use std::{
23 env::consts::{ARCH, OS},
24 ffi::OsString,
25 sync::Arc,
26 time::Duration,
27};
28use update_notification::UpdateNotification;
29use util::http::{HttpClient, ZedHttpClient};
30use workspace::Workspace;
31
32const SHOULD_SHOW_UPDATE_NOTIFICATION_KEY: &str = "auto-updater-should-show-updated-notification";
33const POLL_INTERVAL: Duration = Duration::from_secs(60 * 60);
34
35actions!(auto_update, [Check, DismissErrorMessage, ViewReleaseNotes]);
36
37#[derive(Serialize)]
38struct UpdateRequestBody {
39 installation_id: Option<Arc<str>>,
40 release_channel: Option<&'static str>,
41 telemetry: bool,
42}
43
44#[derive(Clone, Copy, PartialEq, Eq)]
45pub enum AutoUpdateStatus {
46 Idle,
47 Checking,
48 Downloading,
49 Installing,
50 Updated,
51 Errored,
52}
53
54pub struct AutoUpdater {
55 status: AutoUpdateStatus,
56 current_version: SemanticVersion,
57 http_client: Arc<ZedHttpClient>,
58 pending_poll: Option<Task<Option<()>>>,
59}
60
61#[derive(Deserialize)]
62struct JsonRelease {
63 version: String,
64 url: String,
65}
66
67struct AutoUpdateSetting(bool);
68
69/// Whether or not to automatically check for updates.
70///
71/// Default: true
72#[derive(Clone, Default, JsonSchema, Deserialize, Serialize)]
73#[serde(transparent)]
74struct AutoUpdateSettingOverride(Option<bool>);
75
76impl Settings for AutoUpdateSetting {
77 const KEY: Option<&'static str> = Some("auto_update");
78
79 type FileContent = AutoUpdateSettingOverride;
80
81 fn load(
82 default_value: &Self::FileContent,
83 user_values: &[&Self::FileContent],
84 _: &mut AppContext,
85 ) -> Result<Self> {
86 Ok(Self(
87 Self::json_merge(default_value, user_values)?
88 .0
89 .ok_or_else(Self::missing_default)?,
90 ))
91 }
92}
93
94#[derive(Default)]
95struct GlobalAutoUpdate(Option<Model<AutoUpdater>>);
96
97impl Global for GlobalAutoUpdate {}
98
99pub fn init(http_client: Arc<ZedHttpClient>, cx: &mut AppContext) {
100 AutoUpdateSetting::register(cx);
101
102 cx.observe_new_views(|workspace: &mut Workspace, _cx| {
103 workspace.register_action(|_, action: &Check, cx| check(action, cx));
104
105 workspace.register_action(|_, action, cx| {
106 view_release_notes(action, cx);
107 });
108 })
109 .detach();
110
111 if let Some(version) = ZED_APP_VERSION.or_else(|| cx.app_metadata().app_version) {
112 let auto_updater = cx.new_model(|cx| {
113 let updater = AutoUpdater::new(version, http_client);
114
115 let mut update_subscription = AutoUpdateSetting::get_global(cx)
116 .0
117 .then(|| updater.start_polling(cx));
118
119 cx.observe_global::<SettingsStore>(move |updater, cx| {
120 if AutoUpdateSetting::get_global(cx).0 {
121 if update_subscription.is_none() {
122 update_subscription = Some(updater.start_polling(cx))
123 }
124 } else {
125 update_subscription.take();
126 }
127 })
128 .detach();
129
130 updater
131 });
132 cx.set_global(GlobalAutoUpdate(Some(auto_updater)));
133 }
134}
135
136pub fn check(_: &Check, cx: &mut WindowContext) {
137 if let Some(updater) = AutoUpdater::get(cx) {
138 updater.update(cx, |updater, cx| updater.poll(cx));
139 } else {
140 drop(cx.prompt(
141 gpui::PromptLevel::Info,
142 "Could not check for updates",
143 Some("Auto-updates disabled for non-bundled app."),
144 &["Ok"],
145 ));
146 }
147}
148
149pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut AppContext) -> Option<()> {
150 let auto_updater = AutoUpdater::get(cx)?;
151 let release_channel = ReleaseChannel::try_global(cx)?;
152
153 if matches!(
154 release_channel,
155 ReleaseChannel::Stable | ReleaseChannel::Preview
156 ) {
157 let auto_updater = auto_updater.read(cx);
158 let release_channel = release_channel.dev_name();
159 let current_version = auto_updater.current_version;
160 let url = &auto_updater
161 .http_client
162 .zed_url(&format!("/releases/{release_channel}/{current_version}"));
163 cx.open_url(&url);
164 }
165
166 None
167}
168
169pub fn notify_of_any_new_update(cx: &mut ViewContext<Workspace>) -> Option<()> {
170 let updater = AutoUpdater::get(cx)?;
171 let version = updater.read(cx).current_version;
172 let should_show_notification = updater.read(cx).should_show_update_notification(cx);
173
174 cx.spawn(|workspace, mut cx| async move {
175 let should_show_notification = should_show_notification.await?;
176 if should_show_notification {
177 workspace.update(&mut cx, |workspace, cx| {
178 workspace.show_notification(0, cx, |cx| {
179 cx.new_view(|_| UpdateNotification::new(version))
180 });
181 updater
182 .read(cx)
183 .set_should_show_update_notification(false, cx)
184 .detach_and_log_err(cx);
185 })?;
186 }
187 anyhow::Ok(())
188 })
189 .detach();
190
191 None
192}
193
194impl AutoUpdater {
195 pub fn get(cx: &mut AppContext) -> Option<Model<Self>> {
196 cx.default_global::<GlobalAutoUpdate>().0.clone()
197 }
198
199 fn new(current_version: SemanticVersion, http_client: Arc<ZedHttpClient>) -> Self {
200 Self {
201 status: AutoUpdateStatus::Idle,
202 current_version,
203 http_client,
204 pending_poll: None,
205 }
206 }
207
208 pub fn start_polling(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
209 cx.spawn(|this, mut cx| async move {
210 loop {
211 this.update(&mut cx, |this, cx| this.poll(cx))?;
212 cx.background_executor().timer(POLL_INTERVAL).await;
213 }
214 })
215 }
216
217 pub fn poll(&mut self, cx: &mut ModelContext<Self>) {
218 if self.pending_poll.is_some() || self.status == AutoUpdateStatus::Updated {
219 return;
220 }
221
222 self.status = AutoUpdateStatus::Checking;
223 cx.notify();
224
225 self.pending_poll = Some(cx.spawn(|this, mut cx| async move {
226 let result = Self::update(this.upgrade()?, cx.clone()).await;
227 this.update(&mut cx, |this, cx| {
228 this.pending_poll = None;
229 if let Err(error) = result {
230 log::error!("auto-update failed: error:{:?}", error);
231 this.status = AutoUpdateStatus::Errored;
232 cx.notify();
233 }
234 })
235 .ok()
236 }));
237 }
238
239 pub fn status(&self) -> AutoUpdateStatus {
240 self.status
241 }
242
243 pub fn dismiss_error(&mut self, cx: &mut ModelContext<Self>) {
244 self.status = AutoUpdateStatus::Idle;
245 cx.notify();
246 }
247
248 async fn update(this: Model<Self>, mut cx: AsyncAppContext) -> Result<()> {
249 let (client, current_version) = this.read_with(&cx, |this, _| {
250 (this.http_client.clone(), this.current_version)
251 })?;
252
253 let mut url_string = client.zed_url(&format!(
254 "/api/releases/latest?asset=Zed.dmg&os={}&arch={}",
255 OS, ARCH
256 ));
257 cx.update(|cx| {
258 if let Some(param) = ReleaseChannel::try_global(cx)
259 .map(|release_channel| release_channel.release_query_param())
260 .flatten()
261 {
262 url_string += "&";
263 url_string += param;
264 }
265 })?;
266
267 let mut response = client.get(&url_string, Default::default(), true).await?;
268
269 let mut body = Vec::new();
270 response
271 .body_mut()
272 .read_to_end(&mut body)
273 .await
274 .context("error reading release")?;
275 let release: JsonRelease =
276 serde_json::from_slice(body.as_slice()).context("error deserializing release")?;
277
278 let should_download = match *RELEASE_CHANNEL {
279 ReleaseChannel::Nightly => cx
280 .update(|cx| AppCommitSha::try_global(cx).map(|sha| release.version != sha.0))
281 .ok()
282 .flatten()
283 .unwrap_or(true),
284 _ => release.version.parse::<SemanticVersion>()? > current_version,
285 };
286
287 if !should_download {
288 this.update(&mut cx, |this, cx| {
289 this.status = AutoUpdateStatus::Idle;
290 cx.notify();
291 })?;
292 return Ok(());
293 }
294
295 this.update(&mut cx, |this, cx| {
296 this.status = AutoUpdateStatus::Downloading;
297 cx.notify();
298 })?;
299
300 let temp_dir = tempfile::Builder::new()
301 .prefix("zed-auto-update")
302 .tempdir()?;
303 let dmg_path = temp_dir.path().join("Zed.dmg");
304 let mount_path = temp_dir.path().join("Zed");
305 let running_app_path = ZED_APP_PATH
306 .clone()
307 .map_or_else(|| cx.update(|cx| cx.app_path())?, Ok)?;
308 let running_app_filename = running_app_path
309 .file_name()
310 .ok_or_else(|| anyhow!("invalid running app path"))?;
311 let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
312 mounted_app_path.push("/");
313
314 let mut dmg_file = File::create(&dmg_path).await?;
315
316 let (installation_id, release_channel, telemetry) = cx.update(|cx| {
317 let installation_id = Client::global(cx).telemetry().installation_id();
318 let release_channel = ReleaseChannel::try_global(cx)
319 .map(|release_channel| release_channel.display_name());
320 let telemetry = TelemetrySettings::get_global(cx).metrics;
321
322 (installation_id, release_channel, telemetry)
323 })?;
324
325 let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
326 installation_id,
327 release_channel,
328 telemetry,
329 })?);
330
331 let mut response = client.get(&release.url, request_body, true).await?;
332 smol::io::copy(response.body_mut(), &mut dmg_file).await?;
333 log::info!("downloaded update. path:{:?}", dmg_path);
334
335 this.update(&mut cx, |this, cx| {
336 this.status = AutoUpdateStatus::Installing;
337 cx.notify();
338 })?;
339
340 let output = Command::new("hdiutil")
341 .args(&["attach", "-nobrowse"])
342 .arg(&dmg_path)
343 .arg("-mountroot")
344 .arg(&temp_dir.path())
345 .output()
346 .await?;
347 if !output.status.success() {
348 Err(anyhow!(
349 "failed to mount: {:?}",
350 String::from_utf8_lossy(&output.stderr)
351 ))?;
352 }
353
354 let output = Command::new("rsync")
355 .args(&["-av", "--delete"])
356 .arg(&mounted_app_path)
357 .arg(&running_app_path)
358 .output()
359 .await?;
360 if !output.status.success() {
361 Err(anyhow!(
362 "failed to copy app: {:?}",
363 String::from_utf8_lossy(&output.stderr)
364 ))?;
365 }
366
367 let output = Command::new("hdiutil")
368 .args(&["detach"])
369 .arg(&mount_path)
370 .output()
371 .await?;
372 if !output.status.success() {
373 Err(anyhow!(
374 "failed to unmount: {:?}",
375 String::from_utf8_lossy(&output.stderr)
376 ))?;
377 }
378
379 this.update(&mut cx, |this, cx| {
380 this.set_should_show_update_notification(true, cx)
381 .detach_and_log_err(cx);
382 this.status = AutoUpdateStatus::Updated;
383 cx.notify();
384 })?;
385 Ok(())
386 }
387
388 fn set_should_show_update_notification(
389 &self,
390 should_show: bool,
391 cx: &AppContext,
392 ) -> Task<Result<()>> {
393 cx.background_executor().spawn(async move {
394 if should_show {
395 KEY_VALUE_STORE
396 .write_kvp(
397 SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
398 "".to_string(),
399 )
400 .await?;
401 } else {
402 KEY_VALUE_STORE
403 .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
404 .await?;
405 }
406 Ok(())
407 })
408 }
409
410 fn should_show_update_notification(&self, cx: &AppContext) -> Task<Result<bool>> {
411 cx.background_executor().spawn(async move {
412 Ok(KEY_VALUE_STORE
413 .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
414 .is_some())
415 })
416 }
417}