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