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