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.server, 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
468        if smol::fs::metadata(&version_path).await.is_err() {
469            log::info!("downloading zed-remote-server {os} {arch}");
470            download_remote_server_binary(&version_path, release, client, cx).await?;
471        }
472
473        Ok(version_path)
474    }
475
476    async fn get_latest_release(
477        this: &Model<Self>,
478        asset: &str,
479        os: &str,
480        arch: &str,
481        release_channel: Option<ReleaseChannel>,
482        cx: &mut AsyncAppContext,
483    ) -> Result<JsonRelease> {
484        let client = this.read_with(cx, |this, _| this.http_client.clone())?;
485        let mut url_string = client.build_url(&format!(
486            "/api/releases/latest?asset={}&os={}&arch={}",
487            asset, os, arch
488        ));
489        if let Some(param) = release_channel.and_then(|c| c.release_query_param()) {
490            url_string += "&";
491            url_string += param;
492        }
493
494        let mut response = client.get(&url_string, Default::default(), true).await?;
495
496        let mut body = Vec::new();
497        response
498            .body_mut()
499            .read_to_end(&mut body)
500            .await
501            .context("error reading release")?;
502
503        if !response.status().is_success() {
504            Err(anyhow!(
505                "failed to fetch release: {:?}",
506                String::from_utf8_lossy(&body),
507            ))?;
508        }
509
510        serde_json::from_slice(body.as_slice()).with_context(|| {
511            format!(
512                "error deserializing release {:?}",
513                String::from_utf8_lossy(&body),
514            )
515        })
516    }
517
518    async fn update(this: Model<Self>, mut cx: AsyncAppContext) -> Result<()> {
519        let (client, current_version, release_channel) = this.update(&mut cx, |this, cx| {
520            this.status = AutoUpdateStatus::Checking;
521            cx.notify();
522            (
523                this.http_client.clone(),
524                this.current_version,
525                ReleaseChannel::try_global(cx),
526            )
527        })?;
528
529        let release =
530            Self::get_latest_release(&this, "zed", OS, ARCH, release_channel, &mut cx).await?;
531
532        let should_download = match *RELEASE_CHANNEL {
533            ReleaseChannel::Nightly => cx
534                .update(|cx| AppCommitSha::try_global(cx).map(|sha| release.version != sha.0))
535                .ok()
536                .flatten()
537                .unwrap_or(true),
538            _ => release.version.parse::<SemanticVersion>()? > current_version,
539        };
540
541        if !should_download {
542            this.update(&mut cx, |this, cx| {
543                this.status = AutoUpdateStatus::Idle;
544                cx.notify();
545            })?;
546            return Ok(());
547        }
548
549        this.update(&mut cx, |this, cx| {
550            this.status = AutoUpdateStatus::Downloading;
551            cx.notify();
552        })?;
553
554        let temp_dir = tempfile::Builder::new()
555            .prefix("zed-auto-update")
556            .tempdir()?;
557
558        let filename = match OS {
559            "macos" => Ok("Zed.dmg"),
560            "linux" => Ok("zed.tar.gz"),
561            _ => Err(anyhow!("not supported: {:?}", OS)),
562        }?;
563        let downloaded_asset = temp_dir.path().join(filename);
564        download_release(&downloaded_asset, release, client, &cx).await?;
565
566        this.update(&mut cx, |this, cx| {
567            this.status = AutoUpdateStatus::Installing;
568            cx.notify();
569        })?;
570
571        let binary_path = match OS {
572            "macos" => install_release_macos(&temp_dir, downloaded_asset, &cx).await,
573            "linux" => install_release_linux(&temp_dir, downloaded_asset, &cx).await,
574            _ => Err(anyhow!("not supported: {:?}", OS)),
575        }?;
576
577        this.update(&mut cx, |this, cx| {
578            this.set_should_show_update_notification(true, cx)
579                .detach_and_log_err(cx);
580            this.status = AutoUpdateStatus::Updated { binary_path };
581            cx.notify();
582        })?;
583
584        Ok(())
585    }
586
587    fn set_should_show_update_notification(
588        &self,
589        should_show: bool,
590        cx: &AppContext,
591    ) -> Task<Result<()>> {
592        cx.background_executor().spawn(async move {
593            if should_show {
594                KEY_VALUE_STORE
595                    .write_kvp(
596                        SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
597                        "".to_string(),
598                    )
599                    .await?;
600            } else {
601                KEY_VALUE_STORE
602                    .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
603                    .await?;
604            }
605            Ok(())
606        })
607    }
608
609    fn should_show_update_notification(&self, cx: &AppContext) -> Task<Result<bool>> {
610        cx.background_executor().spawn(async move {
611            Ok(KEY_VALUE_STORE
612                .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
613                .is_some())
614        })
615    }
616}
617
618async fn download_remote_server_binary(
619    target_path: &PathBuf,
620    release: JsonRelease,
621    client: Arc<HttpClientWithUrl>,
622    cx: &AsyncAppContext,
623) -> Result<()> {
624    let mut target_file = File::create(&target_path).await?;
625    let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
626        let telemetry = Client::global(cx).telemetry().clone();
627        let is_staff = telemetry.is_staff();
628        let installation_id = telemetry.installation_id();
629        let release_channel =
630            ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
631        let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
632
633        (
634            installation_id,
635            release_channel,
636            telemetry_enabled,
637            is_staff,
638        )
639    })?;
640    let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
641        installation_id,
642        release_channel,
643        telemetry: telemetry_enabled,
644        is_staff,
645        destination: "remote",
646    })?);
647
648    let mut response = client.get(&release.url, request_body, true).await?;
649    smol::io::copy(response.body_mut(), &mut target_file).await?;
650    Ok(())
651}
652
653async fn download_release(
654    target_path: &Path,
655    release: JsonRelease,
656    client: Arc<HttpClientWithUrl>,
657    cx: &AsyncAppContext,
658) -> Result<()> {
659    let mut target_file = File::create(&target_path).await?;
660
661    let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
662        let telemetry = Client::global(cx).telemetry().clone();
663        let is_staff = telemetry.is_staff();
664        let installation_id = telemetry.installation_id();
665        let release_channel =
666            ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
667        let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
668
669        (
670            installation_id,
671            release_channel,
672            telemetry_enabled,
673            is_staff,
674        )
675    })?;
676
677    let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
678        installation_id,
679        release_channel,
680        telemetry: telemetry_enabled,
681        is_staff,
682        destination: "local",
683    })?);
684
685    let mut response = client.get(&release.url, request_body, true).await?;
686    smol::io::copy(response.body_mut(), &mut target_file).await?;
687    log::info!("downloaded update. path:{:?}", target_path);
688
689    Ok(())
690}
691
692async fn install_release_linux(
693    temp_dir: &tempfile::TempDir,
694    downloaded_tar_gz: PathBuf,
695    cx: &AsyncAppContext,
696) -> Result<PathBuf> {
697    let channel = cx.update(|cx| ReleaseChannel::global(cx).dev_name())?;
698    let home_dir = PathBuf::from(env::var("HOME").context("no HOME env var set")?);
699    let running_app_path = cx.update(|cx| cx.app_path())??;
700
701    let extracted = temp_dir.path().join("zed");
702    fs::create_dir_all(&extracted)
703        .await
704        .context("failed to create directory into which to extract update")?;
705
706    let output = Command::new("tar")
707        .arg("-xzf")
708        .arg(&downloaded_tar_gz)
709        .arg("-C")
710        .arg(&extracted)
711        .output()
712        .await?;
713
714    anyhow::ensure!(
715        output.status.success(),
716        "failed to extract {:?} to {:?}: {:?}",
717        downloaded_tar_gz,
718        extracted,
719        String::from_utf8_lossy(&output.stderr)
720    );
721
722    let suffix = if channel != "stable" {
723        format!("-{}", channel)
724    } else {
725        String::default()
726    };
727    let app_folder_name = format!("zed{}.app", suffix);
728
729    let from = extracted.join(&app_folder_name);
730    let mut to = home_dir.join(".local");
731
732    let expected_suffix = format!("{}/libexec/zed-editor", app_folder_name);
733
734    if let Some(prefix) = running_app_path
735        .to_str()
736        .and_then(|str| str.strip_suffix(&expected_suffix))
737    {
738        to = PathBuf::from(prefix);
739    }
740
741    let output = Command::new("rsync")
742        .args(["-av", "--delete"])
743        .arg(&from)
744        .arg(&to)
745        .output()
746        .await?;
747
748    anyhow::ensure!(
749        output.status.success(),
750        "failed to copy Zed update from {:?} to {:?}: {:?}",
751        from,
752        to,
753        String::from_utf8_lossy(&output.stderr)
754    );
755
756    Ok(to.join(expected_suffix))
757}
758
759async fn install_release_macos(
760    temp_dir: &tempfile::TempDir,
761    downloaded_dmg: PathBuf,
762    cx: &AsyncAppContext,
763) -> Result<PathBuf> {
764    let running_app_path = cx.update(|cx| cx.app_path())??;
765    let running_app_filename = running_app_path
766        .file_name()
767        .ok_or_else(|| anyhow!("invalid running app path"))?;
768
769    let mount_path = temp_dir.path().join("Zed");
770    let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
771
772    mounted_app_path.push("/");
773    let output = Command::new("hdiutil")
774        .args(["attach", "-nobrowse"])
775        .arg(&downloaded_dmg)
776        .arg("-mountroot")
777        .arg(temp_dir.path())
778        .output()
779        .await?;
780
781    anyhow::ensure!(
782        output.status.success(),
783        "failed to mount: {:?}",
784        String::from_utf8_lossy(&output.stderr)
785    );
786
787    // Create an MacOsUnmounter that will be dropped (and thus unmount the disk) when this function exits
788    let _unmounter = MacOsUnmounter {
789        mount_path: mount_path.clone(),
790    };
791
792    let output = Command::new("rsync")
793        .args(["-av", "--delete"])
794        .arg(&mounted_app_path)
795        .arg(&running_app_path)
796        .output()
797        .await?;
798
799    anyhow::ensure!(
800        output.status.success(),
801        "failed to copy app: {:?}",
802        String::from_utf8_lossy(&output.stderr)
803    );
804
805    Ok(running_app_path)
806}