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