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