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