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