auto_update.rs

  1mod update_notification;
  2
  3use anyhow::{anyhow, Context, Result};
  4use client::{Client, TelemetrySettings, ZED_APP_PATH};
  5use db::kvp::KEY_VALUE_STORE;
  6use db::RELEASE_CHANNEL;
  7use editor::{Editor, MultiBuffer};
  8use gpui::{
  9    actions, AppContext, AsyncAppContext, Context as _, Global, Model, ModelContext,
 10    SemanticVersion, SharedString, Task, View, ViewContext, VisualContext, WindowContext,
 11};
 12use isahc::AsyncBody;
 13
 14use markdown_preview::markdown_preview_view::{MarkdownPreviewMode, MarkdownPreviewView};
 15use schemars::JsonSchema;
 16use serde::Deserialize;
 17use serde_derive::Serialize;
 18use smol::{fs, io::AsyncReadExt};
 19
 20use settings::{Settings, SettingsSources, SettingsStore};
 21use smol::{fs::File, process::Command};
 22
 23use http::{HttpClient, HttpClientWithUrl};
 24use release_channel::{AppCommitSha, AppVersion, ReleaseChannel};
 25use std::{
 26    env::consts::{ARCH, OS},
 27    ffi::OsString,
 28    path::PathBuf,
 29    sync::Arc,
 30    time::Duration,
 31};
 32use update_notification::UpdateNotification;
 33use util::ResultExt;
 34use workspace::notifications::NotificationId;
 35use workspace::Workspace;
 36
 37const SHOULD_SHOW_UPDATE_NOTIFICATION_KEY: &str = "auto-updater-should-show-updated-notification";
 38const POLL_INTERVAL: Duration = Duration::from_secs(60 * 60);
 39
 40actions!(
 41    auto_update,
 42    [
 43        Check,
 44        DismissErrorMessage,
 45        ViewReleaseNotes,
 46        ViewReleaseNotesLocally
 47    ]
 48);
 49
 50#[derive(Serialize)]
 51struct UpdateRequestBody {
 52    installation_id: Option<Arc<str>>,
 53    release_channel: Option<&'static str>,
 54    telemetry: bool,
 55}
 56
 57#[derive(Clone, PartialEq, Eq)]
 58pub enum AutoUpdateStatus {
 59    Idle,
 60    Checking,
 61    Downloading,
 62    Installing,
 63    Updated { binary_path: PathBuf },
 64    Errored,
 65}
 66
 67impl AutoUpdateStatus {
 68    pub fn is_updated(&self) -> bool {
 69        matches!(self, Self::Updated { .. })
 70    }
 71}
 72
 73pub struct AutoUpdater {
 74    status: AutoUpdateStatus,
 75    current_version: SemanticVersion,
 76    http_client: Arc<HttpClientWithUrl>,
 77    pending_poll: Option<Task<Option<()>>>,
 78}
 79
 80#[derive(Deserialize)]
 81struct JsonRelease {
 82    version: String,
 83    url: String,
 84}
 85
 86struct AutoUpdateSetting(bool);
 87
 88/// Whether or not to automatically check for updates.
 89///
 90/// Default: true
 91#[derive(Clone, Copy, Default, JsonSchema, Deserialize, Serialize)]
 92#[serde(transparent)]
 93struct AutoUpdateSettingContent(bool);
 94
 95impl Settings for AutoUpdateSetting {
 96    const KEY: Option<&'static str> = Some("auto_update");
 97
 98    type FileContent = Option<AutoUpdateSettingContent>;
 99
100    fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
101        let auto_update = [sources.release_channel, sources.user]
102            .into_iter()
103            .find_map(|value| value.copied().flatten())
104            .unwrap_or(sources.default.ok_or_else(Self::missing_default)?);
105
106        Ok(Self(auto_update.0))
107    }
108}
109
110#[derive(Default)]
111struct GlobalAutoUpdate(Option<Model<AutoUpdater>>);
112
113impl Global for GlobalAutoUpdate {}
114
115#[derive(Deserialize)]
116struct ReleaseNotesBody {
117    title: String,
118    release_notes: String,
119}
120
121pub fn init(http_client: Arc<HttpClientWithUrl>, cx: &mut AppContext) {
122    AutoUpdateSetting::register(cx);
123
124    cx.observe_new_views(|workspace: &mut Workspace, _cx| {
125        workspace.register_action(|_, action: &Check, cx| check(action, cx));
126
127        workspace.register_action(|_, action, cx| {
128            view_release_notes(action, cx);
129        });
130
131        workspace.register_action(|workspace, _: &ViewReleaseNotesLocally, cx| {
132            view_release_notes_locally(workspace, cx);
133        });
134    })
135    .detach();
136
137    let version = release_channel::AppVersion::global(cx);
138    let auto_updater = cx.new_model(|cx| {
139        let updater = AutoUpdater::new(version, http_client);
140
141        let mut update_subscription = AutoUpdateSetting::get_global(cx)
142            .0
143            .then(|| updater.start_polling(cx));
144
145        cx.observe_global::<SettingsStore>(move |updater, cx| {
146            if AutoUpdateSetting::get_global(cx).0 {
147                if update_subscription.is_none() {
148                    update_subscription = Some(updater.start_polling(cx))
149                }
150            } else {
151                update_subscription.take();
152            }
153        })
154        .detach();
155
156        updater
157    });
158    cx.set_global(GlobalAutoUpdate(Some(auto_updater)));
159}
160
161pub fn check(_: &Check, cx: &mut WindowContext) {
162    if let Some(updater) = AutoUpdater::get(cx) {
163        updater.update(cx, |updater, cx| updater.poll(cx));
164    } else {
165        drop(cx.prompt(
166            gpui::PromptLevel::Info,
167            "Could not check for updates",
168            Some("Auto-updates disabled for non-bundled app."),
169            &["Ok"],
170        ));
171    }
172}
173
174pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut AppContext) -> Option<()> {
175    let auto_updater = AutoUpdater::get(cx)?;
176    let release_channel = ReleaseChannel::try_global(cx)?;
177
178    if matches!(
179        release_channel,
180        ReleaseChannel::Stable | ReleaseChannel::Preview
181    ) {
182        let auto_updater = auto_updater.read(cx);
183        let release_channel = release_channel.dev_name();
184        let current_version = auto_updater.current_version;
185        let url = &auto_updater
186            .http_client
187            .build_url(&format!("/releases/{release_channel}/{current_version}"));
188        cx.open_url(&url);
189    }
190
191    None
192}
193
194fn view_release_notes_locally(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
195    let release_channel = ReleaseChannel::global(cx);
196    let version = AppVersion::global(cx).to_string();
197
198    let client = client::Client::global(cx).http_client();
199    let url = client.build_url(&format!(
200        "/api/release_notes/{}/{}",
201        release_channel.dev_name(),
202        version
203    ));
204
205    let markdown = workspace
206        .app_state()
207        .languages
208        .language_for_name("Markdown");
209
210    workspace
211        .with_local_workspace(cx, move |_, cx| {
212            cx.spawn(|workspace, mut cx| async move {
213                let markdown = markdown.await.log_err();
214                let response = client.get(&url, Default::default(), true).await;
215                let Some(mut response) = response.log_err() else {
216                    return;
217                };
218
219                let mut body = Vec::new();
220                response.body_mut().read_to_end(&mut body).await.ok();
221
222                let body: serde_json::Result<ReleaseNotesBody> =
223                    serde_json::from_slice(body.as_slice());
224
225                if let Ok(body) = body {
226                    workspace
227                        .update(&mut cx, |workspace, cx| {
228                            let project = workspace.project().clone();
229                            let buffer = project.update(cx, |project, cx| {
230                                project.create_local_buffer("", markdown, cx)
231                            });
232                            buffer.update(cx, |buffer, cx| {
233                                buffer.edit([(0..0, body.release_notes)], None, cx)
234                            });
235                            let language_registry = project.read(cx).languages().clone();
236
237                            let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
238
239                            let tab_description = SharedString::from(body.title.to_string());
240                            let editor = cx.new_view(|cx| {
241                                Editor::for_multibuffer(buffer, Some(project), true, cx)
242                            });
243                            let workspace_handle = workspace.weak_handle();
244                            let view: View<MarkdownPreviewView> = MarkdownPreviewView::new(
245                                MarkdownPreviewMode::Default,
246                                editor,
247                                workspace_handle,
248                                language_registry,
249                                Some(tab_description),
250                                cx,
251                            );
252                            workspace.add_item_to_active_pane(Box::new(view.clone()), None, cx);
253                            cx.notify();
254                        })
255                        .log_err();
256                }
257            })
258            .detach();
259        })
260        .detach();
261}
262
263pub fn notify_of_any_new_update(cx: &mut ViewContext<Workspace>) -> Option<()> {
264    let updater = AutoUpdater::get(cx)?;
265    let version = updater.read(cx).current_version;
266    let should_show_notification = updater.read(cx).should_show_update_notification(cx);
267
268    cx.spawn(|workspace, mut cx| async move {
269        let should_show_notification = should_show_notification.await?;
270        if should_show_notification {
271            workspace.update(&mut cx, |workspace, cx| {
272                workspace.show_notification(
273                    NotificationId::unique::<UpdateNotification>(),
274                    cx,
275                    |cx| cx.new_view(|_| UpdateNotification::new(version)),
276                );
277                updater
278                    .read(cx)
279                    .set_should_show_update_notification(false, cx)
280                    .detach_and_log_err(cx);
281            })?;
282        }
283        anyhow::Ok(())
284    })
285    .detach();
286
287    None
288}
289
290impl AutoUpdater {
291    pub fn get(cx: &mut AppContext) -> Option<Model<Self>> {
292        cx.default_global::<GlobalAutoUpdate>().0.clone()
293    }
294
295    fn new(current_version: SemanticVersion, http_client: Arc<HttpClientWithUrl>) -> Self {
296        Self {
297            status: AutoUpdateStatus::Idle,
298            current_version,
299            http_client,
300            pending_poll: None,
301        }
302    }
303
304    pub fn start_polling(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
305        cx.spawn(|this, mut cx| async move {
306            loop {
307                this.update(&mut cx, |this, cx| this.poll(cx))?;
308                cx.background_executor().timer(POLL_INTERVAL).await;
309            }
310        })
311    }
312
313    pub fn poll(&mut self, cx: &mut ModelContext<Self>) {
314        if self.pending_poll.is_some() || self.status.is_updated() {
315            return;
316        }
317
318        self.status = AutoUpdateStatus::Checking;
319        cx.notify();
320
321        self.pending_poll = Some(cx.spawn(|this, mut cx| async move {
322            let result = Self::update(this.upgrade()?, cx.clone()).await;
323            this.update(&mut cx, |this, cx| {
324                this.pending_poll = None;
325                if let Err(error) = result {
326                    log::error!("auto-update failed: error:{:?}", error);
327                    this.status = AutoUpdateStatus::Errored;
328                    cx.notify();
329                }
330            })
331            .ok()
332        }));
333    }
334
335    pub fn status(&self) -> AutoUpdateStatus {
336        self.status.clone()
337    }
338
339    pub fn dismiss_error(&mut self, cx: &mut ModelContext<Self>) {
340        self.status = AutoUpdateStatus::Idle;
341        cx.notify();
342    }
343
344    async fn update(this: Model<Self>, mut cx: AsyncAppContext) -> Result<()> {
345        // Skip auto-update for flatpaks
346        #[cfg(target_os = "linux")]
347        if matches!(std::env::var("ZED_IS_FLATPAK_INSTALL"), Ok(_)) {
348            this.update(&mut cx, |this, cx| {
349                this.status = AutoUpdateStatus::Idle;
350                cx.notify();
351            })?;
352            return Ok(());
353        }
354
355        let (client, current_version) = this.read_with(&cx, |this, _| {
356            (this.http_client.clone(), this.current_version)
357        })?;
358
359        let asset = match OS {
360            "linux" => format!("zed-linux-{}.tar.gz", ARCH),
361            "macos" => "Zed.dmg".into(),
362            _ => return Err(anyhow!("auto-update not supported for OS {:?}", OS)),
363        };
364
365        let mut url_string = client.build_url(&format!(
366            "/api/releases/latest?asset={}&os={}&arch={}",
367            asset, OS, ARCH
368        ));
369        cx.update(|cx| {
370            if let Some(param) = ReleaseChannel::try_global(cx)
371                .and_then(|release_channel| release_channel.release_query_param())
372            {
373                url_string += "&";
374                url_string += param;
375            }
376        })?;
377
378        let mut response = client.get(&url_string, Default::default(), true).await?;
379
380        let mut body = Vec::new();
381        response
382            .body_mut()
383            .read_to_end(&mut body)
384            .await
385            .context("error reading release")?;
386
387        let release: JsonRelease =
388            serde_json::from_slice(body.as_slice()).context("error deserializing release")?;
389
390        let should_download = match *RELEASE_CHANNEL {
391            ReleaseChannel::Nightly => cx
392                .update(|cx| AppCommitSha::try_global(cx).map(|sha| release.version != sha.0))
393                .ok()
394                .flatten()
395                .unwrap_or(true),
396            _ => release.version.parse::<SemanticVersion>()? > current_version,
397        };
398
399        if !should_download {
400            this.update(&mut cx, |this, cx| {
401                this.status = AutoUpdateStatus::Idle;
402                cx.notify();
403            })?;
404            return Ok(());
405        }
406
407        this.update(&mut cx, |this, cx| {
408            this.status = AutoUpdateStatus::Downloading;
409            cx.notify();
410        })?;
411
412        let temp_dir = tempfile::Builder::new()
413            .prefix("zed-auto-update")
414            .tempdir()?;
415        let downloaded_asset = download_release(&temp_dir, release, &asset, client, &cx).await?;
416
417        this.update(&mut cx, |this, cx| {
418            this.status = AutoUpdateStatus::Installing;
419            cx.notify();
420        })?;
421
422        // We store the path of our current binary, before we install, since installation might
423        // delete it. Once deleted, it's hard to get the path to our binary on Linux.
424        // So we cache it here, which allows us to then restart later on.
425        let binary_path = cx.update(|cx| cx.app_path())??;
426
427        match OS {
428            "macos" => install_release_macos(&temp_dir, downloaded_asset, &cx).await,
429            "linux" => install_release_linux(&temp_dir, downloaded_asset, &cx).await,
430            _ => Err(anyhow!("not supported: {:?}", OS)),
431        }?;
432
433        this.update(&mut cx, |this, cx| {
434            this.set_should_show_update_notification(true, cx)
435                .detach_and_log_err(cx);
436            this.status = AutoUpdateStatus::Updated { binary_path };
437            cx.notify();
438        })?;
439
440        Ok(())
441    }
442
443    fn set_should_show_update_notification(
444        &self,
445        should_show: bool,
446        cx: &AppContext,
447    ) -> Task<Result<()>> {
448        cx.background_executor().spawn(async move {
449            if should_show {
450                KEY_VALUE_STORE
451                    .write_kvp(
452                        SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
453                        "".to_string(),
454                    )
455                    .await?;
456            } else {
457                KEY_VALUE_STORE
458                    .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
459                    .await?;
460            }
461            Ok(())
462        })
463    }
464
465    fn should_show_update_notification(&self, cx: &AppContext) -> Task<Result<bool>> {
466        cx.background_executor().spawn(async move {
467            Ok(KEY_VALUE_STORE
468                .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
469                .is_some())
470        })
471    }
472}
473
474async fn download_release(
475    temp_dir: &tempfile::TempDir,
476    release: JsonRelease,
477    target_filename: &str,
478    client: Arc<HttpClientWithUrl>,
479    cx: &AsyncAppContext,
480) -> Result<PathBuf> {
481    let target_path = temp_dir.path().join(target_filename);
482    let mut target_file = File::create(&target_path).await?;
483
484    let (installation_id, release_channel, telemetry) = cx.update(|cx| {
485        let installation_id = Client::global(cx).telemetry().installation_id();
486        let release_channel =
487            ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
488        let telemetry = TelemetrySettings::get_global(cx).metrics;
489
490        (installation_id, release_channel, telemetry)
491    })?;
492
493    let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
494        installation_id,
495        release_channel,
496        telemetry,
497    })?);
498
499    let mut response = client.get(&release.url, request_body, true).await?;
500    smol::io::copy(response.body_mut(), &mut target_file).await?;
501    log::info!("downloaded update. path:{:?}", target_path);
502
503    Ok(target_path)
504}
505
506async fn install_release_linux(
507    temp_dir: &tempfile::TempDir,
508    downloaded_tar_gz: PathBuf,
509    cx: &AsyncAppContext,
510) -> Result<()> {
511    let channel = cx.update(|cx| ReleaseChannel::global(cx).dev_name())?;
512    let home_dir = PathBuf::from(std::env::var("HOME").context("no HOME env var set")?);
513
514    let extracted = temp_dir.path().join("zed");
515    fs::create_dir_all(&extracted)
516        .await
517        .context("failed to create directory into which to extract update")?;
518
519    let output = Command::new("tar")
520        .arg("-xzf")
521        .arg(&downloaded_tar_gz)
522        .arg("-C")
523        .arg(&extracted)
524        .output()
525        .await?;
526
527    anyhow::ensure!(
528        output.status.success(),
529        "failed to extract {:?} to {:?}: {:?}",
530        downloaded_tar_gz,
531        extracted,
532        String::from_utf8_lossy(&output.stderr)
533    );
534
535    let suffix = if channel != "stable" {
536        format!("-{}", channel)
537    } else {
538        String::default()
539    };
540    let app_folder_name = format!("zed{}.app", suffix);
541
542    let from = extracted.join(&app_folder_name);
543    let to = home_dir.join(".local");
544
545    let output = Command::new("rsync")
546        .args(&["-av", "--delete"])
547        .arg(&from)
548        .arg(&to)
549        .output()
550        .await?;
551
552    anyhow::ensure!(
553        output.status.success(),
554        "failed to copy Zed update from {:?} to {:?}: {:?}",
555        from,
556        to,
557        String::from_utf8_lossy(&output.stderr)
558    );
559
560    Ok(())
561}
562
563async fn install_release_macos(
564    temp_dir: &tempfile::TempDir,
565    downloaded_dmg: PathBuf,
566    cx: &AsyncAppContext,
567) -> Result<()> {
568    let running_app_path = ZED_APP_PATH
569        .clone()
570        .map_or_else(|| cx.update(|cx| cx.app_path())?, Ok)?;
571    let running_app_filename = running_app_path
572        .file_name()
573        .ok_or_else(|| anyhow!("invalid running app path"))?;
574
575    let mount_path = temp_dir.path().join("Zed");
576    let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
577
578    mounted_app_path.push("/");
579    let output = Command::new("hdiutil")
580        .args(&["attach", "-nobrowse"])
581        .arg(&downloaded_dmg)
582        .arg("-mountroot")
583        .arg(&temp_dir.path())
584        .output()
585        .await?;
586
587    anyhow::ensure!(
588        output.status.success(),
589        "failed to mount: {:?}",
590        String::from_utf8_lossy(&output.stderr)
591    );
592
593    let output = Command::new("rsync")
594        .args(&["-av", "--delete"])
595        .arg(&mounted_app_path)
596        .arg(&running_app_path)
597        .output()
598        .await?;
599
600    anyhow::ensure!(
601        output.status.success(),
602        "failed to copy app: {:?}",
603        String::from_utf8_lossy(&output.stderr)
604    );
605
606    let output = Command::new("hdiutil")
607        .args(&["detach"])
608        .arg(&mount_path)
609        .output()
610        .await?;
611
612    anyhow::ensure!(
613        output.status.success(),
614        "failed to unount: {:?}",
615        String::from_utf8_lossy(&output.stderr)
616    );
617
618    Ok(())
619}