auto_update.rs

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