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