1mod update_notification;
2
3use anyhow::{anyhow, Context, Result};
4use client::{Client, TelemetrySettings, ZED_APP_PATH};
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::{HttpClient, HttpClientWithUrl};
24use release_channel::{AppCommitSha, AppVersion, ReleaseChannel};
25use std::{
26 env::{
27 self,
28 consts::{ARCH, OS},
29 },
30 ffi::OsString,
31 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(Box::new(view.clone()), None, cx);
292 cx.notify();
293 })
294 .log_err();
295 }
296 })
297 .detach();
298 })
299 .detach();
300}
301
302pub fn notify_of_any_new_update(cx: &mut ViewContext<Workspace>) -> Option<()> {
303 let updater = AutoUpdater::get(cx)?;
304 let version = updater.read(cx).current_version;
305 let should_show_notification = updater.read(cx).should_show_update_notification(cx);
306
307 cx.spawn(|workspace, mut cx| async move {
308 let should_show_notification = should_show_notification.await?;
309 if should_show_notification {
310 workspace.update(&mut cx, |workspace, cx| {
311 workspace.show_notification(
312 NotificationId::unique::<UpdateNotification>(),
313 cx,
314 |cx| cx.new_view(|_| UpdateNotification::new(version)),
315 );
316 updater
317 .read(cx)
318 .set_should_show_update_notification(false, cx)
319 .detach_and_log_err(cx);
320 })?;
321 }
322 anyhow::Ok(())
323 })
324 .detach();
325
326 None
327}
328
329impl AutoUpdater {
330 pub fn get(cx: &mut AppContext) -> Option<Model<Self>> {
331 cx.default_global::<GlobalAutoUpdate>().0.clone()
332 }
333
334 fn new(current_version: SemanticVersion, http_client: Arc<HttpClientWithUrl>) -> Self {
335 Self {
336 status: AutoUpdateStatus::Idle,
337 current_version,
338 http_client,
339 pending_poll: None,
340 }
341 }
342
343 pub fn start_polling(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
344 cx.spawn(|this, mut cx| async move {
345 loop {
346 this.update(&mut cx, |this, cx| this.poll(cx))?;
347 cx.background_executor().timer(POLL_INTERVAL).await;
348 }
349 })
350 }
351
352 pub fn poll(&mut self, cx: &mut ModelContext<Self>) {
353 if self.pending_poll.is_some() || self.status.is_updated() {
354 return;
355 }
356
357 self.status = AutoUpdateStatus::Checking;
358 cx.notify();
359
360 self.pending_poll = Some(cx.spawn(|this, mut cx| async move {
361 let result = Self::update(this.upgrade()?, cx.clone()).await;
362 this.update(&mut cx, |this, cx| {
363 this.pending_poll = None;
364 if let Err(error) = result {
365 log::error!("auto-update failed: error:{:?}", error);
366 this.status = AutoUpdateStatus::Errored;
367 cx.notify();
368 }
369 })
370 .ok()
371 }));
372 }
373
374 pub fn status(&self) -> AutoUpdateStatus {
375 self.status.clone()
376 }
377
378 pub fn dismiss_error(&mut self, cx: &mut ModelContext<Self>) {
379 self.status = AutoUpdateStatus::Idle;
380 cx.notify();
381 }
382
383 async fn update(this: Model<Self>, mut cx: AsyncAppContext) -> Result<()> {
384 let (client, current_version) = this.read_with(&cx, |this, _| {
385 (this.http_client.clone(), this.current_version)
386 })?;
387
388 let asset = match OS {
389 "linux" => format!("zed-linux-{}.tar.gz", ARCH),
390 "macos" => "Zed.dmg".into(),
391 _ => return Err(anyhow!("auto-update not supported for OS {:?}", OS)),
392 };
393
394 let mut url_string = client.build_url(&format!(
395 "/api/releases/latest?asset={}&os={}&arch={}",
396 asset, OS, ARCH
397 ));
398 cx.update(|cx| {
399 if let Some(param) = ReleaseChannel::try_global(cx)
400 .and_then(|release_channel| release_channel.release_query_param())
401 {
402 url_string += "&";
403 url_string += param;
404 }
405 })?;
406
407 let mut response = client.get(&url_string, Default::default(), true).await?;
408
409 let mut body = Vec::new();
410 response
411 .body_mut()
412 .read_to_end(&mut body)
413 .await
414 .context("error reading release")?;
415
416 let release: JsonRelease =
417 serde_json::from_slice(body.as_slice()).context("error deserializing release")?;
418
419 let should_download = match *RELEASE_CHANNEL {
420 ReleaseChannel::Nightly => cx
421 .update(|cx| AppCommitSha::try_global(cx).map(|sha| release.version != sha.0))
422 .ok()
423 .flatten()
424 .unwrap_or(true),
425 _ => release.version.parse::<SemanticVersion>()? > current_version,
426 };
427
428 if !should_download {
429 this.update(&mut cx, |this, cx| {
430 this.status = AutoUpdateStatus::Idle;
431 cx.notify();
432 })?;
433 return Ok(());
434 }
435
436 this.update(&mut cx, |this, cx| {
437 this.status = AutoUpdateStatus::Downloading;
438 cx.notify();
439 })?;
440
441 let temp_dir = tempfile::Builder::new()
442 .prefix("zed-auto-update")
443 .tempdir()?;
444 let downloaded_asset = download_release(&temp_dir, release, &asset, client, &cx).await?;
445
446 this.update(&mut cx, |this, cx| {
447 this.status = AutoUpdateStatus::Installing;
448 cx.notify();
449 })?;
450
451 // We store the path of our current binary, before we install, since installation might
452 // delete it. Once deleted, it's hard to get the path to our binary on Linux.
453 // So we cache it here, which allows us to then restart later on.
454 let binary_path = cx.update(|cx| cx.app_path())??;
455
456 match OS {
457 "macos" => install_release_macos(&temp_dir, downloaded_asset, &cx).await,
458 "linux" => install_release_linux(&temp_dir, downloaded_asset, &cx).await,
459 _ => Err(anyhow!("not supported: {:?}", OS)),
460 }?;
461
462 this.update(&mut cx, |this, cx| {
463 this.set_should_show_update_notification(true, cx)
464 .detach_and_log_err(cx);
465 this.status = AutoUpdateStatus::Updated { binary_path };
466 cx.notify();
467 })?;
468
469 Ok(())
470 }
471
472 fn set_should_show_update_notification(
473 &self,
474 should_show: bool,
475 cx: &AppContext,
476 ) -> Task<Result<()>> {
477 cx.background_executor().spawn(async move {
478 if should_show {
479 KEY_VALUE_STORE
480 .write_kvp(
481 SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
482 "".to_string(),
483 )
484 .await?;
485 } else {
486 KEY_VALUE_STORE
487 .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
488 .await?;
489 }
490 Ok(())
491 })
492 }
493
494 fn should_show_update_notification(&self, cx: &AppContext) -> Task<Result<bool>> {
495 cx.background_executor().spawn(async move {
496 Ok(KEY_VALUE_STORE
497 .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
498 .is_some())
499 })
500 }
501}
502
503async fn download_release(
504 temp_dir: &tempfile::TempDir,
505 release: JsonRelease,
506 target_filename: &str,
507 client: Arc<HttpClientWithUrl>,
508 cx: &AsyncAppContext,
509) -> Result<PathBuf> {
510 let target_path = temp_dir.path().join(target_filename);
511 let mut target_file = File::create(&target_path).await?;
512
513 let (installation_id, release_channel, telemetry) = cx.update(|cx| {
514 let installation_id = Client::global(cx).telemetry().installation_id();
515 let release_channel =
516 ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
517 let telemetry = TelemetrySettings::get_global(cx).metrics;
518
519 (installation_id, release_channel, telemetry)
520 })?;
521
522 let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
523 installation_id,
524 release_channel,
525 telemetry,
526 })?);
527
528 let mut response = client.get(&release.url, request_body, true).await?;
529 smol::io::copy(response.body_mut(), &mut target_file).await?;
530 log::info!("downloaded update. path:{:?}", target_path);
531
532 Ok(target_path)
533}
534
535async fn install_release_linux(
536 temp_dir: &tempfile::TempDir,
537 downloaded_tar_gz: PathBuf,
538 cx: &AsyncAppContext,
539) -> Result<()> {
540 let channel = cx.update(|cx| ReleaseChannel::global(cx).dev_name())?;
541 let home_dir = PathBuf::from(env::var("HOME").context("no HOME env var set")?);
542
543 let extracted = temp_dir.path().join("zed");
544 fs::create_dir_all(&extracted)
545 .await
546 .context("failed to create directory into which to extract update")?;
547
548 let output = Command::new("tar")
549 .arg("-xzf")
550 .arg(&downloaded_tar_gz)
551 .arg("-C")
552 .arg(&extracted)
553 .output()
554 .await?;
555
556 anyhow::ensure!(
557 output.status.success(),
558 "failed to extract {:?} to {:?}: {:?}",
559 downloaded_tar_gz,
560 extracted,
561 String::from_utf8_lossy(&output.stderr)
562 );
563
564 let suffix = if channel != "stable" {
565 format!("-{}", channel)
566 } else {
567 String::default()
568 };
569 let app_folder_name = format!("zed{}.app", suffix);
570
571 let from = extracted.join(&app_folder_name);
572 let to = home_dir.join(".local");
573
574 let output = Command::new("rsync")
575 .args(&["-av", "--delete"])
576 .arg(&from)
577 .arg(&to)
578 .output()
579 .await?;
580
581 anyhow::ensure!(
582 output.status.success(),
583 "failed to copy Zed update from {:?} to {:?}: {:?}",
584 from,
585 to,
586 String::from_utf8_lossy(&output.stderr)
587 );
588
589 Ok(())
590}
591
592async fn install_release_macos(
593 temp_dir: &tempfile::TempDir,
594 downloaded_dmg: PathBuf,
595 cx: &AsyncAppContext,
596) -> Result<()> {
597 let running_app_path = ZED_APP_PATH
598 .clone()
599 .map_or_else(|| cx.update(|cx| cx.app_path())?, Ok)?;
600 let running_app_filename = running_app_path
601 .file_name()
602 .ok_or_else(|| anyhow!("invalid running app path"))?;
603
604 let mount_path = temp_dir.path().join("Zed");
605 let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
606
607 mounted_app_path.push("/");
608 let output = Command::new("hdiutil")
609 .args(&["attach", "-nobrowse"])
610 .arg(&downloaded_dmg)
611 .arg("-mountroot")
612 .arg(&temp_dir.path())
613 .output()
614 .await?;
615
616 anyhow::ensure!(
617 output.status.success(),
618 "failed to mount: {:?}",
619 String::from_utf8_lossy(&output.stderr)
620 );
621
622 let output = Command::new("rsync")
623 .args(&["-av", "--delete"])
624 .arg(&mounted_app_path)
625 .arg(&running_app_path)
626 .output()
627 .await?;
628
629 anyhow::ensure!(
630 output.status.success(),
631 "failed to copy app: {:?}",
632 String::from_utf8_lossy(&output.stderr)
633 );
634
635 let output = Command::new("hdiutil")
636 .args(&["detach"])
637 .arg(&mount_path)
638 .output()
639 .await?;
640
641 anyhow::ensure!(
642 output.status.success(),
643 "failed to unount: {:?}",
644 String::from_utf8_lossy(&output.stderr)
645 );
646
647 Ok(())
648}