1use anyhow::{anyhow, Context as _, Result};
2use client::{Client, TelemetrySettings};
3use db::kvp::KEY_VALUE_STORE;
4use db::RELEASE_CHANNEL;
5use gpui::{
6 actions, App, AppContext as _, AsyncApp, Context, Entity, Global, SemanticVersion, Task, Window,
7};
8use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
9use paths::remote_servers_dir;
10use release_channel::{AppCommitSha, ReleaseChannel};
11use schemars::JsonSchema;
12use serde::{Deserialize, Serialize};
13use settings::{Settings, SettingsSources, SettingsStore};
14use smol::{fs, io::AsyncReadExt};
15use smol::{fs::File, process::Command};
16use std::{
17 env::{
18 self,
19 consts::{ARCH, OS},
20 },
21 ffi::OsString,
22 path::{Path, PathBuf},
23 sync::Arc,
24 time::Duration,
25};
26use which::which;
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!(auto_update, [Check, DismissErrorMessage, ViewReleaseNotes,]);
33
34#[derive(Serialize)]
35struct UpdateRequestBody {
36 installation_id: Option<Arc<str>>,
37 release_channel: Option<&'static str>,
38 telemetry: bool,
39 is_staff: Option<bool>,
40 destination: &'static str,
41}
42
43#[derive(Clone, PartialEq, Eq)]
44pub enum AutoUpdateStatus {
45 Idle,
46 Checking,
47 Downloading,
48 Installing,
49 Updated { binary_path: PathBuf },
50 Errored,
51}
52
53impl AutoUpdateStatus {
54 pub fn is_updated(&self) -> bool {
55 matches!(self, Self::Updated { .. })
56 }
57}
58
59pub struct AutoUpdater {
60 status: AutoUpdateStatus,
61 current_version: SemanticVersion,
62 http_client: Arc<HttpClientWithUrl>,
63 pending_poll: Option<Task<Option<()>>>,
64}
65
66#[derive(Deserialize)]
67pub struct JsonRelease {
68 pub version: String,
69 pub url: String,
70}
71
72struct MacOsUnmounter {
73 mount_path: PathBuf,
74}
75
76impl Drop for MacOsUnmounter {
77 fn drop(&mut self) {
78 let unmount_output = std::process::Command::new("hdiutil")
79 .args(["detach", "-force"])
80 .arg(&self.mount_path)
81 .output();
82
83 match unmount_output {
84 Ok(output) if output.status.success() => {
85 log::info!("Successfully unmounted the disk image");
86 }
87 Ok(output) => {
88 log::error!(
89 "Failed to unmount disk image: {:?}",
90 String::from_utf8_lossy(&output.stderr)
91 );
92 }
93 Err(error) => {
94 log::error!("Error while trying to unmount disk image: {:?}", error);
95 }
96 }
97 }
98}
99
100struct AutoUpdateSetting(bool);
101
102/// Whether or not to automatically check for updates.
103///
104/// Default: true
105#[derive(Clone, Copy, Default, JsonSchema, Deserialize, Serialize)]
106#[serde(transparent)]
107struct AutoUpdateSettingContent(bool);
108
109impl Settings for AutoUpdateSetting {
110 const KEY: Option<&'static str> = Some("auto_update");
111
112 type FileContent = Option<AutoUpdateSettingContent>;
113
114 fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
115 let auto_update = [sources.server, sources.release_channel, sources.user]
116 .into_iter()
117 .find_map(|value| value.copied().flatten())
118 .unwrap_or(sources.default.ok_or_else(Self::missing_default)?);
119
120 Ok(Self(auto_update.0))
121 }
122}
123
124#[derive(Default)]
125struct GlobalAutoUpdate(Option<Entity<AutoUpdater>>);
126
127impl Global for GlobalAutoUpdate {}
128
129pub fn init(http_client: Arc<HttpClientWithUrl>, cx: &mut App) {
130 AutoUpdateSetting::register(cx);
131
132 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
133 workspace.register_action(|_, action: &Check, window, cx| check(action, window, cx));
134
135 workspace.register_action(|_, action, _, cx| {
136 view_release_notes(action, cx);
137 });
138 })
139 .detach();
140
141 let version = release_channel::AppVersion::global(cx);
142 let auto_updater = cx.new(|cx| {
143 let updater = AutoUpdater::new(version, http_client);
144
145 let poll_for_updates = ReleaseChannel::try_global(cx)
146 .map(|channel| channel.poll_for_updates())
147 .unwrap_or(false);
148
149 if option_env!("ZED_UPDATE_EXPLANATION").is_none()
150 && env::var("ZED_UPDATE_EXPLANATION").is_err()
151 && poll_for_updates
152 {
153 let mut update_subscription = AutoUpdateSetting::get_global(cx)
154 .0
155 .then(|| updater.start_polling(cx));
156
157 cx.observe_global::<SettingsStore>(move |updater: &mut AutoUpdater, cx| {
158 if AutoUpdateSetting::get_global(cx).0 {
159 if update_subscription.is_none() {
160 update_subscription = Some(updater.start_polling(cx))
161 }
162 } else {
163 update_subscription.take();
164 }
165 })
166 .detach();
167 }
168
169 updater
170 });
171 cx.set_global(GlobalAutoUpdate(Some(auto_updater)));
172}
173
174pub fn check(_: &Check, window: &mut Window, cx: &mut App) {
175 if let Some(message) = option_env!("ZED_UPDATE_EXPLANATION") {
176 drop(window.prompt(
177 gpui::PromptLevel::Info,
178 "Zed was installed via a package manager.",
179 Some(message),
180 &["Ok"],
181 cx,
182 ));
183 return;
184 }
185
186 if let Ok(message) = env::var("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 !ReleaseChannel::try_global(cx)
198 .map(|channel| channel.poll_for_updates())
199 .unwrap_or(false)
200 {
201 return;
202 }
203
204 if let Some(updater) = AutoUpdater::get(cx) {
205 updater.update(cx, |updater, cx| updater.poll(cx));
206 } else {
207 drop(window.prompt(
208 gpui::PromptLevel::Info,
209 "Could not check for updates",
210 Some("Auto-updates disabled for non-bundled app."),
211 &["Ok"],
212 cx,
213 ));
214 }
215}
216
217pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut App) -> Option<()> {
218 let auto_updater = AutoUpdater::get(cx)?;
219 let release_channel = ReleaseChannel::try_global(cx)?;
220
221 match release_channel {
222 ReleaseChannel::Stable | ReleaseChannel::Preview => {
223 let auto_updater = auto_updater.read(cx);
224 let current_version = auto_updater.current_version;
225 let release_channel = release_channel.dev_name();
226 let path = format!("/releases/{release_channel}/{current_version}");
227 let url = &auto_updater.http_client.build_url(&path);
228 cx.open_url(url);
229 }
230 ReleaseChannel::Nightly => {
231 cx.open_url("https://github.com/zed-industries/zed/commits/nightly/");
232 }
233 ReleaseChannel::Dev => {
234 cx.open_url("https://github.com/zed-industries/zed/commits/main/");
235 }
236 }
237 None
238}
239
240impl AutoUpdater {
241 pub fn get(cx: &mut App) -> Option<Entity<Self>> {
242 cx.default_global::<GlobalAutoUpdate>().0.clone()
243 }
244
245 fn new(current_version: SemanticVersion, http_client: Arc<HttpClientWithUrl>) -> Self {
246 Self {
247 status: AutoUpdateStatus::Idle,
248 current_version,
249 http_client,
250 pending_poll: None,
251 }
252 }
253
254 pub fn start_polling(&self, cx: &mut Context<Self>) -> Task<Result<()>> {
255 cx.spawn(async move |this, cx| loop {
256 this.update(cx, |this, cx| this.poll(cx))?;
257 cx.background_executor().timer(POLL_INTERVAL).await;
258 })
259 }
260
261 pub fn poll(&mut self, cx: &mut Context<Self>) {
262 if self.pending_poll.is_some() || self.status.is_updated() {
263 return;
264 }
265
266 cx.notify();
267
268 self.pending_poll = Some(cx.spawn(async move |this, cx| {
269 let result = Self::update(this.upgrade()?, cx.clone()).await;
270 this.update(cx, |this, cx| {
271 this.pending_poll = None;
272 if let Err(error) = result {
273 log::error!("auto-update failed: error:{:?}", error);
274 this.status = AutoUpdateStatus::Errored;
275 cx.notify();
276 }
277 })
278 .ok()
279 }));
280 }
281
282 pub fn current_version(&self) -> SemanticVersion {
283 self.current_version
284 }
285
286 pub fn status(&self) -> AutoUpdateStatus {
287 self.status.clone()
288 }
289
290 pub fn dismiss_error(&mut self, cx: &mut Context<Self>) {
291 self.status = AutoUpdateStatus::Idle;
292 cx.notify();
293 }
294
295 // If you are packaging Zed and need to override the place it downloads SSH remotes from,
296 // you can override this function. You should also update get_remote_server_release_url to return
297 // Ok(None).
298 pub async fn download_remote_server_release(
299 os: &str,
300 arch: &str,
301 release_channel: ReleaseChannel,
302 version: Option<SemanticVersion>,
303 cx: &mut AsyncApp,
304 ) -> Result<PathBuf> {
305 let this = cx.update(|cx| {
306 cx.default_global::<GlobalAutoUpdate>()
307 .0
308 .clone()
309 .ok_or_else(|| anyhow!("auto-update not initialized"))
310 })??;
311
312 let release = Self::get_release(
313 &this,
314 "zed-remote-server",
315 os,
316 arch,
317 version,
318 Some(release_channel),
319 cx,
320 )
321 .await?;
322
323 let servers_dir = paths::remote_servers_dir();
324 let channel_dir = servers_dir.join(release_channel.dev_name());
325 let platform_dir = channel_dir.join(format!("{}-{}", os, arch));
326 let version_path = platform_dir.join(format!("{}.gz", release.version));
327 smol::fs::create_dir_all(&platform_dir).await.ok();
328
329 let client = this.read_with(cx, |this, _| this.http_client.clone())?;
330
331 if smol::fs::metadata(&version_path).await.is_err() {
332 log::info!(
333 "downloading zed-remote-server {os} {arch} version {}",
334 release.version
335 );
336 download_remote_server_binary(&version_path, release, client, cx).await?;
337 }
338
339 Ok(version_path)
340 }
341
342 pub async fn get_remote_server_release_url(
343 os: &str,
344 arch: &str,
345 release_channel: ReleaseChannel,
346 version: Option<SemanticVersion>,
347 cx: &mut AsyncApp,
348 ) -> Result<Option<(String, String)>> {
349 let this = cx.update(|cx| {
350 cx.default_global::<GlobalAutoUpdate>()
351 .0
352 .clone()
353 .ok_or_else(|| anyhow!("auto-update not initialized"))
354 })??;
355
356 let release = Self::get_release(
357 &this,
358 "zed-remote-server",
359 os,
360 arch,
361 version,
362 Some(release_channel),
363 cx,
364 )
365 .await?;
366
367 let update_request_body = build_remote_server_update_request_body(cx)?;
368 let body = serde_json::to_string(&update_request_body)?;
369
370 Ok(Some((release.url, body)))
371 }
372
373 async fn get_release(
374 this: &Entity<Self>,
375 asset: &str,
376 os: &str,
377 arch: &str,
378 version: Option<SemanticVersion>,
379 release_channel: Option<ReleaseChannel>,
380 cx: &mut AsyncApp,
381 ) -> Result<JsonRelease> {
382 let client = this.read_with(cx, |this, _| this.http_client.clone())?;
383
384 if let Some(version) = version {
385 let channel = release_channel.map(|c| c.dev_name()).unwrap_or("stable");
386
387 let url = format!("/api/releases/{channel}/{version}/{asset}-{os}-{arch}.gz?update=1",);
388
389 Ok(JsonRelease {
390 version: version.to_string(),
391 url: client.build_url(&url),
392 })
393 } else {
394 let mut url_string = client.build_url(&format!(
395 "/api/releases/latest?asset={}&os={}&arch={}",
396 asset, os, arch
397 ));
398 if let Some(param) = release_channel.and_then(|c| c.release_query_param()) {
399 url_string += "&";
400 url_string += param;
401 }
402
403 let mut response = client.get(&url_string, Default::default(), true).await?;
404 let mut body = Vec::new();
405 response.body_mut().read_to_end(&mut body).await?;
406
407 if !response.status().is_success() {
408 return Err(anyhow!(
409 "failed to fetch release: {:?}",
410 String::from_utf8_lossy(&body),
411 ));
412 }
413
414 serde_json::from_slice(body.as_slice()).with_context(|| {
415 format!(
416 "error deserializing release {:?}",
417 String::from_utf8_lossy(&body),
418 )
419 })
420 }
421 }
422
423 async fn get_latest_release(
424 this: &Entity<Self>,
425 asset: &str,
426 os: &str,
427 arch: &str,
428 release_channel: Option<ReleaseChannel>,
429 cx: &mut AsyncApp,
430 ) -> Result<JsonRelease> {
431 Self::get_release(this, asset, os, arch, None, release_channel, cx).await
432 }
433
434 async fn update(this: Entity<Self>, mut cx: AsyncApp) -> Result<()> {
435 let (client, current_version, release_channel) = this.update(&mut cx, |this, cx| {
436 this.status = AutoUpdateStatus::Checking;
437 cx.notify();
438 (
439 this.http_client.clone(),
440 this.current_version,
441 ReleaseChannel::try_global(cx),
442 )
443 })?;
444
445 let release =
446 Self::get_latest_release(&this, "zed", OS, ARCH, release_channel, &mut cx).await?;
447
448 let should_download = match *RELEASE_CHANNEL {
449 ReleaseChannel::Nightly => cx
450 .update(|cx| AppCommitSha::try_global(cx).map(|sha| release.version != sha.0))
451 .ok()
452 .flatten()
453 .unwrap_or(true),
454 _ => release.version.parse::<SemanticVersion>()? > current_version,
455 };
456
457 if !should_download {
458 this.update(&mut cx, |this, cx| {
459 this.status = AutoUpdateStatus::Idle;
460 cx.notify();
461 })?;
462 return Ok(());
463 }
464
465 this.update(&mut cx, |this, cx| {
466 this.status = AutoUpdateStatus::Downloading;
467 cx.notify();
468 })?;
469
470 let temp_dir = tempfile::Builder::new()
471 .prefix("zed-auto-update")
472 .tempdir()?;
473
474 let filename = match OS {
475 "macos" => Ok("Zed.dmg"),
476 "linux" => Ok("zed.tar.gz"),
477 _ => Err(anyhow!("not supported: {:?}", OS)),
478 }?;
479
480 anyhow::ensure!(
481 which("rsync").is_ok(),
482 "Aborting. Could not find rsync which is required for auto-updates."
483 );
484
485 let downloaded_asset = temp_dir.path().join(filename);
486 download_release(&downloaded_asset, release, client, &cx).await?;
487
488 this.update(&mut cx, |this, cx| {
489 this.status = AutoUpdateStatus::Installing;
490 cx.notify();
491 })?;
492
493 let binary_path = match OS {
494 "macos" => install_release_macos(&temp_dir, downloaded_asset, &cx).await,
495 "linux" => install_release_linux(&temp_dir, downloaded_asset, &cx).await,
496 _ => Err(anyhow!("not supported: {:?}", OS)),
497 }?;
498
499 this.update(&mut cx, |this, cx| {
500 this.set_should_show_update_notification(true, cx)
501 .detach_and_log_err(cx);
502 this.status = AutoUpdateStatus::Updated { binary_path };
503 cx.notify();
504 })?;
505
506 Ok(())
507 }
508
509 pub fn set_should_show_update_notification(
510 &self,
511 should_show: bool,
512 cx: &App,
513 ) -> Task<Result<()>> {
514 cx.background_spawn(async move {
515 if should_show {
516 KEY_VALUE_STORE
517 .write_kvp(
518 SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
519 "".to_string(),
520 )
521 .await?;
522 } else {
523 KEY_VALUE_STORE
524 .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
525 .await?;
526 }
527 Ok(())
528 })
529 }
530
531 pub fn should_show_update_notification(&self, cx: &App) -> Task<Result<bool>> {
532 cx.background_spawn(async move {
533 Ok(KEY_VALUE_STORE
534 .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
535 .is_some())
536 })
537 }
538}
539
540async fn download_remote_server_binary(
541 target_path: &PathBuf,
542 release: JsonRelease,
543 client: Arc<HttpClientWithUrl>,
544 cx: &AsyncApp,
545) -> Result<()> {
546 let temp = tempfile::Builder::new().tempfile_in(remote_servers_dir())?;
547 let mut temp_file = File::create(&temp).await?;
548 let update_request_body = build_remote_server_update_request_body(cx)?;
549 let request_body = AsyncBody::from(serde_json::to_string(&update_request_body)?);
550
551 let mut response = client.get(&release.url, request_body, true).await?;
552 if !response.status().is_success() {
553 return Err(anyhow!(
554 "failed to download remote server release: {:?}",
555 response.status()
556 ));
557 }
558 smol::io::copy(response.body_mut(), &mut temp_file).await?;
559 smol::fs::rename(&temp, &target_path).await?;
560
561 Ok(())
562}
563
564fn build_remote_server_update_request_body(cx: &AsyncApp) -> Result<UpdateRequestBody> {
565 let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
566 let telemetry = Client::global(cx).telemetry().clone();
567 let is_staff = telemetry.is_staff();
568 let installation_id = telemetry.installation_id();
569 let release_channel =
570 ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
571 let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
572
573 (
574 installation_id,
575 release_channel,
576 telemetry_enabled,
577 is_staff,
578 )
579 })?;
580
581 Ok(UpdateRequestBody {
582 installation_id,
583 release_channel,
584 telemetry: telemetry_enabled,
585 is_staff,
586 destination: "remote",
587 })
588}
589
590async fn download_release(
591 target_path: &Path,
592 release: JsonRelease,
593 client: Arc<HttpClientWithUrl>,
594 cx: &AsyncApp,
595) -> Result<()> {
596 let mut target_file = File::create(&target_path).await?;
597
598 let (installation_id, release_channel, telemetry_enabled, is_staff) = cx.update(|cx| {
599 let telemetry = Client::global(cx).telemetry().clone();
600 let is_staff = telemetry.is_staff();
601 let installation_id = telemetry.installation_id();
602 let release_channel =
603 ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
604 let telemetry_enabled = TelemetrySettings::get_global(cx).metrics;
605
606 (
607 installation_id,
608 release_channel,
609 telemetry_enabled,
610 is_staff,
611 )
612 })?;
613
614 let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
615 installation_id,
616 release_channel,
617 telemetry: telemetry_enabled,
618 is_staff,
619 destination: "local",
620 })?);
621
622 let mut response = client.get(&release.url, request_body, true).await?;
623 smol::io::copy(response.body_mut(), &mut target_file).await?;
624 log::info!("downloaded update. path:{:?}", target_path);
625
626 Ok(())
627}
628
629async fn install_release_linux(
630 temp_dir: &tempfile::TempDir,
631 downloaded_tar_gz: PathBuf,
632 cx: &AsyncApp,
633) -> Result<PathBuf> {
634 let channel = cx.update(|cx| ReleaseChannel::global(cx).dev_name())?;
635 let home_dir = PathBuf::from(env::var("HOME").context("no HOME env var set")?);
636 let running_app_path = cx.update(|cx| cx.app_path())??;
637
638 let extracted = temp_dir.path().join("zed");
639 fs::create_dir_all(&extracted)
640 .await
641 .context("failed to create directory into which to extract update")?;
642
643 let output = Command::new("tar")
644 .arg("-xzf")
645 .arg(&downloaded_tar_gz)
646 .arg("-C")
647 .arg(&extracted)
648 .output()
649 .await?;
650
651 anyhow::ensure!(
652 output.status.success(),
653 "failed to extract {:?} to {:?}: {:?}",
654 downloaded_tar_gz,
655 extracted,
656 String::from_utf8_lossy(&output.stderr)
657 );
658
659 let suffix = if channel != "stable" {
660 format!("-{}", channel)
661 } else {
662 String::default()
663 };
664 let app_folder_name = format!("zed{}.app", suffix);
665
666 let from = extracted.join(&app_folder_name);
667 let mut to = home_dir.join(".local");
668
669 let expected_suffix = format!("{}/libexec/zed-editor", app_folder_name);
670
671 if let Some(prefix) = running_app_path
672 .to_str()
673 .and_then(|str| str.strip_suffix(&expected_suffix))
674 {
675 to = PathBuf::from(prefix);
676 }
677
678 let output = Command::new("rsync")
679 .args(["-av", "--delete"])
680 .arg(&from)
681 .arg(&to)
682 .output()
683 .await?;
684
685 anyhow::ensure!(
686 output.status.success(),
687 "failed to copy Zed update from {:?} to {:?}: {:?}",
688 from,
689 to,
690 String::from_utf8_lossy(&output.stderr)
691 );
692
693 Ok(to.join(expected_suffix))
694}
695
696async fn install_release_macos(
697 temp_dir: &tempfile::TempDir,
698 downloaded_dmg: PathBuf,
699 cx: &AsyncApp,
700) -> Result<PathBuf> {
701 let running_app_path = cx.update(|cx| cx.app_path())??;
702 let running_app_filename = running_app_path
703 .file_name()
704 .ok_or_else(|| anyhow!("invalid running app path"))?;
705
706 let mount_path = temp_dir.path().join("Zed");
707 let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
708
709 mounted_app_path.push("/");
710 let output = Command::new("hdiutil")
711 .args(["attach", "-nobrowse"])
712 .arg(&downloaded_dmg)
713 .arg("-mountroot")
714 .arg(temp_dir.path())
715 .output()
716 .await?;
717
718 anyhow::ensure!(
719 output.status.success(),
720 "failed to mount: {:?}",
721 String::from_utf8_lossy(&output.stderr)
722 );
723
724 // Create an MacOsUnmounter that will be dropped (and thus unmount the disk) when this function exits
725 let _unmounter = MacOsUnmounter {
726 mount_path: mount_path.clone(),
727 };
728
729 let output = Command::new("rsync")
730 .args(["-av", "--delete"])
731 .arg(&mounted_app_path)
732 .arg(&running_app_path)
733 .output()
734 .await?;
735
736 anyhow::ensure!(
737 output.status.success(),
738 "failed to copy app: {:?}",
739 String::from_utf8_lossy(&output.stderr)
740 );
741
742 Ok(running_app_path)
743}