auto_update.rs

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