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