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