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