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::{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)]
 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    AutoUpdateSetting::register(cx);
 142
 143    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
 144        workspace.register_action(|_, action, window, cx| check(action, window, cx));
 145
 146        workspace.register_action(|_, action, _, cx| {
 147            view_release_notes(action, cx);
 148        });
 149    })
 150    .detach();
 151
 152    let version = release_channel::AppVersion::global(cx);
 153    let auto_updater = cx.new(|cx| {
 154        let updater = AutoUpdater::new(version, http_client, cx);
 155
 156        let poll_for_updates = ReleaseChannel::try_global(cx)
 157            .map(|channel| channel.poll_for_updates())
 158            .unwrap_or(false);
 159
 160        if option_env!("ZED_UPDATE_EXPLANATION").is_none()
 161            && env::var("ZED_UPDATE_EXPLANATION").is_err()
 162            && poll_for_updates
 163        {
 164            let mut update_subscription = AutoUpdateSetting::get_global(cx)
 165                .0
 166                .then(|| updater.start_polling(cx));
 167
 168            cx.observe_global::<SettingsStore>(move |updater: &mut AutoUpdater, cx| {
 169                if AutoUpdateSetting::get_global(cx).0 {
 170                    if update_subscription.is_none() {
 171                        update_subscription = Some(updater.start_polling(cx))
 172                    }
 173                } else {
 174                    update_subscription.take();
 175                }
 176            })
 177            .detach();
 178        }
 179
 180        updater
 181    });
 182    cx.set_global(GlobalAutoUpdate(Some(auto_updater)));
 183}
 184
 185pub fn check(_: &Check, window: &mut Window, cx: &mut App) {
 186    if let Some(message) = option_env!("ZED_UPDATE_EXPLANATION") {
 187        drop(window.prompt(
 188            gpui::PromptLevel::Info,
 189            "Zed was installed via a package manager.",
 190            Some(message),
 191            &["Ok"],
 192            cx,
 193        ));
 194        return;
 195    }
 196
 197    if let Ok(message) = env::var("ZED_UPDATE_EXPLANATION") {
 198        drop(window.prompt(
 199            gpui::PromptLevel::Info,
 200            "Zed was installed via a package manager.",
 201            Some(&message),
 202            &["Ok"],
 203            cx,
 204        ));
 205        return;
 206    }
 207
 208    if !ReleaseChannel::try_global(cx)
 209        .map(|channel| channel.poll_for_updates())
 210        .unwrap_or(false)
 211    {
 212        return;
 213    }
 214
 215    if let Some(updater) = AutoUpdater::get(cx) {
 216        updater.update(cx, |updater, cx| updater.poll(UpdateCheckType::Manual, cx));
 217    } else {
 218        drop(window.prompt(
 219            gpui::PromptLevel::Info,
 220            "Could not check for updates",
 221            Some("Auto-updates disabled for non-bundled app."),
 222            &["Ok"],
 223            cx,
 224        ));
 225    }
 226}
 227
 228pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut App) -> Option<()> {
 229    let auto_updater = AutoUpdater::get(cx)?;
 230    let release_channel = ReleaseChannel::try_global(cx)?;
 231
 232    match release_channel {
 233        ReleaseChannel::Stable | ReleaseChannel::Preview => {
 234            let auto_updater = auto_updater.read(cx);
 235            let current_version = auto_updater.current_version;
 236            let release_channel = release_channel.dev_name();
 237            let path = format!("/releases/{release_channel}/{current_version}");
 238            let url = &auto_updater.http_client.build_url(&path);
 239            cx.open_url(url);
 240        }
 241        ReleaseChannel::Nightly => {
 242            cx.open_url("https://github.com/zed-industries/zed/commits/nightly/");
 243        }
 244        ReleaseChannel::Dev => {
 245            cx.open_url("https://github.com/zed-industries/zed/commits/main/");
 246        }
 247    }
 248    None
 249}
 250
 251#[cfg(not(target_os = "windows"))]
 252struct InstallerDir(tempfile::TempDir);
 253
 254#[cfg(not(target_os = "windows"))]
 255impl InstallerDir {
 256    async fn new() -> Result<Self> {
 257        Ok(Self(
 258            tempfile::Builder::new()
 259                .prefix("zed-auto-update")
 260                .tempdir()?,
 261        ))
 262    }
 263
 264    fn path(&self) -> &Path {
 265        self.0.path()
 266    }
 267}
 268
 269#[cfg(target_os = "windows")]
 270struct InstallerDir(PathBuf);
 271
 272#[cfg(target_os = "windows")]
 273impl InstallerDir {
 274    async fn new() -> Result<Self> {
 275        let installer_dir = std::env::current_exe()?
 276            .parent()
 277            .context("No parent dir for Zed.exe")?
 278            .join("updates");
 279        if smol::fs::metadata(&installer_dir).await.is_ok() {
 280            smol::fs::remove_dir_all(&installer_dir).await?;
 281        }
 282        smol::fs::create_dir(&installer_dir).await?;
 283        Ok(Self(installer_dir))
 284    }
 285
 286    fn path(&self) -> &Path {
 287        self.0.as_path()
 288    }
 289}
 290
 291pub enum UpdateCheckType {
 292    Automatic,
 293    Manual,
 294}
 295
 296impl AutoUpdater {
 297    pub fn get(cx: &mut App) -> Option<Entity<Self>> {
 298        cx.default_global::<GlobalAutoUpdate>().0.clone()
 299    }
 300
 301    fn new(
 302        current_version: SemanticVersion,
 303        http_client: Arc<HttpClientWithUrl>,
 304        cx: &mut Context<Self>,
 305    ) -> Self {
 306        // On windows, executable files cannot be overwritten while they are
 307        // running, so we must wait to overwrite the application until quitting
 308        // or restarting. When quitting the app, we spawn the auto update helper
 309        // to finish the auto update process after Zed exits. When restarting
 310        // the app after an update, we use `set_restart_path` to run the auto
 311        // update helper instead of the app, so that it can overwrite the app
 312        // and then spawn the new binary.
 313        #[cfg(target_os = "windows")]
 314        let quit_subscription = Some(cx.on_app_quit(|_, _| finalize_auto_update_on_quit()));
 315        #[cfg(not(target_os = "windows"))]
 316        let quit_subscription = None;
 317
 318        cx.on_app_restart(|this, _| {
 319            this.quit_subscription.take();
 320        })
 321        .detach();
 322
 323        Self {
 324            status: AutoUpdateStatus::Idle,
 325            current_version,
 326            http_client,
 327            pending_poll: None,
 328            quit_subscription,
 329        }
 330    }
 331
 332    pub fn start_polling(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
 333        cx.spawn(async move |this, cx| {
 334            #[cfg(target_os = "windows")]
 335            {
 336                use util::ResultExt;
 337
 338                cleanup_windows()
 339                    .await
 340                    .context("failed to cleanup old directories")
 341                    .log_err();
 342            }
 343
 344            loop {
 345                this.update(cx, |this, cx| this.poll(UpdateCheckType::Automatic, cx))?;
 346                cx.background_executor().timer(POLL_INTERVAL).await;
 347            }
 348        })
 349    }
 350
 351    pub fn poll(&mut self, check_type: UpdateCheckType, cx: &mut Context<Self>) {
 352        if self.pending_poll.is_some() {
 353            return;
 354        }
 355
 356        cx.notify();
 357
 358        self.pending_poll = Some(cx.spawn(async move |this, cx| {
 359            let result = Self::update(this.upgrade()?, cx.clone()).await;
 360            this.update(cx, |this, cx| {
 361                this.pending_poll = None;
 362                if let Err(error) = result {
 363                    this.status = match check_type {
 364                        // Be quiet if the check was automated (e.g. when offline)
 365                        UpdateCheckType::Automatic => {
 366                            log::info!("auto-update check failed: error:{:?}", error);
 367                            AutoUpdateStatus::Idle
 368                        }
 369                        UpdateCheckType::Manual => {
 370                            log::error!("auto-update failed: error:{:?}", error);
 371                            AutoUpdateStatus::Errored {
 372                                error: Arc::new(error),
 373                            }
 374                        }
 375                    };
 376
 377                    cx.notify();
 378                }
 379            })
 380            .ok()
 381        }));
 382    }
 383
 384    pub fn current_version(&self) -> SemanticVersion {
 385        self.current_version
 386    }
 387
 388    pub fn status(&self) -> AutoUpdateStatus {
 389        self.status.clone()
 390    }
 391
 392    pub fn dismiss(&mut self, cx: &mut Context<Self>) -> bool {
 393        if let AutoUpdateStatus::Idle = self.status {
 394            return false;
 395        }
 396        self.status = AutoUpdateStatus::Idle;
 397        cx.notify();
 398        true
 399    }
 400
 401    // If you are packaging Zed and need to override the place it downloads SSH remotes from,
 402    // you can override this function. You should also update get_remote_server_release_url to return
 403    // Ok(None).
 404    pub async fn download_remote_server_release(
 405        os: &str,
 406        arch: &str,
 407        release_channel: ReleaseChannel,
 408        version: Option<SemanticVersion>,
 409        cx: &mut AsyncApp,
 410    ) -> Result<PathBuf> {
 411        let this = cx.update(|cx| {
 412            cx.default_global::<GlobalAutoUpdate>()
 413                .0
 414                .clone()
 415                .context("auto-update not initialized")
 416        })??;
 417
 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            download_remote_server_binary(&version_path, release, client, cx).await?;
 443        }
 444
 445        Ok(version_path)
 446    }
 447
 448    pub async fn get_remote_server_release_url(
 449        os: &str,
 450        arch: &str,
 451        release_channel: ReleaseChannel,
 452        version: Option<SemanticVersion>,
 453        cx: &mut AsyncApp,
 454    ) -> Result<Option<(String, String)>> {
 455        let this = cx.update(|cx| {
 456            cx.default_global::<GlobalAutoUpdate>()
 457                .0
 458                .clone()
 459                .context("auto-update not initialized")
 460        })??;
 461
 462        let release = Self::get_release(
 463            &this,
 464            "zed-remote-server",
 465            os,
 466            arch,
 467            version,
 468            Some(release_channel),
 469            cx,
 470        )
 471        .await?;
 472
 473        let update_request_body = build_remote_server_update_request_body(cx)?;
 474        let body = serde_json::to_string(&update_request_body)?;
 475
 476        Ok(Some((release.url, body)))
 477    }
 478
 479    async fn get_release(
 480        this: &Entity<Self>,
 481        asset: &str,
 482        os: &str,
 483        arch: &str,
 484        version: Option<SemanticVersion>,
 485        release_channel: Option<ReleaseChannel>,
 486        cx: &mut AsyncApp,
 487    ) -> Result<JsonRelease> {
 488        let client = this.read_with(cx, |this, _| this.http_client.clone())?;
 489
 490        if let Some(version) = version {
 491            let channel = release_channel.map(|c| c.dev_name()).unwrap_or("stable");
 492
 493            let url = format!("/api/releases/{channel}/{version}/{asset}-{os}-{arch}.gz?update=1",);
 494
 495            Ok(JsonRelease {
 496                version: version.to_string(),
 497                url: client.build_url(&url),
 498            })
 499        } else {
 500            let mut url_string = client.build_url(&format!(
 501                "/api/releases/latest?asset={}&os={}&arch={}",
 502                asset, os, arch
 503            ));
 504            if let Some(param) = release_channel.and_then(|c| c.release_query_param()) {
 505                url_string += "&";
 506                url_string += param;
 507            }
 508
 509            let mut response = client.get(&url_string, Default::default(), true).await?;
 510            let mut body = Vec::new();
 511            response.body_mut().read_to_end(&mut body).await?;
 512
 513            anyhow::ensure!(
 514                response.status().is_success(),
 515                "failed to fetch release: {:?}",
 516                String::from_utf8_lossy(&body),
 517            );
 518
 519            serde_json::from_slice(body.as_slice()).with_context(|| {
 520                format!(
 521                    "error deserializing release {:?}",
 522                    String::from_utf8_lossy(&body),
 523                )
 524            })
 525        }
 526    }
 527
 528    async fn get_latest_release(
 529        this: &Entity<Self>,
 530        asset: &str,
 531        os: &str,
 532        arch: &str,
 533        release_channel: Option<ReleaseChannel>,
 534        cx: &mut AsyncApp,
 535    ) -> Result<JsonRelease> {
 536        Self::get_release(this, asset, os, arch, None, release_channel, cx).await
 537    }
 538
 539    async fn update(this: Entity<Self>, mut cx: AsyncApp) -> Result<()> {
 540        let (client, installed_version, previous_status, release_channel) =
 541            this.read_with(&cx, |this, cx| {
 542                (
 543                    this.http_client.clone(),
 544                    this.current_version,
 545                    this.status.clone(),
 546                    ReleaseChannel::try_global(cx),
 547                )
 548            })?;
 549
 550        Self::check_dependencies()?;
 551
 552        this.update(&mut cx, |this, cx| {
 553            this.status = AutoUpdateStatus::Checking;
 554            log::info!("Auto Update: checking for updates");
 555            cx.notify();
 556        })?;
 557
 558        let fetched_release_data =
 559            Self::get_latest_release(&this, "zed", OS, ARCH, release_channel, &mut cx).await?;
 560        let fetched_version = fetched_release_data.clone().version;
 561        let app_commit_sha = cx.update(|cx| AppCommitSha::try_global(cx).map(|sha| sha.full()));
 562        let newer_version = Self::check_if_fetched_version_is_newer(
 563            *RELEASE_CHANNEL,
 564            app_commit_sha,
 565            installed_version,
 566            fetched_version,
 567            previous_status.clone(),
 568        )?;
 569
 570        let Some(newer_version) = newer_version else {
 571            return this.update(&mut cx, |this, cx| {
 572                let status = match previous_status {
 573                    AutoUpdateStatus::Updated { .. } => previous_status,
 574                    _ => AutoUpdateStatus::Idle,
 575                };
 576                this.status = status;
 577                cx.notify();
 578            });
 579        };
 580
 581        this.update(&mut cx, |this, cx| {
 582            this.status = AutoUpdateStatus::Downloading {
 583                version: newer_version.clone(),
 584            };
 585            cx.notify();
 586        })?;
 587
 588        let installer_dir = InstallerDir::new().await?;
 589        let target_path = Self::target_path(&installer_dir).await?;
 590        download_release(&target_path, fetched_release_data, client, &cx).await?;
 591
 592        this.update(&mut cx, |this, cx| {
 593            this.status = AutoUpdateStatus::Installing {
 594                version: newer_version.clone(),
 595            };
 596            cx.notify();
 597        })?;
 598
 599        let new_binary_path = Self::install_release(installer_dir, target_path, &cx).await?;
 600        if let Some(new_binary_path) = new_binary_path {
 601            cx.update(|cx| cx.set_restart_path(new_binary_path))?;
 602        }
 603
 604        this.update(&mut cx, |this, cx| {
 605            this.set_should_show_update_notification(true, cx)
 606                .detach_and_log_err(cx);
 607            this.status = AutoUpdateStatus::Updated {
 608                version: newer_version,
 609            };
 610            cx.notify();
 611        })
 612    }
 613
 614    fn check_if_fetched_version_is_newer(
 615        release_channel: ReleaseChannel,
 616        app_commit_sha: Result<Option<String>>,
 617        installed_version: SemanticVersion,
 618        fetched_version: String,
 619        status: AutoUpdateStatus,
 620    ) -> Result<Option<VersionCheckType>> {
 621        let parsed_fetched_version = fetched_version.parse::<SemanticVersion>();
 622
 623        if let AutoUpdateStatus::Updated { version, .. } = status {
 624            match version {
 625                VersionCheckType::Sha(cached_version) => {
 626                    let should_download = fetched_version != cached_version.full();
 627                    let newer_version = should_download
 628                        .then(|| VersionCheckType::Sha(AppCommitSha::new(fetched_version)));
 629                    return Ok(newer_version);
 630                }
 631                VersionCheckType::Semantic(cached_version) => {
 632                    return Self::check_if_fetched_version_is_newer_non_nightly(
 633                        cached_version,
 634                        parsed_fetched_version?,
 635                    );
 636                }
 637            }
 638        }
 639
 640        match release_channel {
 641            ReleaseChannel::Nightly => {
 642                let should_download = app_commit_sha
 643                    .ok()
 644                    .flatten()
 645                    .map(|sha| fetched_version != sha)
 646                    .unwrap_or(true);
 647                let newer_version = should_download
 648                    .then(|| VersionCheckType::Sha(AppCommitSha::new(fetched_version)));
 649                Ok(newer_version)
 650            }
 651            _ => Self::check_if_fetched_version_is_newer_non_nightly(
 652                installed_version,
 653                parsed_fetched_version?,
 654            ),
 655        }
 656    }
 657
 658    fn check_dependencies() -> Result<()> {
 659        #[cfg(not(target_os = "windows"))]
 660        anyhow::ensure!(
 661            which::which("rsync").is_ok(),
 662            "Could not auto-update because the required rsync utility was not found."
 663        );
 664        Ok(())
 665    }
 666
 667    async fn target_path(installer_dir: &InstallerDir) -> Result<PathBuf> {
 668        let filename = match OS {
 669            "macos" => anyhow::Ok("Zed.dmg"),
 670            "linux" => Ok("zed.tar.gz"),
 671            "windows" => Ok("Zed.exe"),
 672            unsupported_os => anyhow::bail!("not supported: {unsupported_os}"),
 673        }?;
 674
 675        Ok(installer_dir.path().join(filename))
 676    }
 677
 678    async fn install_release(
 679        installer_dir: InstallerDir,
 680        target_path: PathBuf,
 681        cx: &AsyncApp,
 682    ) -> Result<Option<PathBuf>> {
 683        match OS {
 684            "macos" => install_release_macos(&installer_dir, target_path, cx).await,
 685            "linux" => install_release_linux(&installer_dir, target_path, cx).await,
 686            "windows" => install_release_windows(target_path).await,
 687            unsupported_os => anyhow::bail!("not supported: {unsupported_os}"),
 688        }
 689    }
 690
 691    fn check_if_fetched_version_is_newer_non_nightly(
 692        installed_version: SemanticVersion,
 693        fetched_version: SemanticVersion,
 694    ) -> Result<Option<VersionCheckType>> {
 695        let should_download = fetched_version > installed_version;
 696        let newer_version = should_download.then(|| VersionCheckType::Semantic(fetched_version));
 697        Ok(newer_version)
 698    }
 699
 700    pub fn set_should_show_update_notification(
 701        &self,
 702        should_show: bool,
 703        cx: &App,
 704    ) -> Task<Result<()>> {
 705        cx.background_spawn(async move {
 706            if should_show {
 707                KEY_VALUE_STORE
 708                    .write_kvp(
 709                        SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
 710                        "".to_string(),
 711                    )
 712                    .await?;
 713            } else {
 714                KEY_VALUE_STORE
 715                    .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
 716                    .await?;
 717            }
 718            Ok(())
 719        })
 720    }
 721
 722    pub fn should_show_update_notification(&self, cx: &App) -> Task<Result<bool>> {
 723        cx.background_spawn(async move {
 724            Ok(KEY_VALUE_STORE
 725                .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
 726                .is_some())
 727        })
 728    }
 729}
 730
 731async fn download_remote_server_binary(
 732    target_path: &PathBuf,
 733    release: JsonRelease,
 734    client: Arc<HttpClientWithUrl>,
 735    cx: &AsyncApp,
 736) -> Result<()> {
 737    let temp = tempfile::Builder::new().tempfile_in(remote_servers_dir())?;
 738    let mut temp_file = File::create(&temp).await?;
 739    let update_request_body = build_remote_server_update_request_body(cx)?;
 740    let request_body = AsyncBody::from(serde_json::to_string(&update_request_body)?);
 741
 742    let mut response = client.get(&release.url, request_body, true).await?;
 743    anyhow::ensure!(
 744        response.status().is_success(),
 745        "failed to download remote server release: {:?}",
 746        response.status()
 747    );
 748    smol::io::copy(response.body_mut(), &mut temp_file).await?;
 749    smol::fs::rename(&temp, &target_path).await?;
 750
 751    Ok(())
 752}
 753
 754fn build_remote_server_update_request_body(cx: &AsyncApp) -> Result<UpdateRequestBody> {
 755    let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
 756        let telemetry = Client::global(cx).telemetry().clone();
 757        let is_staff = telemetry.is_staff();
 758        let installation_id = telemetry.installation_id();
 759        let release_channel =
 760            ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
 761        let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
 762
 763        (
 764            installation_id,
 765            release_channel,
 766            telemetry_enabled,
 767            is_staff,
 768        )
 769    })?;
 770
 771    Ok(UpdateRequestBody {
 772        installation_id,
 773        release_channel,
 774        telemetry: telemetry_enabled,
 775        is_staff,
 776        destination: "remote",
 777    })
 778}
 779
 780async fn download_release(
 781    target_path: &Path,
 782    release: JsonRelease,
 783    client: Arc<HttpClientWithUrl>,
 784    cx: &AsyncApp,
 785) -> Result<()> {
 786    let mut target_file = File::create(&target_path).await?;
 787
 788    let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
 789        let telemetry = Client::global(cx).telemetry().clone();
 790        let is_staff = telemetry.is_staff();
 791        let installation_id = telemetry.installation_id();
 792        let release_channel =
 793            ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
 794        let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
 795
 796        (
 797            installation_id,
 798            release_channel,
 799            telemetry_enabled,
 800            is_staff,
 801        )
 802    })?;
 803
 804    let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
 805        installation_id,
 806        release_channel,
 807        telemetry: telemetry_enabled,
 808        is_staff,
 809        destination: "local",
 810    })?);
 811
 812    let mut response = client.get(&release.url, request_body, true).await?;
 813    smol::io::copy(response.body_mut(), &mut target_file).await?;
 814    log::info!("downloaded update. path:{:?}", target_path);
 815
 816    Ok(())
 817}
 818
 819async fn install_release_linux(
 820    temp_dir: &InstallerDir,
 821    downloaded_tar_gz: PathBuf,
 822    cx: &AsyncApp,
 823) -> Result<Option<PathBuf>> {
 824    let channel = cx.update(|cx| ReleaseChannel::global(cx).dev_name())?;
 825    let home_dir = PathBuf::from(env::var("HOME").context("no HOME env var set")?);
 826    let running_app_path = cx.update(|cx| cx.app_path())??;
 827
 828    let extracted = temp_dir.path().join("zed");
 829    fs::create_dir_all(&extracted)
 830        .await
 831        .context("failed to create directory into which to extract update")?;
 832
 833    let output = Command::new("tar")
 834        .arg("-xzf")
 835        .arg(&downloaded_tar_gz)
 836        .arg("-C")
 837        .arg(&extracted)
 838        .output()
 839        .await?;
 840
 841    anyhow::ensure!(
 842        output.status.success(),
 843        "failed to extract {:?} to {:?}: {:?}",
 844        downloaded_tar_gz,
 845        extracted,
 846        String::from_utf8_lossy(&output.stderr)
 847    );
 848
 849    let suffix = if channel != "stable" {
 850        format!("-{}", channel)
 851    } else {
 852        String::default()
 853    };
 854    let app_folder_name = format!("zed{}.app", suffix);
 855
 856    let from = extracted.join(&app_folder_name);
 857    let mut to = home_dir.join(".local");
 858
 859    let expected_suffix = format!("{}/libexec/zed-editor", app_folder_name);
 860
 861    if let Some(prefix) = running_app_path
 862        .to_str()
 863        .and_then(|str| str.strip_suffix(&expected_suffix))
 864    {
 865        to = PathBuf::from(prefix);
 866    }
 867
 868    let output = Command::new("rsync")
 869        .args(["-av", "--delete"])
 870        .arg(&from)
 871        .arg(&to)
 872        .output()
 873        .await?;
 874
 875    anyhow::ensure!(
 876        output.status.success(),
 877        "failed to copy Zed update from {:?} to {:?}: {:?}",
 878        from,
 879        to,
 880        String::from_utf8_lossy(&output.stderr)
 881    );
 882
 883    Ok(Some(to.join(expected_suffix)))
 884}
 885
 886async fn install_release_macos(
 887    temp_dir: &InstallerDir,
 888    downloaded_dmg: PathBuf,
 889    cx: &AsyncApp,
 890) -> Result<Option<PathBuf>> {
 891    let running_app_path = cx.update(|cx| cx.app_path())??;
 892    let running_app_filename = running_app_path
 893        .file_name()
 894        .with_context(|| format!("invalid running app path {running_app_path:?}"))?;
 895
 896    let mount_path = temp_dir.path().join("Zed");
 897    let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
 898
 899    mounted_app_path.push("/");
 900    let output = Command::new("hdiutil")
 901        .args(["attach", "-nobrowse"])
 902        .arg(&downloaded_dmg)
 903        .arg("-mountroot")
 904        .arg(temp_dir.path())
 905        .output()
 906        .await?;
 907
 908    anyhow::ensure!(
 909        output.status.success(),
 910        "failed to mount: {:?}",
 911        String::from_utf8_lossy(&output.stderr)
 912    );
 913
 914    // Create an MacOsUnmounter that will be dropped (and thus unmount the disk) when this function exits
 915    let _unmounter = MacOsUnmounter {
 916        mount_path: mount_path.clone(),
 917        background_executor: cx.background_executor(),
 918    };
 919
 920    let output = Command::new("rsync")
 921        .args(["-av", "--delete"])
 922        .arg(&mounted_app_path)
 923        .arg(&running_app_path)
 924        .output()
 925        .await?;
 926
 927    anyhow::ensure!(
 928        output.status.success(),
 929        "failed to copy app: {:?}",
 930        String::from_utf8_lossy(&output.stderr)
 931    );
 932
 933    Ok(None)
 934}
 935
 936#[cfg(target_os = "windows")]
 937async fn cleanup_windows() -> Result<()> {
 938    use util::ResultExt;
 939
 940    let parent = std::env::current_exe()?
 941        .parent()
 942        .context("No parent dir for Zed.exe")?
 943        .to_owned();
 944
 945    // keep in sync with crates/auto_update_helper/src/updater.rs
 946    smol::fs::remove_dir(parent.join("updates"))
 947        .await
 948        .context("failed to remove updates dir")
 949        .log_err();
 950    smol::fs::remove_dir(parent.join("install"))
 951        .await
 952        .context("failed to remove install dir")
 953        .log_err();
 954    smol::fs::remove_dir(parent.join("old"))
 955        .await
 956        .context("failed to remove old version dir")
 957        .log_err();
 958
 959    Ok(())
 960}
 961
 962async fn install_release_windows(downloaded_installer: PathBuf) -> Result<Option<PathBuf>> {
 963    let output = Command::new(downloaded_installer)
 964        .arg("/verysilent")
 965        .arg("/update=true")
 966        .arg("!desktopicon")
 967        .arg("!quicklaunchicon")
 968        .output()
 969        .await?;
 970    anyhow::ensure!(
 971        output.status.success(),
 972        "failed to start installer: {:?}",
 973        String::from_utf8_lossy(&output.stderr)
 974    );
 975    // We return the path to the update helper program, because it will
 976    // perform the final steps of the update process, copying the new binary,
 977    // deleting the old one, and launching the new binary.
 978    let helper_path = std::env::current_exe()?
 979        .parent()
 980        .context("No parent dir for Zed.exe")?
 981        .join("tools")
 982        .join("auto_update_helper.exe");
 983    Ok(Some(helper_path))
 984}
 985
 986pub async fn finalize_auto_update_on_quit() {
 987    let Some(installer_path) = std::env::current_exe()
 988        .ok()
 989        .and_then(|p| p.parent().map(|p| p.join("updates")))
 990    else {
 991        return;
 992    };
 993
 994    // The installer will create a flag file after it finishes updating
 995    let flag_file = installer_path.join("versions.txt");
 996    if flag_file.exists()
 997        && let Some(helper) = installer_path
 998            .parent()
 999            .map(|p| p.join("tools").join("auto_update_helper.exe"))
1000    {
1001        let mut command = util::command::new_smol_command(helper);
1002        command.arg("--launch");
1003        command.arg("false");
1004        if let Ok(mut cmd) = command.spawn() {
1005            _ = cmd.status().await;
1006        }
1007    }
1008}
1009
1010#[cfg(test)]
1011mod tests {
1012    use gpui::TestAppContext;
1013    use settings::default_settings;
1014
1015    use super::*;
1016
1017    #[gpui::test]
1018    fn test_auto_update_defaults_to_true(cx: &mut TestAppContext) {
1019        cx.update(|cx| {
1020            let mut store = SettingsStore::new(cx, &settings::default_settings());
1021            store
1022                .set_default_settings(&default_settings(), cx)
1023                .expect("Unable to set default settings");
1024            store
1025                .set_user_settings("{}", cx)
1026                .expect("Unable to set user settings");
1027            cx.set_global(store);
1028            AutoUpdateSetting::register(cx);
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}