1use anyhow::{anyhow, Context, Result};
2use client::{Client, TelemetrySettings};
3use db::kvp::KEY_VALUE_STORE;
4use db::RELEASE_CHANNEL;
5use gpui::{
6 actions, AppContext, AsyncAppContext, Context as _, Global, Model, ModelContext,
7 SemanticVersion, Task, WindowContext,
8};
9use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
10use paths::remote_servers_dir;
11use release_channel::{AppCommitSha, ReleaseChannel};
12use schemars::JsonSchema;
13use serde::{Deserialize, Serialize};
14use settings::{Settings, SettingsSources, SettingsStore};
15use smol::{fs, io::AsyncReadExt};
16use smol::{fs::File, process::Command};
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 which::which;
28use workspace::Workspace;
29
30const SHOULD_SHOW_UPDATE_NOTIFICATION_KEY: &str = "auto-updater-should-show-updated-notification";
31const POLL_INTERVAL: Duration = Duration::from_secs(60 * 60);
32
33actions!(auto_update, [Check, DismissErrorMessage, ViewReleaseNotes,]);
34
35#[derive(Serialize)]
36struct UpdateRequestBody {
37 installation_id: Option<Arc<str>>,
38 release_channel: Option<&'static str>,
39 telemetry: bool,
40 is_staff: Option<bool>,
41 destination: &'static str,
42}
43
44#[derive(Clone, PartialEq, Eq)]
45pub enum AutoUpdateStatus {
46 Idle,
47 Checking,
48 Downloading,
49 Installing,
50 Updated { binary_path: PathBuf },
51 Errored,
52}
53
54impl AutoUpdateStatus {
55 pub fn is_updated(&self) -> bool {
56 matches!(self, Self::Updated { .. })
57 }
58}
59
60pub struct AutoUpdater {
61 status: AutoUpdateStatus,
62 current_version: SemanticVersion,
63 http_client: Arc<HttpClientWithUrl>,
64 pending_poll: Option<Task<Option<()>>>,
65}
66
67#[derive(Deserialize)]
68pub struct JsonRelease {
69 pub version: String,
70 pub url: String,
71}
72
73struct MacOsUnmounter {
74 mount_path: PathBuf,
75}
76
77impl Drop for MacOsUnmounter {
78 fn drop(&mut self) {
79 let unmount_output = std::process::Command::new("hdiutil")
80 .args(["detach", "-force"])
81 .arg(&self.mount_path)
82 .output();
83
84 match unmount_output {
85 Ok(output) if output.status.success() => {
86 log::info!("Successfully unmounted the disk image");
87 }
88 Ok(output) => {
89 log::error!(
90 "Failed to unmount disk image: {:?}",
91 String::from_utf8_lossy(&output.stderr)
92 );
93 }
94 Err(error) => {
95 log::error!("Error while trying to unmount disk image: {:?}", error);
96 }
97 }
98 }
99}
100
101struct AutoUpdateSetting(bool);
102
103/// Whether or not to automatically check for updates.
104///
105/// Default: true
106#[derive(Clone, Copy, Default, JsonSchema, Deserialize, Serialize)]
107#[serde(transparent)]
108struct AutoUpdateSettingContent(bool);
109
110impl Settings for AutoUpdateSetting {
111 const KEY: Option<&'static str> = Some("auto_update");
112
113 type FileContent = Option<AutoUpdateSettingContent>;
114
115 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
116 let auto_update = [sources.server, sources.release_channel, sources.user]
117 .into_iter()
118 .find_map(|value| value.copied().flatten())
119 .unwrap_or(sources.default.ok_or_else(Self::missing_default)?);
120
121 Ok(Self(auto_update.0))
122 }
123}
124
125#[derive(Default)]
126struct GlobalAutoUpdate(Option<Model<AutoUpdater>>);
127
128impl Global for GlobalAutoUpdate {}
129
130pub fn init(http_client: Arc<HttpClientWithUrl>, cx: &mut AppContext) {
131 AutoUpdateSetting::register(cx);
132
133 cx.observe_new_views(|workspace: &mut Workspace, _cx| {
134 workspace.register_action(|_, action: &Check, cx| check(action, cx));
135
136 workspace.register_action(|_, action, cx| {
137 view_release_notes(action, cx);
138 });
139 })
140 .detach();
141
142 let version = release_channel::AppVersion::global(cx);
143 let auto_updater = cx.new_model(|cx| {
144 let updater = AutoUpdater::new(version, http_client);
145
146 let poll_for_updates = ReleaseChannel::try_global(cx)
147 .map(|channel| channel.poll_for_updates())
148 .unwrap_or(false);
149
150 if option_env!("ZED_UPDATE_EXPLANATION").is_none()
151 && env::var("ZED_UPDATE_EXPLANATION").is_err()
152 && poll_for_updates
153 {
154 let mut update_subscription = AutoUpdateSetting::get_global(cx)
155 .0
156 .then(|| updater.start_polling(cx));
157
158 cx.observe_global::<SettingsStore>(move |updater, cx| {
159 if AutoUpdateSetting::get_global(cx).0 {
160 if update_subscription.is_none() {
161 update_subscription = Some(updater.start_polling(cx))
162 }
163 } else {
164 update_subscription.take();
165 }
166 })
167 .detach();
168 }
169
170 updater
171 });
172 cx.set_global(GlobalAutoUpdate(Some(auto_updater)));
173}
174
175pub fn check(_: &Check, cx: &mut WindowContext) {
176 if let Some(message) = option_env!("ZED_UPDATE_EXPLANATION") {
177 drop(cx.prompt(
178 gpui::PromptLevel::Info,
179 "Zed was installed via a package manager.",
180 Some(message),
181 &["Ok"],
182 ));
183 return;
184 }
185
186 if let Ok(message) = env::var("ZED_UPDATE_EXPLANATION") {
187 drop(cx.prompt(
188 gpui::PromptLevel::Info,
189 "Zed was installed via a package manager.",
190 Some(&message),
191 &["Ok"],
192 ));
193 return;
194 }
195
196 if !ReleaseChannel::try_global(cx)
197 .map(|channel| channel.poll_for_updates())
198 .unwrap_or(false)
199 {
200 return;
201 }
202
203 if let Some(updater) = AutoUpdater::get(cx) {
204 updater.update(cx, |updater, cx| updater.poll(cx));
205 } else {
206 drop(cx.prompt(
207 gpui::PromptLevel::Info,
208 "Could not check for updates",
209 Some("Auto-updates disabled for non-bundled app."),
210 &["Ok"],
211 ));
212 }
213}
214
215pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut AppContext) -> Option<()> {
216 let auto_updater = AutoUpdater::get(cx)?;
217 let release_channel = ReleaseChannel::try_global(cx)?;
218
219 match release_channel {
220 ReleaseChannel::Stable | ReleaseChannel::Preview => {
221 let auto_updater = auto_updater.read(cx);
222 let current_version = auto_updater.current_version;
223 let release_channel = release_channel.dev_name();
224 let path = format!("/releases/{release_channel}/{current_version}");
225 let url = &auto_updater.http_client.build_url(&path);
226 cx.open_url(url);
227 }
228 ReleaseChannel::Nightly => {
229 cx.open_url("https://github.com/zed-industries/zed/commits/nightly/");
230 }
231 ReleaseChannel::Dev => {
232 cx.open_url("https://github.com/zed-industries/zed/commits/main/");
233 }
234 }
235 None
236}
237
238impl AutoUpdater {
239 pub fn get(cx: &mut AppContext) -> Option<Model<Self>> {
240 cx.default_global::<GlobalAutoUpdate>().0.clone()
241 }
242
243 fn new(current_version: SemanticVersion, http_client: Arc<HttpClientWithUrl>) -> Self {
244 Self {
245 status: AutoUpdateStatus::Idle,
246 current_version,
247 http_client,
248 pending_poll: None,
249 }
250 }
251
252 pub fn start_polling(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
253 cx.spawn(|this, mut cx| async move {
254 loop {
255 this.update(&mut cx, |this, cx| this.poll(cx))?;
256 cx.background_executor().timer(POLL_INTERVAL).await;
257 }
258 })
259 }
260
261 pub fn poll(&mut self, cx: &mut ModelContext<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(|this, mut cx| async move {
269 let result = Self::update(this.upgrade()?, cx.clone()).await;
270 this.update(&mut 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 ModelContext<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 AsyncAppContext,
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 AsyncAppContext,
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: &Model<Self>,
375 asset: &str,
376 os: &str,
377 arch: &str,
378 version: Option<SemanticVersion>,
379 release_channel: Option<ReleaseChannel>,
380 cx: &mut AsyncAppContext,
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: &Model<Self>,
425 asset: &str,
426 os: &str,
427 arch: &str,
428 release_channel: Option<ReleaseChannel>,
429 cx: &mut AsyncAppContext,
430 ) -> Result<JsonRelease> {
431 Self::get_release(this, asset, os, arch, None, release_channel, cx).await
432 }
433
434 async fn update(this: Model<Self>, mut cx: AsyncAppContext) -> 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: &AppContext,
513 ) -> Task<Result<()>> {
514 cx.background_executor().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: &AppContext) -> Task<Result<bool>> {
532 cx.background_executor().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: &AsyncAppContext,
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: &AsyncAppContext) -> 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: &AsyncAppContext,
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: &AsyncAppContext,
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: &AsyncAppContext,
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}