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 = parsed_fetched_version
641 .as_ref()
642 .ok()
643 .is_none_or(|version| version.build.as_str() != cached_version.full());
644 let newer_version = should_download
645 .then(|| VersionCheckType::Sha(AppCommitSha::new(fetched_version)));
646 return Ok(newer_version);
647 }
648 VersionCheckType::Semantic(cached_version) => {
649 return Self::check_if_fetched_version_is_newer_non_nightly(
650 cached_version,
651 parsed_fetched_version?,
652 );
653 }
654 }
655 }
656
657 match release_channel {
658 ReleaseChannel::Nightly => {
659 let should_download = app_commit_sha
660 .ok()
661 .flatten()
662 .map(|sha| {
663 parsed_fetched_version
664 .as_ref()
665 .ok()
666 .is_none_or(|version| version.build.as_str() != sha)
667 })
668 .unwrap_or(true);
669 let newer_version = should_download
670 .then(|| VersionCheckType::Sha(AppCommitSha::new(fetched_version)));
671 Ok(newer_version)
672 }
673 _ => Self::check_if_fetched_version_is_newer_non_nightly(
674 installed_version,
675 parsed_fetched_version?,
676 ),
677 }
678 }
679
680 fn check_dependencies() -> Result<()> {
681 #[cfg(not(target_os = "windows"))]
682 anyhow::ensure!(
683 which::which("rsync").is_ok(),
684 "Could not auto-update because the required rsync utility was not found."
685 );
686 Ok(())
687 }
688
689 async fn target_path(installer_dir: &InstallerDir) -> Result<PathBuf> {
690 let filename = match OS {
691 "macos" => anyhow::Ok("Zed.dmg"),
692 "linux" => Ok("zed.tar.gz"),
693 "windows" => Ok("Zed.exe"),
694 unsupported_os => anyhow::bail!("not supported: {unsupported_os}"),
695 }?;
696
697 Ok(installer_dir.path().join(filename))
698 }
699
700 async fn install_release(
701 installer_dir: InstallerDir,
702 target_path: PathBuf,
703 cx: &AsyncApp,
704 ) -> Result<Option<PathBuf>> {
705 #[cfg(test)]
706 if let Some(test_install) =
707 cx.try_read_global::<tests::InstallOverride, _>(|g, _| g.0.clone())
708 {
709 return test_install(target_path, cx);
710 }
711 match OS {
712 "macos" => install_release_macos(&installer_dir, target_path, cx).await,
713 "linux" => install_release_linux(&installer_dir, target_path, cx).await,
714 "windows" => install_release_windows(target_path).await,
715 unsupported_os => anyhow::bail!("not supported: {unsupported_os}"),
716 }
717 }
718
719 fn check_if_fetched_version_is_newer_non_nightly(
720 mut installed_version: Version,
721 fetched_version: Version,
722 ) -> Result<Option<VersionCheckType>> {
723 // For non-nightly releases, ignore build and pre-release fields as they're not provided by our endpoints right now.
724 installed_version.build = semver::BuildMetadata::EMPTY;
725 installed_version.pre = semver::Prerelease::EMPTY;
726 let should_download = fetched_version > installed_version;
727 let newer_version = should_download.then(|| VersionCheckType::Semantic(fetched_version));
728 Ok(newer_version)
729 }
730
731 pub fn set_should_show_update_notification(
732 &self,
733 should_show: bool,
734 cx: &App,
735 ) -> Task<Result<()>> {
736 cx.background_spawn(async move {
737 if should_show {
738 KEY_VALUE_STORE
739 .write_kvp(
740 SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
741 "".to_string(),
742 )
743 .await?;
744 } else {
745 KEY_VALUE_STORE
746 .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
747 .await?;
748 }
749 Ok(())
750 })
751 }
752
753 pub fn should_show_update_notification(&self, cx: &App) -> Task<Result<bool>> {
754 cx.background_spawn(async move {
755 Ok(KEY_VALUE_STORE
756 .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
757 .is_some())
758 })
759 }
760}
761
762async fn download_remote_server_binary(
763 target_path: &PathBuf,
764 release: ReleaseAsset,
765 client: Arc<HttpClientWithUrl>,
766) -> Result<()> {
767 let temp = tempfile::Builder::new().tempfile_in(remote_servers_dir())?;
768 let mut temp_file = File::create(&temp).await?;
769
770 let mut response = client.get(&release.url, Default::default(), true).await?;
771 anyhow::ensure!(
772 response.status().is_success(),
773 "failed to download remote server release: {:?}",
774 response.status()
775 );
776 smol::io::copy(response.body_mut(), &mut temp_file).await?;
777 smol::fs::rename(&temp, &target_path).await?;
778
779 Ok(())
780}
781
782async fn download_release(
783 target_path: &Path,
784 release: ReleaseAsset,
785 client: Arc<HttpClientWithUrl>,
786) -> Result<()> {
787 let mut target_file = File::create(&target_path).await?;
788
789 let mut response = client.get(&release.url, Default::default(), true).await?;
790 anyhow::ensure!(
791 response.status().is_success(),
792 "failed to download update: {:?}",
793 response.status()
794 );
795 smol::io::copy(response.body_mut(), &mut target_file).await?;
796 log::info!("downloaded update. path:{:?}", target_path);
797
798 Ok(())
799}
800
801async fn install_release_linux(
802 temp_dir: &InstallerDir,
803 downloaded_tar_gz: PathBuf,
804 cx: &AsyncApp,
805) -> Result<Option<PathBuf>> {
806 let channel = cx.update(|cx| ReleaseChannel::global(cx).dev_name())?;
807 let home_dir = PathBuf::from(env::var("HOME").context("no HOME env var set")?);
808 let running_app_path = cx.update(|cx| cx.app_path())??;
809
810 let extracted = temp_dir.path().join("zed");
811 fs::create_dir_all(&extracted)
812 .await
813 .context("failed to create directory into which to extract update")?;
814
815 let output = new_smol_command("tar")
816 .arg("-xzf")
817 .arg(&downloaded_tar_gz)
818 .arg("-C")
819 .arg(&extracted)
820 .output()
821 .await?;
822
823 anyhow::ensure!(
824 output.status.success(),
825 "failed to extract {:?} to {:?}: {:?}",
826 downloaded_tar_gz,
827 extracted,
828 String::from_utf8_lossy(&output.stderr)
829 );
830
831 let suffix = if channel != "stable" {
832 format!("-{}", channel)
833 } else {
834 String::default()
835 };
836 let app_folder_name = format!("zed{}.app", suffix);
837
838 let from = extracted.join(&app_folder_name);
839 let mut to = home_dir.join(".local");
840
841 let expected_suffix = format!("{}/libexec/zed-editor", app_folder_name);
842
843 if let Some(prefix) = running_app_path
844 .to_str()
845 .and_then(|str| str.strip_suffix(&expected_suffix))
846 {
847 to = PathBuf::from(prefix);
848 }
849
850 let output = new_smol_command("rsync")
851 .args(["-av", "--delete"])
852 .arg(&from)
853 .arg(&to)
854 .output()
855 .await?;
856
857 anyhow::ensure!(
858 output.status.success(),
859 "failed to copy Zed update from {:?} to {:?}: {:?}",
860 from,
861 to,
862 String::from_utf8_lossy(&output.stderr)
863 );
864
865 Ok(Some(to.join(expected_suffix)))
866}
867
868async fn install_release_macos(
869 temp_dir: &InstallerDir,
870 downloaded_dmg: PathBuf,
871 cx: &AsyncApp,
872) -> Result<Option<PathBuf>> {
873 let running_app_path = cx.update(|cx| cx.app_path())??;
874 let running_app_filename = running_app_path
875 .file_name()
876 .with_context(|| format!("invalid running app path {running_app_path:?}"))?;
877
878 let mount_path = temp_dir.path().join("Zed");
879 let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
880
881 mounted_app_path.push("/");
882 let output = new_smol_command("hdiutil")
883 .args(["attach", "-nobrowse"])
884 .arg(&downloaded_dmg)
885 .arg("-mountroot")
886 .arg(temp_dir.path())
887 .output()
888 .await?;
889
890 anyhow::ensure!(
891 output.status.success(),
892 "failed to mount: {:?}",
893 String::from_utf8_lossy(&output.stderr)
894 );
895
896 // Create an MacOsUnmounter that will be dropped (and thus unmount the disk) when this function exits
897 let _unmounter = MacOsUnmounter {
898 mount_path: mount_path.clone(),
899 background_executor: cx.background_executor(),
900 };
901
902 let output = new_smol_command("rsync")
903 .args(["-av", "--delete"])
904 .arg(&mounted_app_path)
905 .arg(&running_app_path)
906 .output()
907 .await?;
908
909 anyhow::ensure!(
910 output.status.success(),
911 "failed to copy app: {:?}",
912 String::from_utf8_lossy(&output.stderr)
913 );
914
915 Ok(None)
916}
917
918async fn cleanup_windows() -> Result<()> {
919 let parent = std::env::current_exe()?
920 .parent()
921 .context("No parent dir for Zed.exe")?
922 .to_owned();
923
924 // keep in sync with crates/auto_update_helper/src/updater.rs
925 _ = smol::fs::remove_dir(parent.join("updates")).await;
926 _ = smol::fs::remove_dir(parent.join("install")).await;
927 _ = smol::fs::remove_dir(parent.join("old")).await;
928
929 Ok(())
930}
931
932async fn install_release_windows(downloaded_installer: PathBuf) -> Result<Option<PathBuf>> {
933 let output = new_smol_command(downloaded_installer)
934 .arg("/verysilent")
935 .arg("/update=true")
936 .arg("!desktopicon")
937 .arg("!quicklaunchicon")
938 .output()
939 .await?;
940 anyhow::ensure!(
941 output.status.success(),
942 "failed to start installer: {:?}",
943 String::from_utf8_lossy(&output.stderr)
944 );
945 // We return the path to the update helper program, because it will
946 // perform the final steps of the update process, copying the new binary,
947 // deleting the old one, and launching the new binary.
948 let helper_path = std::env::current_exe()?
949 .parent()
950 .context("No parent dir for Zed.exe")?
951 .join("tools")
952 .join("auto_update_helper.exe");
953 Ok(Some(helper_path))
954}
955
956pub async fn finalize_auto_update_on_quit() {
957 let Some(installer_path) = std::env::current_exe()
958 .ok()
959 .and_then(|p| p.parent().map(|p| p.join("updates")))
960 else {
961 return;
962 };
963
964 // The installer will create a flag file after it finishes updating
965 let flag_file = installer_path.join("versions.txt");
966 if flag_file.exists()
967 && let Some(helper) = installer_path
968 .parent()
969 .map(|p| p.join("tools").join("auto_update_helper.exe"))
970 {
971 let mut command = util::command::new_smol_command(helper);
972 command.arg("--launch");
973 command.arg("false");
974 if let Ok(mut cmd) = command.spawn() {
975 _ = cmd.status().await;
976 }
977 }
978}
979
980#[cfg(test)]
981mod tests {
982 use client::Client;
983 use clock::FakeSystemClock;
984 use futures::channel::oneshot;
985 use gpui::TestAppContext;
986 use http_client::{FakeHttpClient, Response};
987 use settings::default_settings;
988 use std::{
989 rc::Rc,
990 sync::{
991 Arc,
992 atomic::{self, AtomicBool},
993 },
994 };
995 use tempfile::tempdir;
996
997 #[ctor::ctor]
998 fn init_logger() {
999 zlog::init_test();
1000 }
1001
1002 use super::*;
1003
1004 pub(super) struct InstallOverride(
1005 pub Rc<dyn Fn(PathBuf, &AsyncApp) -> Result<Option<PathBuf>>>,
1006 );
1007 impl Global for InstallOverride {}
1008
1009 #[gpui::test]
1010 fn test_auto_update_defaults_to_true(cx: &mut TestAppContext) {
1011 cx.update(|cx| {
1012 let mut store = SettingsStore::new(cx, &settings::default_settings());
1013 store
1014 .set_default_settings(&default_settings(), cx)
1015 .expect("Unable to set default settings");
1016 store
1017 .set_user_settings("{}", cx)
1018 .expect("Unable to set user settings");
1019 cx.set_global(store);
1020 assert!(AutoUpdateSetting::get_global(cx).0);
1021 });
1022 }
1023
1024 #[gpui::test]
1025 async fn test_auto_update_downloads(cx: &mut TestAppContext) {
1026 cx.background_executor.allow_parking();
1027 zlog::init_test();
1028 let release_available = Arc::new(AtomicBool::new(false));
1029
1030 let (dmg_tx, dmg_rx) = oneshot::channel::<String>();
1031
1032 cx.update(|cx| {
1033 settings::init(cx);
1034
1035 let current_version = semver::Version::new(0, 100, 0);
1036 release_channel::init_test(current_version, ReleaseChannel::Stable, cx);
1037
1038 let clock = Arc::new(FakeSystemClock::new());
1039 let release_available = Arc::clone(&release_available);
1040 let dmg_rx = Arc::new(parking_lot::Mutex::new(Some(dmg_rx)));
1041 let fake_client_http = FakeHttpClient::create(move |req| {
1042 let release_available = release_available.load(atomic::Ordering::Relaxed);
1043 let dmg_rx = dmg_rx.clone();
1044 async move {
1045 if req.uri().path() == "/releases/stable/latest/asset" {
1046 if release_available {
1047 return Ok(Response::builder().status(200).body(
1048 r#"{"version":"0.100.1","url":"https://test.example/new-download"}"#.into()
1049 ).unwrap());
1050 } else {
1051 return Ok(Response::builder().status(200).body(
1052 r#"{"version":"0.100.0","url":"https://test.example/old-download"}"#.into()
1053 ).unwrap());
1054 }
1055 } else if req.uri().path() == "/new-download" {
1056 return Ok(Response::builder().status(200).body({
1057 let dmg_rx = dmg_rx.lock().take().unwrap();
1058 dmg_rx.await.unwrap().into()
1059 }).unwrap());
1060 }
1061 Ok(Response::builder().status(404).body("".into()).unwrap())
1062 }
1063 });
1064 let client = Client::new(clock, fake_client_http, cx);
1065 crate::init(client, cx);
1066 });
1067
1068 let auto_updater = cx.update(|cx| AutoUpdater::get(cx).expect("auto updater should exist"));
1069
1070 cx.background_executor.run_until_parked();
1071
1072 auto_updater.read_with(cx, |updater, _| {
1073 assert_eq!(updater.status(), AutoUpdateStatus::Idle);
1074 assert_eq!(updater.current_version(), semver::Version::new(0, 100, 0));
1075 });
1076
1077 release_available.store(true, atomic::Ordering::SeqCst);
1078 cx.background_executor.advance_clock(POLL_INTERVAL);
1079 cx.background_executor.run_until_parked();
1080
1081 loop {
1082 cx.background_executor.timer(Duration::from_millis(0)).await;
1083 cx.run_until_parked();
1084 let status = auto_updater.read_with(cx, |updater, _| updater.status());
1085 if !matches!(status, AutoUpdateStatus::Idle) {
1086 break;
1087 }
1088 }
1089 let status = auto_updater.read_with(cx, |updater, _| updater.status());
1090 assert_eq!(
1091 status,
1092 AutoUpdateStatus::Downloading {
1093 version: VersionCheckType::Semantic(semver::Version::new(0, 100, 1))
1094 }
1095 );
1096
1097 dmg_tx.send("<fake-zed-update>".to_owned()).unwrap();
1098
1099 let tmp_dir = Arc::new(tempdir().unwrap());
1100
1101 cx.update(|cx| {
1102 let tmp_dir = tmp_dir.clone();
1103 cx.set_global(InstallOverride(Rc::new(move |target_path, _cx| {
1104 let tmp_dir = tmp_dir.clone();
1105 let dest_path = tmp_dir.path().join("zed");
1106 std::fs::copy(&target_path, &dest_path)?;
1107 Ok(Some(dest_path))
1108 })));
1109 });
1110
1111 loop {
1112 cx.background_executor.timer(Duration::from_millis(0)).await;
1113 cx.run_until_parked();
1114 let status = auto_updater.read_with(cx, |updater, _| updater.status());
1115 if !matches!(status, AutoUpdateStatus::Downloading { .. }) {
1116 break;
1117 }
1118 }
1119 let status = auto_updater.read_with(cx, |updater, _| updater.status());
1120 assert_eq!(
1121 status,
1122 AutoUpdateStatus::Updated {
1123 version: VersionCheckType::Semantic(semver::Version::new(0, 100, 1))
1124 }
1125 );
1126 let will_restart = cx.expect_restart();
1127 cx.update(|cx| cx.restart());
1128 let path = will_restart.await.unwrap().unwrap();
1129 assert_eq!(path, tmp_dir.path().join("zed"));
1130 assert_eq!(std::fs::read_to_string(path).unwrap(), "<fake-zed-update>");
1131 }
1132
1133 #[test]
1134 fn test_stable_does_not_update_when_fetched_version_is_not_higher() {
1135 let release_channel = ReleaseChannel::Stable;
1136 let app_commit_sha = Ok(Some("a".to_string()));
1137 let installed_version = semver::Version::new(1, 0, 0);
1138 let status = AutoUpdateStatus::Idle;
1139 let fetched_version = semver::Version::new(1, 0, 0);
1140
1141 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1142 release_channel,
1143 app_commit_sha,
1144 installed_version,
1145 fetched_version.to_string(),
1146 status,
1147 );
1148
1149 assert_eq!(newer_version.unwrap(), None);
1150 }
1151
1152 #[test]
1153 fn test_stable_does_update_when_fetched_version_is_higher() {
1154 let release_channel = ReleaseChannel::Stable;
1155 let app_commit_sha = Ok(Some("a".to_string()));
1156 let installed_version = semver::Version::new(1, 0, 0);
1157 let status = AutoUpdateStatus::Idle;
1158 let fetched_version = semver::Version::new(1, 0, 1);
1159
1160 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1161 release_channel,
1162 app_commit_sha,
1163 installed_version,
1164 fetched_version.to_string(),
1165 status,
1166 );
1167
1168 assert_eq!(
1169 newer_version.unwrap(),
1170 Some(VersionCheckType::Semantic(fetched_version))
1171 );
1172 }
1173
1174 #[test]
1175 fn test_stable_does_not_update_when_fetched_version_is_not_higher_than_cached() {
1176 let release_channel = ReleaseChannel::Stable;
1177 let app_commit_sha = Ok(Some("a".to_string()));
1178 let installed_version = semver::Version::new(1, 0, 0);
1179 let status = AutoUpdateStatus::Updated {
1180 version: VersionCheckType::Semantic(semver::Version::new(1, 0, 1)),
1181 };
1182 let fetched_version = semver::Version::new(1, 0, 1);
1183
1184 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1185 release_channel,
1186 app_commit_sha,
1187 installed_version,
1188 fetched_version.to_string(),
1189 status,
1190 );
1191
1192 assert_eq!(newer_version.unwrap(), None);
1193 }
1194
1195 #[test]
1196 fn test_stable_does_update_when_fetched_version_is_higher_than_cached() {
1197 let release_channel = ReleaseChannel::Stable;
1198 let app_commit_sha = Ok(Some("a".to_string()));
1199 let installed_version = semver::Version::new(1, 0, 0);
1200 let status = AutoUpdateStatus::Updated {
1201 version: VersionCheckType::Semantic(semver::Version::new(1, 0, 1)),
1202 };
1203 let fetched_version = semver::Version::new(1, 0, 2);
1204
1205 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1206 release_channel,
1207 app_commit_sha,
1208 installed_version,
1209 fetched_version.to_string(),
1210 status,
1211 );
1212
1213 assert_eq!(
1214 newer_version.unwrap(),
1215 Some(VersionCheckType::Semantic(fetched_version))
1216 );
1217 }
1218
1219 #[test]
1220 fn test_nightly_does_not_update_when_fetched_sha_is_same() {
1221 let release_channel = ReleaseChannel::Nightly;
1222 let app_commit_sha = Ok(Some("a".to_string()));
1223 let mut installed_version = semver::Version::new(1, 0, 0);
1224 installed_version.build = semver::BuildMetadata::new("a").unwrap();
1225 let status = AutoUpdateStatus::Idle;
1226 let fetched_sha = "1.0.0+a".to_string();
1227
1228 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1229 release_channel,
1230 app_commit_sha,
1231 installed_version,
1232 fetched_sha,
1233 status,
1234 );
1235
1236 assert_eq!(newer_version.unwrap(), None);
1237 }
1238
1239 #[test]
1240 fn test_nightly_does_update_when_fetched_sha_is_not_same() {
1241 let release_channel = ReleaseChannel::Nightly;
1242 let app_commit_sha = Ok(Some("a".to_string()));
1243 let installed_version = semver::Version::new(1, 0, 0);
1244 let status = AutoUpdateStatus::Idle;
1245 let fetched_sha = "b".to_string();
1246
1247 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1248 release_channel,
1249 app_commit_sha,
1250 installed_version,
1251 fetched_sha.clone(),
1252 status,
1253 );
1254
1255 assert_eq!(
1256 newer_version.unwrap(),
1257 Some(VersionCheckType::Sha(AppCommitSha::new(fetched_sha)))
1258 );
1259 }
1260
1261 #[test]
1262 fn test_nightly_does_not_update_when_fetched_version_is_same_as_cached() {
1263 let release_channel = ReleaseChannel::Nightly;
1264 let app_commit_sha = Ok(Some("a".to_string()));
1265 let mut installed_version = semver::Version::new(1, 0, 0);
1266 installed_version.build = semver::BuildMetadata::new("a").unwrap();
1267 let status = AutoUpdateStatus::Updated {
1268 version: VersionCheckType::Sha(AppCommitSha::new("b".to_string())),
1269 };
1270 let fetched_sha = "1.0.0+b".to_string();
1271
1272 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1273 release_channel,
1274 app_commit_sha,
1275 installed_version,
1276 fetched_sha,
1277 status,
1278 );
1279
1280 assert_eq!(newer_version.unwrap(), None);
1281 }
1282
1283 #[test]
1284 fn test_nightly_does_update_when_fetched_sha_is_not_same_as_cached() {
1285 let release_channel = ReleaseChannel::Nightly;
1286 let app_commit_sha = Ok(Some("a".to_string()));
1287 let mut installed_version = semver::Version::new(1, 0, 0);
1288 installed_version.build = semver::BuildMetadata::new("a").unwrap();
1289 let status = AutoUpdateStatus::Updated {
1290 version: VersionCheckType::Sha(AppCommitSha::new("b".to_string())),
1291 };
1292 let fetched_sha = "1.0.0+c".to_string();
1293
1294 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1295 release_channel,
1296 app_commit_sha,
1297 installed_version,
1298 fetched_sha.clone(),
1299 status,
1300 );
1301
1302 assert_eq!(
1303 newer_version.unwrap(),
1304 Some(VersionCheckType::Sha(AppCommitSha::new(fetched_sha)))
1305 );
1306 }
1307
1308 #[test]
1309 fn test_nightly_does_update_when_installed_versions_sha_cannot_be_retrieved() {
1310 let release_channel = ReleaseChannel::Nightly;
1311 let app_commit_sha = Ok(None);
1312 let installed_version = semver::Version::new(1, 0, 0);
1313 let status = AutoUpdateStatus::Idle;
1314 let fetched_sha = "a".to_string();
1315
1316 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1317 release_channel,
1318 app_commit_sha,
1319 installed_version,
1320 fetched_sha.clone(),
1321 status,
1322 );
1323
1324 assert_eq!(
1325 newer_version.unwrap(),
1326 Some(VersionCheckType::Sha(AppCommitSha::new(fetched_sha)))
1327 );
1328 }
1329
1330 #[test]
1331 fn test_nightly_does_not_update_when_cached_update_is_same_as_fetched_and_installed_versions_sha_cannot_be_retrieved()
1332 {
1333 let release_channel = ReleaseChannel::Nightly;
1334 let app_commit_sha = Ok(None);
1335 let installed_version = semver::Version::new(1, 0, 0);
1336 let status = AutoUpdateStatus::Updated {
1337 version: VersionCheckType::Sha(AppCommitSha::new("b".to_string())),
1338 };
1339 let fetched_sha = "1.0.0+b".to_string();
1340
1341 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1342 release_channel,
1343 app_commit_sha,
1344 installed_version,
1345 fetched_sha,
1346 status,
1347 );
1348
1349 assert_eq!(newer_version.unwrap(), None);
1350 }
1351
1352 #[test]
1353 fn test_nightly_does_update_when_cached_update_is_not_same_as_fetched_and_installed_versions_sha_cannot_be_retrieved()
1354 {
1355 let release_channel = ReleaseChannel::Nightly;
1356 let app_commit_sha = Ok(None);
1357 let installed_version = semver::Version::new(1, 0, 0);
1358 let status = AutoUpdateStatus::Updated {
1359 version: VersionCheckType::Sha(AppCommitSha::new("b".to_string())),
1360 };
1361 let fetched_sha = "c".to_string();
1362
1363 let newer_version = AutoUpdater::check_if_fetched_version_is_newer(
1364 release_channel,
1365 app_commit_sha,
1366 installed_version,
1367 fetched_sha.clone(),
1368 status,
1369 );
1370
1371 assert_eq!(
1372 newer_version.unwrap(),
1373 Some(VersionCheckType::Sha(AppCommitSha::new(fetched_sha)))
1374 );
1375 }
1376}