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