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