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