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::consts::{ARCH, OS},
27 ffi::OsString,
28 path::PathBuf,
29 sync::Arc,
30 time::Duration,
31};
32use update_notification::UpdateNotification;
33use util::ResultExt;
34use workspace::notifications::NotificationId;
35use workspace::Workspace;
36
37const SHOULD_SHOW_UPDATE_NOTIFICATION_KEY: &str = "auto-updater-should-show-updated-notification";
38const POLL_INTERVAL: Duration = Duration::from_secs(60 * 60);
39
40actions!(
41 auto_update,
42 [
43 Check,
44 DismissErrorMessage,
45 ViewReleaseNotes,
46 ViewReleaseNotesLocally
47 ]
48);
49
50#[derive(Serialize)]
51struct UpdateRequestBody {
52 installation_id: Option<Arc<str>>,
53 release_channel: Option<&'static str>,
54 telemetry: bool,
55}
56
57#[derive(Clone, PartialEq, Eq)]
58pub enum AutoUpdateStatus {
59 Idle,
60 Checking,
61 Downloading,
62 Installing,
63 Updated { binary_path: PathBuf },
64 Errored,
65}
66
67impl AutoUpdateStatus {
68 pub fn is_updated(&self) -> bool {
69 matches!(self, Self::Updated { .. })
70 }
71}
72
73pub struct AutoUpdater {
74 status: AutoUpdateStatus,
75 current_version: SemanticVersion,
76 http_client: Arc<HttpClientWithUrl>,
77 pending_poll: Option<Task<Option<()>>>,
78}
79
80#[derive(Deserialize)]
81struct JsonRelease {
82 version: String,
83 url: String,
84}
85
86struct AutoUpdateSetting(bool);
87
88/// Whether or not to automatically check for updates.
89///
90/// Default: true
91#[derive(Clone, Copy, Default, JsonSchema, Deserialize, Serialize)]
92#[serde(transparent)]
93struct AutoUpdateSettingContent(bool);
94
95impl Settings for AutoUpdateSetting {
96 const KEY: Option<&'static str> = Some("auto_update");
97
98 type FileContent = Option<AutoUpdateSettingContent>;
99
100 fn load(sources: SettingsSources<Self::FileContent>, _: &mut AppContext) -> Result<Self> {
101 let auto_update = [sources.release_channel, sources.user]
102 .into_iter()
103 .find_map(|value| value.copied().flatten())
104 .unwrap_or(sources.default.ok_or_else(Self::missing_default)?);
105
106 Ok(Self(auto_update.0))
107 }
108}
109
110#[derive(Default)]
111struct GlobalAutoUpdate(Option<Model<AutoUpdater>>);
112
113impl Global for GlobalAutoUpdate {}
114
115#[derive(Deserialize)]
116struct ReleaseNotesBody {
117 title: String,
118 release_notes: String,
119}
120
121pub fn init(http_client: Arc<HttpClientWithUrl>, cx: &mut AppContext) {
122 AutoUpdateSetting::register(cx);
123
124 cx.observe_new_views(|workspace: &mut Workspace, _cx| {
125 workspace.register_action(|_, action: &Check, cx| check(action, cx));
126
127 workspace.register_action(|_, action, cx| {
128 view_release_notes(action, cx);
129 });
130
131 workspace.register_action(|workspace, _: &ViewReleaseNotesLocally, cx| {
132 view_release_notes_locally(workspace, cx);
133 });
134 })
135 .detach();
136
137 let version = release_channel::AppVersion::global(cx);
138 let auto_updater = cx.new_model(|cx| {
139 let updater = AutoUpdater::new(version, http_client);
140
141 let mut update_subscription = AutoUpdateSetting::get_global(cx)
142 .0
143 .then(|| updater.start_polling(cx));
144
145 cx.observe_global::<SettingsStore>(move |updater, cx| {
146 if AutoUpdateSetting::get_global(cx).0 {
147 if update_subscription.is_none() {
148 update_subscription = Some(updater.start_polling(cx))
149 }
150 } else {
151 update_subscription.take();
152 }
153 })
154 .detach();
155
156 updater
157 });
158 cx.set_global(GlobalAutoUpdate(Some(auto_updater)));
159}
160
161pub fn check(_: &Check, cx: &mut WindowContext) {
162 if let Some(updater) = AutoUpdater::get(cx) {
163 updater.update(cx, |updater, cx| updater.poll(cx));
164 } else {
165 drop(cx.prompt(
166 gpui::PromptLevel::Info,
167 "Could not check for updates",
168 Some("Auto-updates disabled for non-bundled app."),
169 &["Ok"],
170 ));
171 }
172}
173
174pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut AppContext) -> Option<()> {
175 let auto_updater = AutoUpdater::get(cx)?;
176 let release_channel = ReleaseChannel::try_global(cx)?;
177
178 if matches!(
179 release_channel,
180 ReleaseChannel::Stable | ReleaseChannel::Preview
181 ) {
182 let auto_updater = auto_updater.read(cx);
183 let release_channel = release_channel.dev_name();
184 let current_version = auto_updater.current_version;
185 let url = &auto_updater
186 .http_client
187 .build_url(&format!("/releases/{release_channel}/{current_version}"));
188 cx.open_url(&url);
189 }
190
191 None
192}
193
194fn view_release_notes_locally(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
195 let release_channel = ReleaseChannel::global(cx);
196 let version = AppVersion::global(cx).to_string();
197
198 let client = client::Client::global(cx).http_client();
199 let url = client.build_url(&format!(
200 "/api/release_notes/{}/{}",
201 release_channel.dev_name(),
202 version
203 ));
204
205 let markdown = workspace
206 .app_state()
207 .languages
208 .language_for_name("Markdown");
209
210 workspace
211 .with_local_workspace(cx, move |_, cx| {
212 cx.spawn(|workspace, mut cx| async move {
213 let markdown = markdown.await.log_err();
214 let response = client.get(&url, Default::default(), true).await;
215 let Some(mut response) = response.log_err() else {
216 return;
217 };
218
219 let mut body = Vec::new();
220 response.body_mut().read_to_end(&mut body).await.ok();
221
222 let body: serde_json::Result<ReleaseNotesBody> =
223 serde_json::from_slice(body.as_slice());
224
225 if let Ok(body) = body {
226 workspace
227 .update(&mut cx, |workspace, cx| {
228 let project = workspace.project().clone();
229 let buffer = project.update(cx, |project, cx| {
230 project.create_local_buffer("", markdown, cx)
231 });
232 buffer.update(cx, |buffer, cx| {
233 buffer.edit([(0..0, body.release_notes)], None, cx)
234 });
235 let language_registry = project.read(cx).languages().clone();
236
237 let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
238
239 let tab_description = SharedString::from(body.title.to_string());
240 let editor = cx.new_view(|cx| {
241 Editor::for_multibuffer(buffer, Some(project), true, cx)
242 });
243 let workspace_handle = workspace.weak_handle();
244 let view: View<MarkdownPreviewView> = MarkdownPreviewView::new(
245 MarkdownPreviewMode::Default,
246 editor,
247 workspace_handle,
248 language_registry,
249 Some(tab_description),
250 cx,
251 );
252 workspace.add_item_to_active_pane(Box::new(view.clone()), None, cx);
253 cx.notify();
254 })
255 .log_err();
256 }
257 })
258 .detach();
259 })
260 .detach();
261}
262
263pub fn notify_of_any_new_update(cx: &mut ViewContext<Workspace>) -> Option<()> {
264 let updater = AutoUpdater::get(cx)?;
265 let version = updater.read(cx).current_version;
266 let should_show_notification = updater.read(cx).should_show_update_notification(cx);
267
268 cx.spawn(|workspace, mut cx| async move {
269 let should_show_notification = should_show_notification.await?;
270 if should_show_notification {
271 workspace.update(&mut cx, |workspace, cx| {
272 workspace.show_notification(
273 NotificationId::unique::<UpdateNotification>(),
274 cx,
275 |cx| cx.new_view(|_| UpdateNotification::new(version)),
276 );
277 updater
278 .read(cx)
279 .set_should_show_update_notification(false, cx)
280 .detach_and_log_err(cx);
281 })?;
282 }
283 anyhow::Ok(())
284 })
285 .detach();
286
287 None
288}
289
290impl AutoUpdater {
291 pub fn get(cx: &mut AppContext) -> Option<Model<Self>> {
292 cx.default_global::<GlobalAutoUpdate>().0.clone()
293 }
294
295 fn new(current_version: SemanticVersion, http_client: Arc<HttpClientWithUrl>) -> Self {
296 Self {
297 status: AutoUpdateStatus::Idle,
298 current_version,
299 http_client,
300 pending_poll: None,
301 }
302 }
303
304 pub fn start_polling(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
305 cx.spawn(|this, mut cx| async move {
306 loop {
307 this.update(&mut cx, |this, cx| this.poll(cx))?;
308 cx.background_executor().timer(POLL_INTERVAL).await;
309 }
310 })
311 }
312
313 pub fn poll(&mut self, cx: &mut ModelContext<Self>) {
314 if self.pending_poll.is_some() || self.status.is_updated() {
315 return;
316 }
317
318 self.status = AutoUpdateStatus::Checking;
319 cx.notify();
320
321 self.pending_poll = Some(cx.spawn(|this, mut cx| async move {
322 let result = Self::update(this.upgrade()?, cx.clone()).await;
323 this.update(&mut cx, |this, cx| {
324 this.pending_poll = None;
325 if let Err(error) = result {
326 log::error!("auto-update failed: error:{:?}", error);
327 this.status = AutoUpdateStatus::Errored;
328 cx.notify();
329 }
330 })
331 .ok()
332 }));
333 }
334
335 pub fn status(&self) -> AutoUpdateStatus {
336 self.status.clone()
337 }
338
339 pub fn dismiss_error(&mut self, cx: &mut ModelContext<Self>) {
340 self.status = AutoUpdateStatus::Idle;
341 cx.notify();
342 }
343
344 async fn update(this: Model<Self>, mut cx: AsyncAppContext) -> Result<()> {
345 let (client, current_version) = this.read_with(&cx, |this, _| {
346 (this.http_client.clone(), this.current_version)
347 })?;
348
349 let asset = match OS {
350 "linux" => format!("zed-linux-{}.tar.gz", ARCH),
351 "macos" => "Zed.dmg".into(),
352 _ => return Err(anyhow!("auto-update not supported for OS {:?}", OS)),
353 };
354
355 let mut url_string = client.build_url(&format!(
356 "/api/releases/latest?asset={}&os={}&arch={}",
357 asset, OS, ARCH
358 ));
359 cx.update(|cx| {
360 if let Some(param) = ReleaseChannel::try_global(cx)
361 .and_then(|release_channel| release_channel.release_query_param())
362 {
363 url_string += "&";
364 url_string += param;
365 }
366 })?;
367
368 let mut response = client.get(&url_string, Default::default(), true).await?;
369
370 let mut body = Vec::new();
371 response
372 .body_mut()
373 .read_to_end(&mut body)
374 .await
375 .context("error reading release")?;
376
377 let release: JsonRelease =
378 serde_json::from_slice(body.as_slice()).context("error deserializing release")?;
379
380 let should_download = match *RELEASE_CHANNEL {
381 ReleaseChannel::Nightly => cx
382 .update(|cx| AppCommitSha::try_global(cx).map(|sha| release.version != sha.0))
383 .ok()
384 .flatten()
385 .unwrap_or(true),
386 _ => release.version.parse::<SemanticVersion>()? > current_version,
387 };
388
389 if !should_download {
390 this.update(&mut cx, |this, cx| {
391 this.status = AutoUpdateStatus::Idle;
392 cx.notify();
393 })?;
394 return Ok(());
395 }
396
397 this.update(&mut cx, |this, cx| {
398 this.status = AutoUpdateStatus::Downloading;
399 cx.notify();
400 })?;
401
402 let temp_dir = tempfile::Builder::new()
403 .prefix("zed-auto-update")
404 .tempdir()?;
405 let downloaded_asset = download_release(&temp_dir, release, &asset, client, &cx).await?;
406
407 this.update(&mut cx, |this, cx| {
408 this.status = AutoUpdateStatus::Installing;
409 cx.notify();
410 })?;
411
412 // We store the path of our current binary, before we install, since installation might
413 // delete it. Once deleted, it's hard to get the path to our binary on Linux.
414 // So we cache it here, which allows us to then restart later on.
415 let binary_path = cx.update(|cx| cx.app_path())??;
416
417 match OS {
418 "macos" => install_release_macos(&temp_dir, downloaded_asset, &cx).await,
419 "linux" => install_release_linux(&temp_dir, downloaded_asset, &cx).await,
420 _ => Err(anyhow!("not supported: {:?}", OS)),
421 }?;
422
423 this.update(&mut cx, |this, cx| {
424 this.set_should_show_update_notification(true, cx)
425 .detach_and_log_err(cx);
426 this.status = AutoUpdateStatus::Updated { binary_path };
427 cx.notify();
428 })?;
429
430 Ok(())
431 }
432
433 fn set_should_show_update_notification(
434 &self,
435 should_show: bool,
436 cx: &AppContext,
437 ) -> Task<Result<()>> {
438 cx.background_executor().spawn(async move {
439 if should_show {
440 KEY_VALUE_STORE
441 .write_kvp(
442 SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
443 "".to_string(),
444 )
445 .await?;
446 } else {
447 KEY_VALUE_STORE
448 .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
449 .await?;
450 }
451 Ok(())
452 })
453 }
454
455 fn should_show_update_notification(&self, cx: &AppContext) -> Task<Result<bool>> {
456 cx.background_executor().spawn(async move {
457 Ok(KEY_VALUE_STORE
458 .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
459 .is_some())
460 })
461 }
462}
463
464async fn download_release(
465 temp_dir: &tempfile::TempDir,
466 release: JsonRelease,
467 target_filename: &str,
468 client: Arc<HttpClientWithUrl>,
469 cx: &AsyncAppContext,
470) -> Result<PathBuf> {
471 let target_path = temp_dir.path().join(target_filename);
472 let mut target_file = File::create(&target_path).await?;
473
474 let (installation_id, release_channel, telemetry) = cx.update(|cx| {
475 let installation_id = Client::global(cx).telemetry().installation_id();
476 let release_channel =
477 ReleaseChannel::try_global(cx).map(|release_channel| release_channel.display_name());
478 let telemetry = TelemetrySettings::get_global(cx).metrics;
479
480 (installation_id, release_channel, telemetry)
481 })?;
482
483 let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
484 installation_id,
485 release_channel,
486 telemetry,
487 })?);
488
489 let mut response = client.get(&release.url, request_body, true).await?;
490 smol::io::copy(response.body_mut(), &mut target_file).await?;
491 log::info!("downloaded update. path:{:?}", target_path);
492
493 Ok(target_path)
494}
495
496async fn install_release_linux(
497 temp_dir: &tempfile::TempDir,
498 downloaded_tar_gz: PathBuf,
499 cx: &AsyncAppContext,
500) -> Result<()> {
501 let channel = cx.update(|cx| ReleaseChannel::global(cx).dev_name())?;
502 let home_dir = PathBuf::from(std::env::var("HOME").context("no HOME env var set")?);
503
504 let extracted = temp_dir.path().join("zed");
505 fs::create_dir_all(&extracted)
506 .await
507 .context("failed to create directory into which to extract update")?;
508
509 let output = Command::new("tar")
510 .arg("-xzf")
511 .arg(&downloaded_tar_gz)
512 .arg("-C")
513 .arg(&extracted)
514 .output()
515 .await?;
516
517 anyhow::ensure!(
518 output.status.success(),
519 "failed to extract {:?} to {:?}: {:?}",
520 downloaded_tar_gz,
521 extracted,
522 String::from_utf8_lossy(&output.stderr)
523 );
524
525 let suffix = if channel != "stable" {
526 format!("-{}", channel)
527 } else {
528 String::default()
529 };
530 let app_folder_name = format!("zed{}.app", suffix);
531
532 let from = extracted.join(&app_folder_name);
533 let to = home_dir.join(".local");
534
535 let output = Command::new("rsync")
536 .args(&["-av", "--delete"])
537 .arg(&from)
538 .arg(&to)
539 .output()
540 .await?;
541
542 anyhow::ensure!(
543 output.status.success(),
544 "failed to copy Zed update from {:?} to {:?}: {:?}",
545 from,
546 to,
547 String::from_utf8_lossy(&output.stderr)
548 );
549
550 Ok(())
551}
552
553async fn install_release_macos(
554 temp_dir: &tempfile::TempDir,
555 downloaded_dmg: PathBuf,
556 cx: &AsyncAppContext,
557) -> Result<()> {
558 let running_app_path = ZED_APP_PATH
559 .clone()
560 .map_or_else(|| cx.update(|cx| cx.app_path())?, Ok)?;
561 let running_app_filename = running_app_path
562 .file_name()
563 .ok_or_else(|| anyhow!("invalid running app path"))?;
564
565 let mount_path = temp_dir.path().join("Zed");
566 let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
567
568 mounted_app_path.push("/");
569 let output = Command::new("hdiutil")
570 .args(&["attach", "-nobrowse"])
571 .arg(&downloaded_dmg)
572 .arg("-mountroot")
573 .arg(&temp_dir.path())
574 .output()
575 .await?;
576
577 anyhow::ensure!(
578 output.status.success(),
579 "failed to mount: {:?}",
580 String::from_utf8_lossy(&output.stderr)
581 );
582
583 let output = Command::new("rsync")
584 .args(&["-av", "--delete"])
585 .arg(&mounted_app_path)
586 .arg(&running_app_path)
587 .output()
588 .await?;
589
590 anyhow::ensure!(
591 output.status.success(),
592 "failed to copy app: {:?}",
593 String::from_utf8_lossy(&output.stderr)
594 );
595
596 let output = Command::new("hdiutil")
597 .args(&["detach"])
598 .arg(&mount_path)
599 .output()
600 .await?;
601
602 anyhow::ensure!(
603 output.status.success(),
604 "failed to unount: {:?}",
605 String::from_utf8_lossy(&output.stderr)
606 );
607
608 Ok(())
609}