auto_update.rs

   1use anyhow::{Context as _, Result};
   2use client::{Client, TelemetrySettings};
   3use db::RELEASE_CHANNEL;
   4use db::kvp::KEY_VALUE_STORE;
   5use gpui::{
   6    App, AppContext as _, AsyncApp, BackgroundExecutor, Context, Entity, Global, SemanticVersion,
   7    Task, Window, actions,
   8};
   9use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
  10use paths::remote_servers_dir;
  11use release_channel::{AppCommitSha, ReleaseChannel};
  12use serde::{Deserialize, Serialize};
  13use settings::{RegisterSetting, Settings, SettingsStore};
  14use smol::{fs, io::AsyncReadExt};
  15use smol::{fs::File, process::Command};
  16use std::mem;
  17use std::{
  18    env::{
  19        self,
  20        consts::{ARCH, OS},
  21    },
  22    ffi::OsString,
  23    path::{Path, PathBuf},
  24    sync::Arc,
  25    time::Duration,
  26};
  27use workspace::Workspace;
  28
  29const SHOULD_SHOW_UPDATE_NOTIFICATION_KEY: &str = "auto-updater-should-show-updated-notification";
  30const POLL_INTERVAL: Duration = Duration::from_secs(60 * 60);
  31
  32actions!(
  33    auto_update,
  34    [
  35        /// Checks for available updates.
  36        Check,
  37        /// Dismisses the update error message.
  38        DismissMessage,
  39        /// Opens the release notes for the current version in a browser.
  40        ViewReleaseNotes,
  41    ]
  42);
  43
  44#[derive(Serialize)]
  45struct UpdateRequestBody {
  46    installation_id: Option<Arc<str>>,
  47    release_channel: Option<&'static str>,
  48    telemetry: bool,
  49    is_staff: Option<bool>,
  50    destination: &'static str,
  51}
  52
  53#[derive(Clone, Debug, PartialEq, Eq)]
  54pub enum VersionCheckType {
  55    Sha(AppCommitSha),
  56    Semantic(SemanticVersion),
  57}
  58
  59#[derive(Clone)]
  60pub enum AutoUpdateStatus {
  61    Idle,
  62    Checking,
  63    Downloading { version: VersionCheckType },
  64    Installing { version: VersionCheckType },
  65    Updated { version: VersionCheckType },
  66    Errored { error: Arc<anyhow::Error> },
  67}
  68
  69impl AutoUpdateStatus {
  70    pub fn is_updated(&self) -> bool {
  71        matches!(self, Self::Updated { .. })
  72    }
  73}
  74
  75pub struct AutoUpdater {
  76    status: AutoUpdateStatus,
  77    current_version: SemanticVersion,
  78    http_client: Arc<HttpClientWithUrl>,
  79    pending_poll: Option<Task<Option<()>>>,
  80    quit_subscription: Option<gpui::Subscription>,
  81}
  82
  83#[derive(Deserialize, Clone, Debug)]
  84pub struct JsonRelease {
  85    pub version: String,
  86    pub url: String,
  87}
  88
  89struct MacOsUnmounter<'a> {
  90    mount_path: PathBuf,
  91    background_executor: &'a BackgroundExecutor,
  92}
  93
  94impl Drop for MacOsUnmounter<'_> {
  95    fn drop(&mut self) {
  96        let mount_path = mem::take(&mut self.mount_path);
  97        self.background_executor
  98            .spawn(async move {
  99                let unmount_output = Command::new("hdiutil")
 100                    .args(["detach", "-force"])
 101                    .arg(&mount_path)
 102                    .output()
 103                    .await;
 104                match unmount_output {
 105                    Ok(output) if output.status.success() => {
 106                        log::info!("Successfully unmounted the disk image");
 107                    }
 108                    Ok(output) => {
 109                        log::error!(
 110                            "Failed to unmount disk image: {:?}",
 111                            String::from_utf8_lossy(&output.stderr)
 112                        );
 113                    }
 114                    Err(error) => {
 115                        log::error!("Error while trying to unmount disk image: {:?}", error);
 116                    }
 117                }
 118            })
 119            .detach();
 120    }
 121}
 122
 123#[derive(Clone, Copy, Debug, RegisterSetting)]
 124struct AutoUpdateSetting(bool);
 125
 126/// Whether or not to automatically check for updates.
 127///
 128/// Default: true
 129impl Settings for AutoUpdateSetting {
 130    fn from_settings(content: &settings::SettingsContent) -> Self {
 131        Self(content.auto_update.unwrap())
 132    }
 133}
 134
 135#[derive(Default)]
 136struct GlobalAutoUpdate(Option<Entity<AutoUpdater>>);
 137
 138impl Global for GlobalAutoUpdate {}
 139
 140pub fn init(http_client: Arc<HttpClientWithUrl>, cx: &mut App) {
 141    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
 142        workspace.register_action(|_, action, window, cx| check(action, window, cx));
 143
 144        workspace.register_action(|_, action, _, cx| {
 145            view_release_notes(action, cx);
 146        });
 147    })
 148    .detach();
 149
 150    let version = release_channel::AppVersion::global(cx);
 151    let auto_updater = cx.new(|cx| {
 152        let updater = AutoUpdater::new(version, http_client, cx);
 153
 154        let poll_for_updates = ReleaseChannel::try_global(cx)
 155            .map(|channel| channel.poll_for_updates())
 156            .unwrap_or(false);
 157
 158        if option_env!("ZED_UPDATE_EXPLANATION").is_none()
 159            && env::var("ZED_UPDATE_EXPLANATION").is_err()
 160            && poll_for_updates
 161        {
 162            let mut update_subscription = AutoUpdateSetting::get_global(cx)
 163                .0
 164                .then(|| updater.start_polling(cx));
 165
 166            cx.observe_global::<SettingsStore>(move |updater: &mut AutoUpdater, cx| {
 167                if AutoUpdateSetting::get_global(cx).0 {
 168                    if update_subscription.is_none() {
 169                        update_subscription = Some(updater.start_polling(cx))
 170                    }
 171                } else {
 172                    update_subscription.take();
 173                }
 174            })
 175            .detach();
 176        }
 177
 178        updater
 179    });
 180    cx.set_global(GlobalAutoUpdate(Some(auto_updater)));
 181}
 182
 183pub fn check(_: &Check, window: &mut Window, cx: &mut App) {
 184    if let Some(message) = option_env!("ZED_UPDATE_EXPLANATION") {
 185        drop(window.prompt(
 186            gpui::PromptLevel::Info,
 187            "Zed was installed via a package manager.",
 188            Some(message),
 189            &["Ok"],
 190            cx,
 191        ));
 192        return;
 193    }
 194
 195    if let Ok(message) = env::var("ZED_UPDATE_EXPLANATION") {
 196        drop(window.prompt(
 197            gpui::PromptLevel::Info,
 198            "Zed was installed via a package manager.",
 199            Some(&message),
 200            &["Ok"],
 201            cx,
 202        ));
 203        return;
 204    }
 205
 206    if !ReleaseChannel::try_global(cx)
 207        .map(|channel| channel.poll_for_updates())
 208        .unwrap_or(false)
 209    {
 210        return;
 211    }
 212
 213    if let Some(updater) = AutoUpdater::get(cx) {
 214        updater.update(cx, |updater, cx| updater.poll(UpdateCheckType::Manual, cx));
 215    } else {
 216        drop(window.prompt(
 217            gpui::PromptLevel::Info,
 218            "Could not check for updates",
 219            Some("Auto-updates disabled for non-bundled app."),
 220            &["Ok"],
 221            cx,
 222        ));
 223    }
 224}
 225
 226pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut App) -> Option<()> {
 227    let auto_updater = AutoUpdater::get(cx)?;
 228    let release_channel = ReleaseChannel::try_global(cx)?;
 229
 230    match release_channel {
 231        ReleaseChannel::Stable | ReleaseChannel::Preview => {
 232            let auto_updater = auto_updater.read(cx);
 233            let current_version = auto_updater.current_version;
 234            let release_channel = release_channel.dev_name();
 235            let path = format!("/releases/{release_channel}/{current_version}");
 236            let url = &auto_updater.http_client.build_url(&path);
 237            cx.open_url(url);
 238        }
 239        ReleaseChannel::Nightly => {
 240            cx.open_url("https://github.com/zed-industries/zed/commits/nightly/");
 241        }
 242        ReleaseChannel::Dev => {
 243            cx.open_url("https://github.com/zed-industries/zed/commits/main/");
 244        }
 245    }
 246    None
 247}
 248
 249#[cfg(not(target_os = "windows"))]
 250struct InstallerDir(tempfile::TempDir);
 251
 252#[cfg(not(target_os = "windows"))]
 253impl InstallerDir {
 254    async fn new() -> Result<Self> {
 255        Ok(Self(
 256            tempfile::Builder::new()
 257                .prefix("zed-auto-update")
 258                .tempdir()?,
 259        ))
 260    }
 261
 262    fn path(&self) -> &Path {
 263        self.0.path()
 264    }
 265}
 266
 267#[cfg(target_os = "windows")]
 268struct InstallerDir(PathBuf);
 269
 270#[cfg(target_os = "windows")]
 271impl InstallerDir {
 272    async fn new() -> Result<Self> {
 273        let installer_dir = std::env::current_exe()?
 274            .parent()
 275            .context("No parent dir for Zed.exe")?
 276            .join("updates");
 277        if smol::fs::metadata(&installer_dir).await.is_ok() {
 278            smol::fs::remove_dir_all(&installer_dir).await?;
 279        }
 280        smol::fs::create_dir(&installer_dir).await?;
 281        Ok(Self(installer_dir))
 282    }
 283
 284    fn path(&self) -> &Path {
 285        self.0.as_path()
 286    }
 287}
 288
 289pub enum UpdateCheckType {
 290    Automatic,
 291    Manual,
 292}
 293
 294impl AutoUpdater {
 295    pub fn get(cx: &mut App) -> Option<Entity<Self>> {
 296        cx.default_global::<GlobalAutoUpdate>().0.clone()
 297    }
 298
 299    fn new(
 300        current_version: SemanticVersion,
 301        http_client: Arc<HttpClientWithUrl>,
 302        cx: &mut Context<Self>,
 303    ) -> Self {
 304        // On windows, executable files cannot be overwritten while they are
 305        // running, so we must wait to overwrite the application until quitting
 306        // or restarting. When quitting the app, we spawn the auto update helper
 307        // to finish the auto update process after Zed exits. When restarting
 308        // the app after an update, we use `set_restart_path` to run the auto
 309        // update helper instead of the app, so that it can overwrite the app
 310        // and then spawn the new binary.
 311        #[cfg(target_os = "windows")]
 312        let quit_subscription = Some(cx.on_app_quit(|_, _| finalize_auto_update_on_quit()));
 313        #[cfg(not(target_os = "windows"))]
 314        let quit_subscription = None;
 315
 316        cx.on_app_restart(|this, _| {
 317            this.quit_subscription.take();
 318        })
 319        .detach();
 320
 321        Self {
 322            status: AutoUpdateStatus::Idle,
 323            current_version,
 324            http_client,
 325            pending_poll: None,
 326            quit_subscription,
 327        }
 328    }
 329
 330    pub fn start_polling(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
 331        cx.spawn(async move |this, cx| {
 332            #[cfg(target_os = "windows")]
 333            {
 334                use util::ResultExt;
 335
 336                cleanup_windows()
 337                    .await
 338                    .context("failed to cleanup old directories")
 339                    .log_err();
 340            }
 341
 342            loop {
 343                this.update(cx, |this, cx| this.poll(UpdateCheckType::Automatic, cx))?;
 344                cx.background_executor().timer(POLL_INTERVAL).await;
 345            }
 346        })
 347    }
 348
 349    pub fn poll(&mut self, check_type: UpdateCheckType, cx: &mut Context<Self>) {
 350        if self.pending_poll.is_some() {
 351            return;
 352        }
 353
 354        cx.notify();
 355
 356        self.pending_poll = Some(cx.spawn(async move |this, cx| {
 357            let result = Self::update(this.upgrade()?, cx.clone()).await;
 358            this.update(cx, |this, cx| {
 359                this.pending_poll = None;
 360                if let Err(error) = result {
 361                    this.status = match check_type {
 362                        // Be quiet if the check was automated (e.g. when offline)
 363                        UpdateCheckType::Automatic => {
 364                            log::info!("auto-update check failed: error:{:?}", error);
 365                            AutoUpdateStatus::Idle
 366                        }
 367                        UpdateCheckType::Manual => {
 368                            log::error!("auto-update failed: error:{:?}", error);
 369                            AutoUpdateStatus::Errored {
 370                                error: Arc::new(error),
 371                            }
 372                        }
 373                    };
 374
 375                    cx.notify();
 376                }
 377            })
 378            .ok()
 379        }));
 380    }
 381
 382    pub fn current_version(&self) -> SemanticVersion {
 383        self.current_version
 384    }
 385
 386    pub fn status(&self) -> AutoUpdateStatus {
 387        self.status.clone()
 388    }
 389
 390    pub fn dismiss(&mut self, cx: &mut Context<Self>) -> bool {
 391        if let AutoUpdateStatus::Idle = self.status {
 392            return false;
 393        }
 394        self.status = AutoUpdateStatus::Idle;
 395        cx.notify();
 396        true
 397    }
 398
 399    // If you are packaging Zed and need to override the place it downloads SSH remotes from,
 400    // you can override this function. You should also update get_remote_server_release_url to return
 401    // Ok(None).
 402    pub async fn download_remote_server_release(
 403        os: &str,
 404        arch: &str,
 405        release_channel: ReleaseChannel,
 406        version: Option<SemanticVersion>,
 407        set_status: impl Fn(&str, &mut AsyncApp) + Send + 'static,
 408        cx: &mut AsyncApp,
 409    ) -> Result<PathBuf> {
 410        let this = cx.update(|cx| {
 411            cx.default_global::<GlobalAutoUpdate>()
 412                .0
 413                .clone()
 414                .context("auto-update not initialized")
 415        })??;
 416
 417        set_status("Fetching remote server release", cx);
 418        let release = Self::get_release(
 419            &this,
 420            "zed-remote-server",
 421            os,
 422            arch,
 423            version,
 424            Some(release_channel),
 425            cx,
 426        )
 427        .await?;
 428
 429        let servers_dir = paths::remote_servers_dir();
 430        let channel_dir = servers_dir.join(release_channel.dev_name());
 431        let platform_dir = channel_dir.join(format!("{}-{}", os, arch));
 432        let version_path = platform_dir.join(format!("{}.gz", release.version));
 433        smol::fs::create_dir_all(&platform_dir).await.ok();
 434
 435        let client = this.read_with(cx, |this, _| this.http_client.clone())?;
 436
 437        if smol::fs::metadata(&version_path).await.is_err() {
 438            log::info!(
 439                "downloading zed-remote-server {os} {arch} version {}",
 440                release.version
 441            );
 442            set_status("Downloading remote server", cx);
 443            download_remote_server_binary(&version_path, release, client, cx).await?;
 444        }
 445
 446        Ok(version_path)
 447    }
 448
 449    pub async fn get_remote_server_release_url(
 450        os: &str,
 451        arch: &str,
 452        release_channel: ReleaseChannel,
 453        version: Option<SemanticVersion>,
 454        cx: &mut AsyncApp,
 455    ) -> Result<Option<(String, String)>> {
 456        let this = cx.update(|cx| {
 457            cx.default_global::<GlobalAutoUpdate>()
 458                .0
 459                .clone()
 460                .context("auto-update not initialized")
 461        })??;
 462
 463        let release = Self::get_release(
 464            &this,
 465            "zed-remote-server",
 466            os,
 467            arch,
 468            version,
 469            Some(release_channel),
 470            cx,
 471        )
 472        .await?;
 473
 474        let update_request_body = build_remote_server_update_request_body(cx)?;
 475        let body = serde_json::to_string(&update_request_body)?;
 476
 477        Ok(Some((release.url, body)))
 478    }
 479
 480    async fn get_release(
 481        this: &Entity<Self>,
 482        asset: &str,
 483        os: &str,
 484        arch: &str,
 485        version: Option<SemanticVersion>,
 486        release_channel: Option<ReleaseChannel>,
 487        cx: &mut AsyncApp,
 488    ) -> Result<JsonRelease> {
 489        let client = this.read_with(cx, |this, _| this.http_client.clone())?;
 490
 491        if let Some(version) = version {
 492            let channel = release_channel.map(|c| c.dev_name()).unwrap_or("stable");
 493
 494            let url = format!("/api/releases/{channel}/{version}/{asset}-{os}-{arch}.gz?update=1",);
 495
 496            Ok(JsonRelease {
 497                version: version.to_string(),
 498                url: client.build_url(&url),
 499            })
 500        } else {
 501            let mut url_string = client.build_url(&format!(
 502                "/api/releases/latest?asset={}&os={}&arch={}",
 503                asset, os, arch
 504            ));
 505            if let Some(param) = release_channel.and_then(|c| c.release_query_param()) {
 506                url_string += "&";
 507                url_string += param;
 508            }
 509
 510            let mut response = client.get(&url_string, Default::default(), true).await?;
 511            let mut body = Vec::new();
 512            response.body_mut().read_to_end(&mut body).await?;
 513
 514            anyhow::ensure!(
 515                response.status().is_success(),
 516                "failed to fetch release: {:?}",
 517                String::from_utf8_lossy(&body),
 518            );
 519
 520            serde_json::from_slice(body.as_slice()).with_context(|| {
 521                format!(
 522                    "error deserializing release {:?}",
 523                    String::from_utf8_lossy(&body),
 524                )
 525            })
 526        }
 527    }
 528
 529    async fn get_latest_release(
 530        this: &Entity<Self>,
 531        asset: &str,
 532        os: &str,
 533        arch: &str,
 534        release_channel: Option<ReleaseChannel>,
 535        cx: &mut AsyncApp,
 536    ) -> Result<JsonRelease> {
 537        Self::get_release(this, asset, os, arch, None, release_channel, cx).await
 538    }
 539
 540    async fn update(this: Entity<Self>, mut cx: AsyncApp) -> Result<()> {
 541        let (client, installed_version, previous_status, release_channel) =
 542            this.read_with(&cx, |this, cx| {
 543                (
 544                    this.http_client.clone(),
 545                    this.current_version,
 546                    this.status.clone(),
 547                    ReleaseChannel::try_global(cx),
 548                )
 549            })?;
 550
 551        Self::check_dependencies()?;
 552
 553        this.update(&mut cx, |this, cx| {
 554            this.status = AutoUpdateStatus::Checking;
 555            log::info!("Auto Update: checking for updates");
 556            cx.notify();
 557        })?;
 558
 559        let fetched_release_data =
 560            Self::get_latest_release(&this, "zed", OS, ARCH, release_channel, &mut cx).await?;
 561        let fetched_version = fetched_release_data.clone().version;
 562        let app_commit_sha = cx.update(|cx| AppCommitSha::try_global(cx).map(|sha| sha.full()));
 563        let newer_version = Self::check_if_fetched_version_is_newer(
 564            *RELEASE_CHANNEL,
 565            app_commit_sha,
 566            installed_version,
 567            fetched_version,
 568            previous_status.clone(),
 569        )?;
 570
 571        let Some(newer_version) = newer_version else {
 572            return this.update(&mut cx, |this, cx| {
 573                let status = match previous_status {
 574                    AutoUpdateStatus::Updated { .. } => previous_status,
 575                    _ => AutoUpdateStatus::Idle,
 576                };
 577                this.status = status;
 578                cx.notify();
 579            });
 580        };
 581
 582        this.update(&mut cx, |this, cx| {
 583            this.status = AutoUpdateStatus::Downloading {
 584                version: newer_version.clone(),
 585            };
 586            cx.notify();
 587        })?;
 588
 589        let installer_dir = InstallerDir::new().await?;
 590        let target_path = Self::target_path(&installer_dir).await?;
 591        download_release(&target_path, fetched_release_data, client, &cx).await?;
 592
 593        this.update(&mut cx, |this, cx| {
 594            this.status = AutoUpdateStatus::Installing {
 595                version: newer_version.clone(),
 596            };
 597            cx.notify();
 598        })?;
 599
 600        let new_binary_path = Self::install_release(installer_dir, target_path, &cx).await?;
 601        if let Some(new_binary_path) = new_binary_path {
 602            cx.update(|cx| cx.set_restart_path(new_binary_path))?;
 603        }
 604
 605        this.update(&mut cx, |this, cx| {
 606            this.set_should_show_update_notification(true, cx)
 607                .detach_and_log_err(cx);
 608            this.status = AutoUpdateStatus::Updated {
 609                version: newer_version,
 610            };
 611            cx.notify();
 612        })
 613    }
 614
 615    fn check_if_fetched_version_is_newer(
 616        release_channel: ReleaseChannel,
 617        app_commit_sha: Result<Option<String>>,
 618        installed_version: SemanticVersion,
 619        fetched_version: String,
 620        status: AutoUpdateStatus,
 621    ) -> Result<Option<VersionCheckType>> {
 622        let parsed_fetched_version = fetched_version.parse::<SemanticVersion>();
 623
 624        if let AutoUpdateStatus::Updated { version, .. } = status {
 625            match version {
 626                VersionCheckType::Sha(cached_version) => {
 627                    let should_download = fetched_version != cached_version.full();
 628                    let newer_version = should_download
 629                        .then(|| VersionCheckType::Sha(AppCommitSha::new(fetched_version)));
 630                    return Ok(newer_version);
 631                }
 632                VersionCheckType::Semantic(cached_version) => {
 633                    return Self::check_if_fetched_version_is_newer_non_nightly(
 634                        cached_version,
 635                        parsed_fetched_version?,
 636                    );
 637                }
 638            }
 639        }
 640
 641        match release_channel {
 642            ReleaseChannel::Nightly => {
 643                let should_download = app_commit_sha
 644                    .ok()
 645                    .flatten()
 646                    .map(|sha| fetched_version != sha)
 647                    .unwrap_or(true);
 648                let newer_version = should_download
 649                    .then(|| VersionCheckType::Sha(AppCommitSha::new(fetched_version)));
 650                Ok(newer_version)
 651            }
 652            _ => Self::check_if_fetched_version_is_newer_non_nightly(
 653                installed_version,
 654                parsed_fetched_version?,
 655            ),
 656        }
 657    }
 658
 659    fn check_dependencies() -> Result<()> {
 660        #[cfg(not(target_os = "windows"))]
 661        anyhow::ensure!(
 662            which::which("rsync").is_ok(),
 663            "Could not auto-update because the required rsync utility was not found."
 664        );
 665        Ok(())
 666    }
 667
 668    async fn target_path(installer_dir: &InstallerDir) -> Result<PathBuf> {
 669        let filename = match OS {
 670            "macos" => anyhow::Ok("Zed.dmg"),
 671            "linux" => Ok("zed.tar.gz"),
 672            "windows" => Ok("Zed.exe"),
 673            unsupported_os => anyhow::bail!("not supported: {unsupported_os}"),
 674        }?;
 675
 676        Ok(installer_dir.path().join(filename))
 677    }
 678
 679    async fn install_release(
 680        installer_dir: InstallerDir,
 681        target_path: PathBuf,
 682        cx: &AsyncApp,
 683    ) -> Result<Option<PathBuf>> {
 684        match OS {
 685            "macos" => install_release_macos(&installer_dir, target_path, cx).await,
 686            "linux" => install_release_linux(&installer_dir, target_path, cx).await,
 687            "windows" => install_release_windows(target_path).await,
 688            unsupported_os => anyhow::bail!("not supported: {unsupported_os}"),
 689        }
 690    }
 691
 692    fn check_if_fetched_version_is_newer_non_nightly(
 693        installed_version: SemanticVersion,
 694        fetched_version: SemanticVersion,
 695    ) -> Result<Option<VersionCheckType>> {
 696        let should_download = fetched_version > installed_version;
 697        let newer_version = should_download.then(|| VersionCheckType::Semantic(fetched_version));
 698        Ok(newer_version)
 699    }
 700
 701    pub fn set_should_show_update_notification(
 702        &self,
 703        should_show: bool,
 704        cx: &App,
 705    ) -> Task<Result<()>> {
 706        cx.background_spawn(async move {
 707            if should_show {
 708                KEY_VALUE_STORE
 709                    .write_kvp(
 710                        SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
 711                        "".to_string(),
 712                    )
 713                    .await?;
 714            } else {
 715                KEY_VALUE_STORE
 716                    .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
 717                    .await?;
 718            }
 719            Ok(())
 720        })
 721    }
 722
 723    pub fn should_show_update_notification(&self, cx: &App) -> Task<Result<bool>> {
 724        cx.background_spawn(async move {
 725            Ok(KEY_VALUE_STORE
 726                .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
 727                .is_some())
 728        })
 729    }
 730}
 731
 732async fn download_remote_server_binary(
 733    target_path: &PathBuf,
 734    release: JsonRelease,
 735    client: Arc<HttpClientWithUrl>,
 736    cx: &AsyncApp,
 737) -> Result<()> {
 738    let temp = tempfile::Builder::new().tempfile_in(remote_servers_dir())?;
 739    let mut temp_file = File::create(&temp).await?;
 740    let update_request_body = build_remote_server_update_request_body(cx)?;
 741    let request_body = AsyncBody::from(serde_json::to_string(&update_request_body)?);
 742
 743    let mut response = client.get(&release.url, request_body, true).await?;
 744    anyhow::ensure!(
 745        response.status().is_success(),
 746        "failed to download remote server release: {:?}",
 747        response.status()
 748    );
 749    smol::io::copy(response.body_mut(), &mut temp_file).await?;
 750    smol::fs::rename(&temp, &target_path).await?;
 751
 752    Ok(())
 753}
 754
 755fn build_remote_server_update_request_body(cx: &AsyncApp) -> Result<UpdateRequestBody> {
 756    let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
 757        let telemetry = Client::global(cx).telemetry().clone();
 758        let is_staff = telemetry.is_staff();
 759        let installation_id = telemetry.installation_id();
 760        let release_channel =
 761            ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
 762        let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
 763
 764        (
 765            installation_id,
 766            release_channel,
 767            telemetry_enabled,
 768            is_staff,
 769        )
 770    })?;
 771
 772    Ok(UpdateRequestBody {
 773        installation_id,
 774        release_channel,
 775        telemetry: telemetry_enabled,
 776        is_staff,
 777        destination: "remote",
 778    })
 779}
 780
 781async fn download_release(
 782    target_path: &Path,
 783    release: JsonRelease,
 784    client: Arc<HttpClientWithUrl>,
 785    cx: &AsyncApp,
 786) -> Result<()> {
 787    let mut target_file = File::create(&target_path).await?;
 788
 789    let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
 790        let telemetry = Client::global(cx).telemetry().clone();
 791        let is_staff = telemetry.is_staff();
 792        let installation_id = telemetry.installation_id();
 793        let release_channel =
 794            ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
 795        let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
 796
 797        (
 798            installation_id,
 799            release_channel,
 800            telemetry_enabled,
 801            is_staff,
 802        )
 803    })?;
 804
 805    let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
 806        installation_id,
 807        release_channel,
 808        telemetry: telemetry_enabled,
 809        is_staff,
 810        destination: "local",
 811    })?);
 812
 813    let mut response = client.get(&release.url, request_body, true).await?;
 814    smol::io::copy(response.body_mut(), &mut target_file).await?;
 815    log::info!("downloaded update. path:{:?}", target_path);
 816
 817    Ok(())
 818}
 819
 820async fn install_release_linux(
 821    temp_dir: &InstallerDir,
 822    downloaded_tar_gz: PathBuf,
 823    cx: &AsyncApp,
 824) -> Result<Option<PathBuf>> {
 825    let channel = cx.update(|cx| ReleaseChannel::global(cx).dev_name())?;
 826    let home_dir = PathBuf::from(env::var("HOME").context("no HOME env var set")?);
 827    let running_app_path = cx.update(|cx| cx.app_path())??;
 828
 829    let extracted = temp_dir.path().join("zed");
 830    fs::create_dir_all(&extracted)
 831        .await
 832        .context("failed to create directory into which to extract update")?;
 833
 834    let output = Command::new("tar")
 835        .arg("-xzf")
 836        .arg(&downloaded_tar_gz)
 837        .arg("-C")
 838        .arg(&extracted)
 839        .output()
 840        .await?;
 841
 842    anyhow::ensure!(
 843        output.status.success(),
 844        "failed to extract {:?} to {:?}: {:?}",
 845        downloaded_tar_gz,
 846        extracted,
 847        String::from_utf8_lossy(&output.stderr)
 848    );
 849
 850    let suffix = if channel != "stable" {
 851        format!("-{}", channel)
 852    } else {
 853        String::default()
 854    };
 855    let app_folder_name = format!("zed{}.app", suffix);
 856
 857    let from = extracted.join(&app_folder_name);
 858    let mut to = home_dir.join(".local");
 859
 860    let expected_suffix = format!("{}/libexec/zed-editor", app_folder_name);
 861
 862    if let Some(prefix) = running_app_path
 863        .to_str()
 864        .and_then(|str| str.strip_suffix(&expected_suffix))
 865    {
 866        to = PathBuf::from(prefix);
 867    }
 868
 869    let output = Command::new("rsync")
 870        .args(["-av", "--delete"])
 871        .arg(&from)
 872        .arg(&to)
 873        .output()
 874        .await?;
 875
 876    anyhow::ensure!(
 877        output.status.success(),
 878        "failed to copy Zed update from {:?} to {:?}: {:?}",
 879        from,
 880        to,
 881        String::from_utf8_lossy(&output.stderr)
 882    );
 883
 884    Ok(Some(to.join(expected_suffix)))
 885}
 886
 887async fn install_release_macos(
 888    temp_dir: &InstallerDir,
 889    downloaded_dmg: PathBuf,
 890    cx: &AsyncApp,
 891) -> Result<Option<PathBuf>> {
 892    let running_app_path = cx.update(|cx| cx.app_path())??;
 893    let running_app_filename = running_app_path
 894        .file_name()
 895        .with_context(|| format!("invalid running app path {running_app_path:?}"))?;
 896
 897    let mount_path = temp_dir.path().join("Zed");
 898    let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
 899
 900    mounted_app_path.push("/");
 901    let output = Command::new("hdiutil")
 902        .args(["attach", "-nobrowse"])
 903        .arg(&downloaded_dmg)
 904        .arg("-mountroot")
 905        .arg(temp_dir.path())
 906        .output()
 907        .await?;
 908
 909    anyhow::ensure!(
 910        output.status.success(),
 911        "failed to mount: {:?}",
 912        String::from_utf8_lossy(&output.stderr)
 913    );
 914
 915    // Create an MacOsUnmounter that will be dropped (and thus unmount the disk) when this function exits
 916    let _unmounter = MacOsUnmounter {
 917        mount_path: mount_path.clone(),
 918        background_executor: cx.background_executor(),
 919    };
 920
 921    let output = Command::new("rsync")
 922        .args(["-av", "--delete"])
 923        .arg(&mounted_app_path)
 924        .arg(&running_app_path)
 925        .output()
 926        .await?;
 927
 928    anyhow::ensure!(
 929        output.status.success(),
 930        "failed to copy app: {:?}",
 931        String::from_utf8_lossy(&output.stderr)
 932    );
 933
 934    Ok(None)
 935}
 936
 937#[cfg(target_os = "windows")]
 938async fn cleanup_windows() -> Result<()> {
 939    use util::ResultExt;
 940
 941    let parent = std::env::current_exe()?
 942        .parent()
 943        .context("No parent dir for Zed.exe")?
 944        .to_owned();
 945
 946    // keep in sync with crates/auto_update_helper/src/updater.rs
 947    smol::fs::remove_dir(parent.join("updates"))
 948        .await
 949        .context("failed to remove updates dir")
 950        .log_err();
 951    smol::fs::remove_dir(parent.join("install"))
 952        .await
 953        .context("failed to remove install dir")
 954        .log_err();
 955    smol::fs::remove_dir(parent.join("old"))
 956        .await
 957        .context("failed to remove old version dir")
 958        .log_err();
 959
 960    Ok(())
 961}
 962
 963async fn install_release_windows(downloaded_installer: PathBuf) -> Result<Option<PathBuf>> {
 964    let output = Command::new(downloaded_installer)
 965        .arg("/verysilent")
 966        .arg("/update=true")
 967        .arg("!desktopicon")
 968        .arg("!quicklaunchicon")
 969        .output()
 970        .await?;
 971    anyhow::ensure!(
 972        output.status.success(),
 973        "failed to start installer: {:?}",
 974        String::from_utf8_lossy(&output.stderr)
 975    );
 976    // We return the path to the update helper program, because it will
 977    // perform the final steps of the update process, copying the new binary,
 978    // deleting the old one, and launching the new binary.
 979    let helper_path = std::env::current_exe()?
 980        .parent()
 981        .context("No parent dir for Zed.exe")?
 982        .join("tools")
 983        .join("auto_update_helper.exe");
 984    Ok(Some(helper_path))
 985}
 986
 987pub async fn finalize_auto_update_on_quit() {
 988    let Some(installer_path) = std::env::current_exe()
 989        .ok()
 990        .and_then(|p| p.parent().map(|p| p.join("updates")))
 991    else {
 992        return;
 993    };
 994
 995    // The installer will create a flag file after it finishes updating
 996    let flag_file = installer_path.join("versions.txt");
 997    if flag_file.exists()
 998        && let Some(helper) = installer_path
 999            .parent()
1000            .map(|p| p.join("tools").join("auto_update_helper.exe"))
1001    {
1002        let mut command = util::command::new_smol_command(helper);
1003        command.arg("--launch");
1004        command.arg("false");
1005        if let Ok(mut cmd) = command.spawn() {
1006            _ = cmd.status().await;
1007        }
1008    }
1009}
1010
1011#[cfg(test)]
1012mod tests {
1013    use gpui::TestAppContext;
1014    use settings::default_settings;
1015
1016    use super::*;
1017
1018    #[gpui::test]
1019    fn test_auto_update_defaults_to_true(cx: &mut TestAppContext) {
1020        cx.update(|cx| {
1021            let mut store = SettingsStore::new(cx, &settings::default_settings());
1022            store
1023                .set_default_settings(&default_settings(), cx)
1024                .expect("Unable to set default settings");
1025            store
1026                .set_user_settings("{}", cx)
1027                .expect("Unable to set user settings");
1028            cx.set_global(store);
1029            assert!(AutoUpdateSetting::get_global(cx).0);
1030        });
1031    }
1032
1033    #[test]
1034    fn test_stable_does_not_update_when_fetched_version_is_not_higher() {
1035        let release_channel = ReleaseChannel::Stable;
1036        let app_commit_sha = Ok(Some("a".to_string()));
1037        let installed_version = SemanticVersion::new(1, 0, 0);
1038        let status = AutoUpdateStatus::Idle;
1039        let fetched_version = SemanticVersion::new(1, 0, 0);
1040
1041        let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1042            release_channel,
1043            app_commit_sha,
1044            installed_version,
1045            fetched_version.to_string(),
1046            status,
1047        );
1048
1049        assert_eq!(newer_version.unwrap(), None);
1050    }
1051
1052    #[test]
1053    fn test_stable_does_update_when_fetched_version_is_higher() {
1054        let release_channel = ReleaseChannel::Stable;
1055        let app_commit_sha = Ok(Some("a".to_string()));
1056        let installed_version = SemanticVersion::new(1, 0, 0);
1057        let status = AutoUpdateStatus::Idle;
1058        let fetched_version = SemanticVersion::new(1, 0, 1);
1059
1060        let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1061            release_channel,
1062            app_commit_sha,
1063            installed_version,
1064            fetched_version.to_string(),
1065            status,
1066        );
1067
1068        assert_eq!(
1069            newer_version.unwrap(),
1070            Some(VersionCheckType::Semantic(fetched_version))
1071        );
1072    }
1073
1074    #[test]
1075    fn test_stable_does_not_update_when_fetched_version_is_not_higher_than_cached() {
1076        let release_channel = ReleaseChannel::Stable;
1077        let app_commit_sha = Ok(Some("a".to_string()));
1078        let installed_version = SemanticVersion::new(1, 0, 0);
1079        let status = AutoUpdateStatus::Updated {
1080            version: VersionCheckType::Semantic(SemanticVersion::new(1, 0, 1)),
1081        };
1082        let fetched_version = SemanticVersion::new(1, 0, 1);
1083
1084        let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1085            release_channel,
1086            app_commit_sha,
1087            installed_version,
1088            fetched_version.to_string(),
1089            status,
1090        );
1091
1092        assert_eq!(newer_version.unwrap(), None);
1093    }
1094
1095    #[test]
1096    fn test_stable_does_update_when_fetched_version_is_higher_than_cached() {
1097        let release_channel = ReleaseChannel::Stable;
1098        let app_commit_sha = Ok(Some("a".to_string()));
1099        let installed_version = SemanticVersion::new(1, 0, 0);
1100        let status = AutoUpdateStatus::Updated {
1101            version: VersionCheckType::Semantic(SemanticVersion::new(1, 0, 1)),
1102        };
1103        let fetched_version = SemanticVersion::new(1, 0, 2);
1104
1105        let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1106            release_channel,
1107            app_commit_sha,
1108            installed_version,
1109            fetched_version.to_string(),
1110            status,
1111        );
1112
1113        assert_eq!(
1114            newer_version.unwrap(),
1115            Some(VersionCheckType::Semantic(fetched_version))
1116        );
1117    }
1118
1119    #[test]
1120    fn test_nightly_does_not_update_when_fetched_sha_is_same() {
1121        let release_channel = ReleaseChannel::Nightly;
1122        let app_commit_sha = Ok(Some("a".to_string()));
1123        let installed_version = SemanticVersion::new(1, 0, 0);
1124        let status = AutoUpdateStatus::Idle;
1125        let fetched_sha = "a".to_string();
1126
1127        let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1128            release_channel,
1129            app_commit_sha,
1130            installed_version,
1131            fetched_sha,
1132            status,
1133        );
1134
1135        assert_eq!(newer_version.unwrap(), None);
1136    }
1137
1138    #[test]
1139    fn test_nightly_does_update_when_fetched_sha_is_not_same() {
1140        let release_channel = ReleaseChannel::Nightly;
1141        let app_commit_sha = Ok(Some("a".to_string()));
1142        let installed_version = SemanticVersion::new(1, 0, 0);
1143        let status = AutoUpdateStatus::Idle;
1144        let fetched_sha = "b".to_string();
1145
1146        let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1147            release_channel,
1148            app_commit_sha,
1149            installed_version,
1150            fetched_sha.clone(),
1151            status,
1152        );
1153
1154        assert_eq!(
1155            newer_version.unwrap(),
1156            Some(VersionCheckType::Sha(AppCommitSha::new(fetched_sha)))
1157        );
1158    }
1159
1160    #[test]
1161    fn test_nightly_does_not_update_when_fetched_sha_is_same_as_cached() {
1162        let release_channel = ReleaseChannel::Nightly;
1163        let app_commit_sha = Ok(Some("a".to_string()));
1164        let installed_version = SemanticVersion::new(1, 0, 0);
1165        let status = AutoUpdateStatus::Updated {
1166            version: VersionCheckType::Sha(AppCommitSha::new("b".to_string())),
1167        };
1168        let fetched_sha = "b".to_string();
1169
1170        let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1171            release_channel,
1172            app_commit_sha,
1173            installed_version,
1174            fetched_sha,
1175            status,
1176        );
1177
1178        assert_eq!(newer_version.unwrap(), None);
1179    }
1180
1181    #[test]
1182    fn test_nightly_does_update_when_fetched_sha_is_not_same_as_cached() {
1183        let release_channel = ReleaseChannel::Nightly;
1184        let app_commit_sha = Ok(Some("a".to_string()));
1185        let installed_version = SemanticVersion::new(1, 0, 0);
1186        let status = AutoUpdateStatus::Updated {
1187            version: VersionCheckType::Sha(AppCommitSha::new("b".to_string())),
1188        };
1189        let fetched_sha = "c".to_string();
1190
1191        let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1192            release_channel,
1193            app_commit_sha,
1194            installed_version,
1195            fetched_sha.clone(),
1196            status,
1197        );
1198
1199        assert_eq!(
1200            newer_version.unwrap(),
1201            Some(VersionCheckType::Sha(AppCommitSha::new(fetched_sha)))
1202        );
1203    }
1204
1205    #[test]
1206    fn test_nightly_does_update_when_installed_versions_sha_cannot_be_retrieved() {
1207        let release_channel = ReleaseChannel::Nightly;
1208        let app_commit_sha = Ok(None);
1209        let installed_version = SemanticVersion::new(1, 0, 0);
1210        let status = AutoUpdateStatus::Idle;
1211        let fetched_sha = "a".to_string();
1212
1213        let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1214            release_channel,
1215            app_commit_sha,
1216            installed_version,
1217            fetched_sha.clone(),
1218            status,
1219        );
1220
1221        assert_eq!(
1222            newer_version.unwrap(),
1223            Some(VersionCheckType::Sha(AppCommitSha::new(fetched_sha)))
1224        );
1225    }
1226
1227    #[test]
1228    fn test_nightly_does_not_update_when_cached_update_is_same_as_fetched_and_installed_versions_sha_cannot_be_retrieved()
1229     {
1230        let release_channel = ReleaseChannel::Nightly;
1231        let app_commit_sha = Ok(None);
1232        let installed_version = SemanticVersion::new(1, 0, 0);
1233        let status = AutoUpdateStatus::Updated {
1234            version: VersionCheckType::Sha(AppCommitSha::new("b".to_string())),
1235        };
1236        let fetched_sha = "b".to_string();
1237
1238        let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1239            release_channel,
1240            app_commit_sha,
1241            installed_version,
1242            fetched_sha,
1243            status,
1244        );
1245
1246        assert_eq!(newer_version.unwrap(), None);
1247    }
1248
1249    #[test]
1250    fn test_nightly_does_update_when_cached_update_is_not_same_as_fetched_and_installed_versions_sha_cannot_be_retrieved()
1251     {
1252        let release_channel = ReleaseChannel::Nightly;
1253        let app_commit_sha = Ok(None);
1254        let installed_version = SemanticVersion::new(1, 0, 0);
1255        let status = AutoUpdateStatus::Updated {
1256            version: VersionCheckType::Sha(AppCommitSha::new("b".to_string())),
1257        };
1258        let fetched_sha = "c".to_string();
1259
1260        let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1261            release_channel,
1262            app_commit_sha,
1263            installed_version,
1264            fetched_sha.clone(),
1265            status,
1266        );
1267
1268        assert_eq!(
1269            newer_version.unwrap(),
1270            Some(VersionCheckType::Sha(AppCommitSha::new(fetched_sha)))
1271        );
1272    }
1273}