auto_update.rs

  1mod update_notification;
  2
  3use anyhow::{anyhow, Context, Result};
  4use client::{Client, TelemetrySettings};
  5use db::kvp::KEY_VALUE_STORE;
  6use db::RELEASE_CHANNEL;
  7use editor::{Editor, MultiBuffer};
  8use gpui::{
  9    actions, AppContext, AsyncAppContext, Context as _, Global, Model, ModelContext,
 10    SemanticVersion, SharedString, Task, View, ViewContext, VisualContext, WindowContext,
 11};
 12
 13use markdown_preview::markdown_preview_view::{MarkdownPreviewMode, MarkdownPreviewView};
 14use schemars::JsonSchema;
 15use serde::Deserialize;
 16use serde_derive::Serialize;
 17use smol::{fs, io::AsyncReadExt};
 18
 19use settings::{Settings, SettingsSources, SettingsStore};
 20use smol::{fs::File, process::Command};
 21
 22use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
 23use release_channel::{AppCommitSha, AppVersion, ReleaseChannel};
 24use std::{
 25    env::{
 26        self,
 27        consts::{ARCH, OS},
 28    },
 29    ffi::OsString,
 30    path::{Path, PathBuf},
 31    sync::Arc,
 32    time::Duration,
 33};
 34use update_notification::UpdateNotification;
 35use util::ResultExt;
 36use workspace::notifications::NotificationId;
 37use workspace::Workspace;
 38
 39const SHOULD_SHOW_UPDATE_NOTIFICATION_KEY: &str = "auto-updater-should-show-updated-notification";
 40const POLL_INTERVAL: Duration = Duration::from_secs(60 * 60);
 41
 42actions!(
 43    auto_update,
 44    [
 45        Check,
 46        DismissErrorMessage,
 47        ViewReleaseNotes,
 48        ViewReleaseNotesLocally
 49    ]
 50);
 51
 52#[derive(Serialize)]
 53struct UpdateRequestBody {
 54    installation_id: Option<Arc<str>>,
 55    release_channel: Option<&'static str>,
 56    telemetry: bool,
 57    is_staff: Option<bool>,
 58    destination: &'static str,
 59}
 60
 61#[derive(Clone, PartialEq, Eq)]
 62pub enum AutoUpdateStatus {
 63    Idle,
 64    Checking,
 65    Downloading,
 66    Installing,
 67    Updated { binary_path: PathBuf },
 68    Errored,
 69}
 70
 71impl AutoUpdateStatus {
 72    pub fn is_updated(&self) -> bool {
 73        matches!(self, Self::Updated { .. })
 74    }
 75}
 76
 77pub struct AutoUpdater {
 78    status: AutoUpdateStatus,
 79    current_version: SemanticVersion,
 80    http_client: Arc<HttpClientWithUrl>,
 81    pending_poll: Option<Task<Option<()>>>,
 82}
 83
 84#[derive(Deserialize)]
 85struct JsonRelease {
 86    version: String,
 87    url: String,
 88}
 89
 90struct MacOsUnmounter {
 91    mount_path: PathBuf,
 92}
 93
 94impl Drop for MacOsUnmounter {
 95    fn drop(&mut self) {
 96        let unmount_output = std::process::Command::new("hdiutil")
 97            .args(["detach", "-force"])
 98            .arg(&self.mount_path)
 99            .output();
100
101        match unmount_output {
102            Ok(output) if output.status.success() => {
103                log::info!("Successfully unmounted the disk image");
104            }
105            Ok(output) => {
106                log::error!(
107                    "Failed to unmount disk image: {:?}",
108                    String::from_utf8_lossy(&output.stderr)
109                );
110            }
111            Err(error) => {
112                log::error!("Error while trying to unmount disk image: {:?}", error);
113            }
114        }
115    }
116}
117
118struct AutoUpdateSetting(bool);
119
120/// Whether or not to automatically check for updates.
121///
122/// Default: true
123#[derive(Clone, Copy, Default, JsonSchema, Deserialize, Serialize)]
124#[serde(transparent)]
125struct AutoUpdateSettingContent(bool);
126
127impl Settings for AutoUpdateSetting {
128    const KEY: Option<&'static str> = Some("auto_update");
129
130    type FileContent = Option<AutoUpdateSettingContent>;
131
132    fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
133        let auto_update = [sources.release_channel, sources.user]
134            .into_iter()
135            .find_map(|value| value.copied().flatten())
136            .unwrap_or(sources.default.ok_or_else(Self::missing_default)?);
137
138        Ok(Self(auto_update.0))
139    }
140}
141
142#[derive(Default)]
143struct GlobalAutoUpdate(Option<Model<AutoUpdater>>);
144
145impl Global for GlobalAutoUpdate {}
146
147#[derive(Deserialize)]
148struct ReleaseNotesBody {
149    title: String,
150    release_notes: String,
151}
152
153pub fn init(http_client: Arc<HttpClientWithUrl>, cx: &mut AppContext) {
154    AutoUpdateSetting::register(cx);
155
156    cx.observe_new_views(|workspace: &mut Workspace, _cx| {
157        workspace.register_action(|_, action: &Check, cx| check(action, cx));
158
159        workspace.register_action(|_, action, cx| {
160            view_release_notes(action, cx);
161        });
162
163        workspace.register_action(|workspace, _: &ViewReleaseNotesLocally, cx| {
164            view_release_notes_locally(workspace, cx);
165        });
166    })
167    .detach();
168
169    let version = release_channel::AppVersion::global(cx);
170    let auto_updater = cx.new_model(|cx| {
171        let updater = AutoUpdater::new(version, http_client);
172
173        let poll_for_updates = ReleaseChannel::try_global(cx)
174            .map(|channel| channel.poll_for_updates())
175            .unwrap_or(false);
176
177        if option_env!("ZED_UPDATE_EXPLANATION").is_none()
178            && env::var("ZED_UPDATE_EXPLANATION").is_err()
179            && poll_for_updates
180        {
181            let mut update_subscription = AutoUpdateSetting::get_global(cx)
182                .0
183                .then(|| updater.start_polling(cx));
184
185            cx.observe_global::<SettingsStore>(move |updater, cx| {
186                if AutoUpdateSetting::get_global(cx).0 {
187                    if update_subscription.is_none() {
188                        update_subscription = Some(updater.start_polling(cx))
189                    }
190                } else {
191                    update_subscription.take();
192                }
193            })
194            .detach();
195        }
196
197        updater
198    });
199    cx.set_global(GlobalAutoUpdate(Some(auto_updater)));
200}
201
202pub fn check(_: &Check, cx: &mut WindowContext) {
203    if let Some(message) = option_env!("ZED_UPDATE_EXPLANATION") {
204        drop(cx.prompt(
205            gpui::PromptLevel::Info,
206            "Zed was installed via a package manager.",
207            Some(message),
208            &["Ok"],
209        ));
210        return;
211    }
212
213    if let Ok(message) = env::var("ZED_UPDATE_EXPLANATION") {
214        drop(cx.prompt(
215            gpui::PromptLevel::Info,
216            "Zed was installed via a package manager.",
217            Some(&message),
218            &["Ok"],
219        ));
220        return;
221    }
222
223    if !ReleaseChannel::try_global(cx)
224        .map(|channel| channel.poll_for_updates())
225        .unwrap_or(false)
226    {
227        return;
228    }
229
230    if let Some(updater) = AutoUpdater::get(cx) {
231        updater.update(cx, |updater, cx| updater.poll(cx));
232    } else {
233        drop(cx.prompt(
234            gpui::PromptLevel::Info,
235            "Could not check for updates",
236            Some("Auto-updates disabled for non-bundled app."),
237            &["Ok"],
238        ));
239    }
240}
241
242pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut AppContext) -> Option<()> {
243    let auto_updater = AutoUpdater::get(cx)?;
244    let release_channel = ReleaseChannel::try_global(cx)?;
245
246    match release_channel {
247        ReleaseChannel::Stable | ReleaseChannel::Preview => {
248            let auto_updater = auto_updater.read(cx);
249            let current_version = auto_updater.current_version;
250            let release_channel = release_channel.dev_name();
251            let path = format!("/releases/{release_channel}/{current_version}");
252            let url = &auto_updater.http_client.build_url(&path);
253            cx.open_url(url);
254        }
255        ReleaseChannel::Nightly => {
256            cx.open_url("https://github.com/zed-industries/zed/commits/nightly/");
257        }
258        ReleaseChannel::Dev => {
259            cx.open_url("https://github.com/zed-industries/zed/commits/main/");
260        }
261    }
262    None
263}
264
265fn view_release_notes_locally(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
266    let release_channel = ReleaseChannel::global(cx);
267
268    let url = match release_channel {
269        ReleaseChannel::Nightly => Some("https://github.com/zed-industries/zed/commits/nightly/"),
270        ReleaseChannel::Dev => Some("https://github.com/zed-industries/zed/commits/main/"),
271        _ => None,
272    };
273
274    if let Some(url) = url {
275        cx.open_url(url);
276        return;
277    }
278
279    let version = AppVersion::global(cx).to_string();
280
281    let client = client::Client::global(cx).http_client();
282    let url = client.build_url(&format!(
283        "/api/release_notes/v2/{}/{}",
284        release_channel.dev_name(),
285        version
286    ));
287
288    let markdown = workspace
289        .app_state()
290        .languages
291        .language_for_name("Markdown");
292
293    workspace
294        .with_local_workspace(cx, move |_, cx| {
295            cx.spawn(|workspace, mut cx| async move {
296                let markdown = markdown.await.log_err();
297                let response = client.get(&url, Default::default(), true).await;
298                let Some(mut response) = response.log_err() else {
299                    return;
300                };
301
302                let mut body = Vec::new();
303                response.body_mut().read_to_end(&mut body).await.ok();
304
305                let body: serde_json::Result<ReleaseNotesBody> =
306                    serde_json::from_slice(body.as_slice());
307
308                if let Ok(body) = body {
309                    workspace
310                        .update(&mut cx, |workspace, cx| {
311                            let project = workspace.project().clone();
312                            let buffer = project.update(cx, |project, cx| {
313                                project.create_local_buffer("", markdown, cx)
314                            });
315                            buffer.update(cx, |buffer, cx| {
316                                buffer.edit([(0..0, body.release_notes)], None, cx)
317                            });
318                            let language_registry = project.read(cx).languages().clone();
319
320                            let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
321
322                            let tab_description = SharedString::from(body.title.to_string());
323                            let editor = cx.new_view(|cx| {
324                                Editor::for_multibuffer(buffer, Some(project), true, cx)
325                            });
326                            let workspace_handle = workspace.weak_handle();
327                            let view: View<MarkdownPreviewView> = MarkdownPreviewView::new(
328                                MarkdownPreviewMode::Default,
329                                editor,
330                                workspace_handle,
331                                language_registry,
332                                Some(tab_description),
333                                cx,
334                            );
335                            workspace.add_item_to_active_pane(
336                                Box::new(view.clone()),
337                                None,
338                                true,
339                                cx,
340                            );
341                            cx.notify();
342                        })
343                        .log_err();
344                }
345            })
346            .detach();
347        })
348        .detach();
349}
350
351pub fn notify_of_any_new_update(cx: &mut ViewContext<Workspace>) -> Option<()> {
352    let updater = AutoUpdater::get(cx)?;
353    let version = updater.read(cx).current_version;
354    let should_show_notification = updater.read(cx).should_show_update_notification(cx);
355
356    cx.spawn(|workspace, mut cx| async move {
357        let should_show_notification = should_show_notification.await?;
358        if should_show_notification {
359            workspace.update(&mut cx, |workspace, cx| {
360                let workspace_handle = workspace.weak_handle();
361                workspace.show_notification(
362                    NotificationId::unique::<UpdateNotification>(),
363                    cx,
364                    |cx| cx.new_view(|_| UpdateNotification::new(version, workspace_handle)),
365                );
366                updater.update(cx, |updater, cx| {
367                    updater
368                        .set_should_show_update_notification(false, cx)
369                        .detach_and_log_err(cx);
370                });
371            })?;
372        }
373        anyhow::Ok(())
374    })
375    .detach();
376
377    None
378}
379
380impl AutoUpdater {
381    pub fn get(cx: &mut AppContext) -> Option<Model<Self>> {
382        cx.default_global::<GlobalAutoUpdate>().0.clone()
383    }
384
385    fn new(current_version: SemanticVersion, http_client: Arc<HttpClientWithUrl>) -> Self {
386        Self {
387            status: AutoUpdateStatus::Idle,
388            current_version,
389            http_client,
390            pending_poll: None,
391        }
392    }
393
394    pub fn start_polling(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
395        cx.spawn(|this, mut cx| async move {
396            loop {
397                this.update(&mut cx, |this, cx| this.poll(cx))?;
398                cx.background_executor().timer(POLL_INTERVAL).await;
399            }
400        })
401    }
402
403    pub fn poll(&mut self, cx: &mut ModelContext<Self>) {
404        if self.pending_poll.is_some() || self.status.is_updated() {
405            return;
406        }
407
408        cx.notify();
409
410        self.pending_poll = Some(cx.spawn(|this, mut cx| async move {
411            let result = Self::update(this.upgrade()?, cx.clone()).await;
412            this.update(&mut cx, |this, cx| {
413                this.pending_poll = None;
414                if let Err(error) = result {
415                    log::error!("auto-update failed: error:{:?}", error);
416                    this.status = AutoUpdateStatus::Errored;
417                    cx.notify();
418                }
419            })
420            .ok()
421        }));
422    }
423
424    pub fn status(&self) -> AutoUpdateStatus {
425        self.status.clone()
426    }
427
428    pub fn dismiss_error(&mut self, cx: &mut ModelContext<Self>) {
429        self.status = AutoUpdateStatus::Idle;
430        cx.notify();
431    }
432
433    pub async fn get_latest_remote_server_release(
434        os: &str,
435        arch: &str,
436        mut release_channel: ReleaseChannel,
437        cx: &mut AsyncAppContext,
438    ) -> Result<PathBuf> {
439        let this = cx.update(|cx| {
440            cx.default_global::<GlobalAutoUpdate>()
441                .0
442                .clone()
443                .ok_or_else(|| anyhow!("auto-update not initialized"))
444        })??;
445
446        if release_channel == ReleaseChannel::Dev {
447            release_channel = ReleaseChannel::Nightly;
448        }
449
450        let release = Self::get_latest_release(
451            &this,
452            "zed-remote-server",
453            os,
454            arch,
455            Some(release_channel),
456            cx,
457        )
458        .await?;
459
460        let servers_dir = paths::remote_servers_dir();
461        let channel_dir = servers_dir.join(release_channel.dev_name());
462        let platform_dir = channel_dir.join(format!("{}-{}", os, arch));
463        let version_path = platform_dir.join(format!("{}.gz", release.version));
464        smol::fs::create_dir_all(&platform_dir).await.ok();
465
466        let client = this.read_with(cx, |this, _| this.http_client.clone())?;
467        if smol::fs::metadata(&version_path).await.is_err() {
468            log::info!("downloading zed-remote-server {os} {arch}");
469            download_remote_server_binary(&version_path, release, client, cx).await?;
470        }
471
472        Ok(version_path)
473    }
474
475    async fn get_latest_release(
476        this: &Model<Self>,
477        asset: &str,
478        os: &str,
479        arch: &str,
480        release_channel: Option<ReleaseChannel>,
481        cx: &mut AsyncAppContext,
482    ) -> Result<JsonRelease> {
483        let client = this.read_with(cx, |this, _| this.http_client.clone())?;
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
495        let mut body = Vec::new();
496        response
497            .body_mut()
498            .read_to_end(&mut body)
499            .await
500            .context("error reading release")?;
501
502        if !response.status().is_success() {
503            Err(anyhow!(
504                "failed to fetch release: {:?}",
505                String::from_utf8_lossy(&body),
506            ))?;
507        }
508
509        serde_json::from_slice(body.as_slice()).with_context(|| {
510            format!(
511                "error deserializing release {:?}",
512                String::from_utf8_lossy(&body),
513            )
514        })
515    }
516
517    async fn update(this: Model<Self>, mut cx: AsyncAppContext) -> Result<()> {
518        let (client, current_version, release_channel) = this.update(&mut cx, |this, cx| {
519            this.status = AutoUpdateStatus::Checking;
520            cx.notify();
521            (
522                this.http_client.clone(),
523                this.current_version,
524                ReleaseChannel::try_global(cx),
525            )
526        })?;
527
528        let release =
529            Self::get_latest_release(&this, "zed", OS, ARCH, release_channel, &mut cx).await?;
530
531        let should_download = match *RELEASE_CHANNEL {
532            ReleaseChannel::Nightly => cx
533                .update(|cx| AppCommitSha::try_global(cx).map(|sha| release.version != sha.0))
534                .ok()
535                .flatten()
536                .unwrap_or(true),
537            _ => release.version.parse::<SemanticVersion>()? > current_version,
538        };
539
540        if !should_download {
541            this.update(&mut cx, |this, cx| {
542                this.status = AutoUpdateStatus::Idle;
543                cx.notify();
544            })?;
545            return Ok(());
546        }
547
548        this.update(&mut cx, |this, cx| {
549            this.status = AutoUpdateStatus::Downloading;
550            cx.notify();
551        })?;
552
553        let temp_dir = tempfile::Builder::new()
554            .prefix("zed-auto-update")
555            .tempdir()?;
556
557        let filename = match OS {
558            "macos" => Ok("Zed.dmg"),
559            "linux" => Ok("zed.tar.gz"),
560            _ => Err(anyhow!("not supported: {:?}", OS)),
561        }?;
562        let downloaded_asset = temp_dir.path().join(filename);
563        download_release(&downloaded_asset, release, client, &cx).await?;
564
565        this.update(&mut cx, |this, cx| {
566            this.status = AutoUpdateStatus::Installing;
567            cx.notify();
568        })?;
569
570        let binary_path = match OS {
571            "macos" => install_release_macos(&temp_dir, downloaded_asset, &cx).await,
572            "linux" => install_release_linux(&temp_dir, downloaded_asset, &cx).await,
573            _ => Err(anyhow!("not supported: {:?}", OS)),
574        }?;
575
576        this.update(&mut cx, |this, cx| {
577            this.set_should_show_update_notification(true, cx)
578                .detach_and_log_err(cx);
579            this.status = AutoUpdateStatus::Updated { binary_path };
580            cx.notify();
581        })?;
582
583        Ok(())
584    }
585
586    fn set_should_show_update_notification(
587        &self,
588        should_show: bool,
589        cx: &AppContext,
590    ) -> Task<Result<()>> {
591        cx.background_executor().spawn(async move {
592            if should_show {
593                KEY_VALUE_STORE
594                    .write_kvp(
595                        SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
596                        "".to_string(),
597                    )
598                    .await?;
599            } else {
600                KEY_VALUE_STORE
601                    .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
602                    .await?;
603            }
604            Ok(())
605        })
606    }
607
608    fn should_show_update_notification(&self, cx: &AppContext) -> Task<Result<bool>> {
609        cx.background_executor().spawn(async move {
610            Ok(KEY_VALUE_STORE
611                .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
612                .is_some())
613        })
614    }
615}
616
617async fn download_remote_server_binary(
618    target_path: &PathBuf,
619    release: JsonRelease,
620    client: Arc<HttpClientWithUrl>,
621    cx: &AsyncAppContext,
622) -> Result<()> {
623    let mut target_file = File::create(&target_path).await?;
624    let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
625        let telemetry = Client::global(cx).telemetry().clone();
626        let is_staff = telemetry.is_staff();
627        let installation_id = telemetry.installation_id();
628        let release_channel =
629            ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
630        let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
631
632        (
633            installation_id,
634            release_channel,
635            telemetry_enabled,
636            is_staff,
637        )
638    })?;
639    let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
640        installation_id,
641        release_channel,
642        telemetry: telemetry_enabled,
643        is_staff,
644        destination: "remote",
645    })?);
646
647    let mut response = client.get(&release.url, request_body, true).await?;
648    smol::io::copy(response.body_mut(), &mut target_file).await?;
649    Ok(())
650}
651
652async fn download_release(
653    target_path: &Path,
654    release: JsonRelease,
655    client: Arc<HttpClientWithUrl>,
656    cx: &AsyncAppContext,
657) -> Result<()> {
658    let mut target_file = File::create(&target_path).await?;
659
660    let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
661        let telemetry = Client::global(cx).telemetry().clone();
662        let is_staff = telemetry.is_staff();
663        let installation_id = telemetry.installation_id();
664        let release_channel =
665            ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
666        let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
667
668        (
669            installation_id,
670            release_channel,
671            telemetry_enabled,
672            is_staff,
673        )
674    })?;
675
676    let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
677        installation_id,
678        release_channel,
679        telemetry: telemetry_enabled,
680        is_staff,
681        destination: "local",
682    })?);
683
684    let mut response = client.get(&release.url, request_body, true).await?;
685    smol::io::copy(response.body_mut(), &mut target_file).await?;
686    log::info!("downloaded update. path:{:?}", target_path);
687
688    Ok(())
689}
690
691async fn install_release_linux(
692    temp_dir: &tempfile::TempDir,
693    downloaded_tar_gz: PathBuf,
694    cx: &AsyncAppContext,
695) -> Result<PathBuf> {
696    let channel = cx.update(|cx| ReleaseChannel::global(cx).dev_name())?;
697    let home_dir = PathBuf::from(env::var("HOME").context("no HOME env var set")?);
698    let running_app_path = cx.update(|cx| cx.app_path())??;
699
700    let extracted = temp_dir.path().join("zed");
701    fs::create_dir_all(&extracted)
702        .await
703        .context("failed to create directory into which to extract update")?;
704
705    let output = Command::new("tar")
706        .arg("-xzf")
707        .arg(&downloaded_tar_gz)
708        .arg("-C")
709        .arg(&extracted)
710        .output()
711        .await?;
712
713    anyhow::ensure!(
714        output.status.success(),
715        "failed to extract {:?} to {:?}: {:?}",
716        downloaded_tar_gz,
717        extracted,
718        String::from_utf8_lossy(&output.stderr)
719    );
720
721    let suffix = if channel != "stable" {
722        format!("-{}", channel)
723    } else {
724        String::default()
725    };
726    let app_folder_name = format!("zed{}.app", suffix);
727
728    let from = extracted.join(&app_folder_name);
729    let mut to = home_dir.join(".local");
730
731    let expected_suffix = format!("{}/libexec/zed-editor", app_folder_name);
732
733    if let Some(prefix) = running_app_path
734        .to_str()
735        .and_then(|str| str.strip_suffix(&expected_suffix))
736    {
737        to = PathBuf::from(prefix);
738    }
739
740    let output = Command::new("rsync")
741        .args(["-av", "--delete"])
742        .arg(&from)
743        .arg(&to)
744        .output()
745        .await?;
746
747    anyhow::ensure!(
748        output.status.success(),
749        "failed to copy Zed update from {:?} to {:?}: {:?}",
750        from,
751        to,
752        String::from_utf8_lossy(&output.stderr)
753    );
754
755    Ok(to.join(expected_suffix))
756}
757
758async fn install_release_macos(
759    temp_dir: &tempfile::TempDir,
760    downloaded_dmg: PathBuf,
761    cx: &AsyncAppContext,
762) -> Result<PathBuf> {
763    let running_app_path = cx.update(|cx| cx.app_path())??;
764    let running_app_filename = running_app_path
765        .file_name()
766        .ok_or_else(|| anyhow!("invalid running app path"))?;
767
768    let mount_path = temp_dir.path().join("Zed");
769    let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
770
771    mounted_app_path.push("/");
772    let output = Command::new("hdiutil")
773        .args(["attach", "-nobrowse"])
774        .arg(&downloaded_dmg)
775        .arg("-mountroot")
776        .arg(temp_dir.path())
777        .output()
778        .await?;
779
780    anyhow::ensure!(
781        output.status.success(),
782        "failed to mount: {:?}",
783        String::from_utf8_lossy(&output.stderr)
784    );
785
786    // Create an MacOsUnmounter that will be dropped (and thus unmount the disk) when this function exits
787    let _unmounter = MacOsUnmounter {
788        mount_path: mount_path.clone(),
789    };
790
791    let output = Command::new("rsync")
792        .args(["-av", "--delete"])
793        .arg(&mounted_app_path)
794        .arg(&running_app_path)
795        .output()
796        .await?;
797
798    anyhow::ensure!(
799        output.status.success(),
800        "failed to copy app: {:?}",
801        String::from_utf8_lossy(&output.stderr)
802    );
803
804    Ok(running_app_path)
805}