auto_update.rs

  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::MarkdownPreviewView;
 15use schemars::JsonSchema;
 16use serde::Deserialize;
 17use serde_derive::Serialize;
 18use smol::io::AsyncReadExt;
 19
 20use settings::{Settings, 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    sync::Arc,
 28    time::Duration,
 29};
 30use update_notification::UpdateNotification;
 31use util::{
 32    http::{HttpClient, HttpClientWithUrl},
 33    ResultExt,
 34};
 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, Copy, PartialEq, Eq)]
 58pub enum AutoUpdateStatus {
 59    Idle,
 60    Checking,
 61    Downloading,
 62    Installing,
 63    Updated,
 64    Errored,
 65}
 66
 67pub struct AutoUpdater {
 68    status: AutoUpdateStatus,
 69    current_version: SemanticVersion,
 70    http_client: Arc<HttpClientWithUrl>,
 71    pending_poll: Option<Task<Option<()>>>,
 72}
 73
 74#[derive(Deserialize)]
 75struct JsonRelease {
 76    version: String,
 77    url: String,
 78}
 79
 80struct AutoUpdateSetting(bool);
 81
 82/// Whether or not to automatically check for updates.
 83///
 84/// Default: true
 85#[derive(Clone, Default, JsonSchema, Deserialize, Serialize)]
 86#[serde(transparent)]
 87struct AutoUpdateSettingOverride(Option<bool>);
 88
 89impl Settings for AutoUpdateSetting {
 90    const KEY: Option<&'static str> = Some("auto_update");
 91
 92    type FileContent = AutoUpdateSettingOverride;
 93
 94    fn load(
 95        default_value: &Self::FileContent,
 96        user_values: &[&Self::FileContent],
 97        _: &mut AppContext,
 98    ) -> Result<Self> {
 99        Ok(Self(
100            Self::json_merge(default_value, user_values)?
101                .0
102                .ok_or_else(Self::missing_default)?,
103        ))
104    }
105}
106
107#[derive(Default)]
108struct GlobalAutoUpdate(Option<Model<AutoUpdater>>);
109
110impl Global for GlobalAutoUpdate {}
111
112#[derive(Deserialize)]
113struct ReleaseNotesBody {
114    title: String,
115    release_notes: String,
116}
117
118pub fn init(http_client: Arc<HttpClientWithUrl>, cx: &mut AppContext) {
119    AutoUpdateSetting::register(cx);
120
121    cx.observe_new_views(|workspace: &mut Workspace, _cx| {
122        workspace.register_action(|_, action: &Check, cx| check(action, cx));
123
124        workspace.register_action(|_, action, cx| {
125            view_release_notes(action, cx);
126        });
127
128        workspace.register_action(|workspace, _: &ViewReleaseNotesLocally, cx| {
129            view_release_notes_locally(workspace, cx);
130        });
131    })
132    .detach();
133
134    let version = release_channel::AppVersion::global(cx);
135    let auto_updater = cx.new_model(|cx| {
136        let updater = AutoUpdater::new(version, http_client);
137
138        let mut update_subscription = AutoUpdateSetting::get_global(cx)
139            .0
140            .then(|| updater.start_polling(cx));
141
142        cx.observe_global::<SettingsStore>(move |updater, cx| {
143            if AutoUpdateSetting::get_global(cx).0 {
144                if update_subscription.is_none() {
145                    update_subscription = Some(updater.start_polling(cx))
146                }
147            } else {
148                update_subscription.take();
149            }
150        })
151        .detach();
152
153        updater
154    });
155    cx.set_global(GlobalAutoUpdate(Some(auto_updater)));
156}
157
158pub fn check(_: &Check, cx: &mut WindowContext) {
159    if let Some(updater) = AutoUpdater::get(cx) {
160        updater.update(cx, |updater, cx| updater.poll(cx));
161    } else {
162        drop(cx.prompt(
163            gpui::PromptLevel::Info,
164            "Could not check for updates",
165            Some("Auto-updates disabled for non-bundled app."),
166            &["Ok"],
167        ));
168    }
169}
170
171pub fn view_release_notes(_: &ViewReleaseNotes, cx: &mut AppContext) -> Option<()> {
172    let auto_updater = AutoUpdater::get(cx)?;
173    let release_channel = ReleaseChannel::try_global(cx)?;
174
175    if matches!(
176        release_channel,
177        ReleaseChannel::Stable | ReleaseChannel::Preview
178    ) {
179        let auto_updater = auto_updater.read(cx);
180        let release_channel = release_channel.dev_name();
181        let current_version = auto_updater.current_version;
182        let url = &auto_updater
183            .http_client
184            .build_url(&format!("/releases/{release_channel}/{current_version}"));
185        cx.open_url(&url);
186    }
187
188    None
189}
190
191fn view_release_notes_locally(workspace: &mut Workspace, cx: &mut ViewContext<Workspace>) {
192    let release_channel = ReleaseChannel::global(cx);
193    let version = AppVersion::global(cx).to_string();
194
195    let client = client::Client::global(cx).http_client();
196    let url = client.build_url(&format!(
197        "/api/release_notes/{}/{}",
198        release_channel.dev_name(),
199        version
200    ));
201
202    let markdown = workspace
203        .app_state()
204        .languages
205        .language_for_name("Markdown");
206
207    workspace
208        .with_local_workspace(cx, move |_, cx| {
209            cx.spawn(|workspace, mut cx| async move {
210                let markdown = markdown.await.log_err();
211                let response = client.get(&url, Default::default(), true).await;
212                let Some(mut response) = response.log_err() else {
213                    return;
214                };
215
216                let mut body = Vec::new();
217                response.body_mut().read_to_end(&mut body).await.ok();
218
219                let body: serde_json::Result<ReleaseNotesBody> =
220                    serde_json::from_slice(body.as_slice());
221
222                if let Ok(body) = body {
223                    workspace
224                        .update(&mut cx, |workspace, cx| {
225                            let project = workspace.project().clone();
226                            let buffer = project
227                                .update(cx, |project, cx| project.create_buffer("", markdown, cx))
228                                .expect("creating buffers on a local workspace always succeeds");
229                            buffer.update(cx, |buffer, cx| {
230                                buffer.edit([(0..0, body.release_notes)], None, cx)
231                            });
232
233                            let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
234
235                            let tab_description = SharedString::from(body.title.to_string());
236                            let editor = cx
237                                .new_view(|cx| Editor::for_multibuffer(buffer, Some(project), cx));
238                            let workspace_handle = workspace.weak_handle();
239                            let view: View<MarkdownPreviewView> = MarkdownPreviewView::new(
240                                editor,
241                                workspace_handle,
242                                Some(tab_description),
243                                cx,
244                            );
245                            workspace.add_item_to_active_pane(Box::new(view.clone()), cx);
246                            cx.notify();
247                        })
248                        .log_err();
249                }
250            })
251            .detach();
252        })
253        .detach();
254}
255
256pub fn notify_of_any_new_update(cx: &mut ViewContext<Workspace>) -> Option<()> {
257    let updater = AutoUpdater::get(cx)?;
258    let version = updater.read(cx).current_version;
259    let should_show_notification = updater.read(cx).should_show_update_notification(cx);
260
261    cx.spawn(|workspace, mut cx| async move {
262        let should_show_notification = should_show_notification.await?;
263        if should_show_notification {
264            workspace.update(&mut cx, |workspace, cx| {
265                workspace.show_notification(0, cx, |cx| {
266                    cx.new_view(|_| UpdateNotification::new(version))
267                });
268                updater
269                    .read(cx)
270                    .set_should_show_update_notification(false, cx)
271                    .detach_and_log_err(cx);
272            })?;
273        }
274        anyhow::Ok(())
275    })
276    .detach();
277
278    None
279}
280
281impl AutoUpdater {
282    pub fn get(cx: &mut AppContext) -> Option<Model<Self>> {
283        cx.default_global::<GlobalAutoUpdate>().0.clone()
284    }
285
286    fn new(current_version: SemanticVersion, http_client: Arc<HttpClientWithUrl>) -> Self {
287        Self {
288            status: AutoUpdateStatus::Idle,
289            current_version,
290            http_client,
291            pending_poll: None,
292        }
293    }
294
295    pub fn start_polling(&self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
296        cx.spawn(|this, mut cx| async move {
297            loop {
298                this.update(&mut cx, |this, cx| this.poll(cx))?;
299                cx.background_executor().timer(POLL_INTERVAL).await;
300            }
301        })
302    }
303
304    pub fn poll(&mut self, cx: &mut ModelContext<Self>) {
305        if self.pending_poll.is_some() || self.status == AutoUpdateStatus::Updated {
306            return;
307        }
308
309        self.status = AutoUpdateStatus::Checking;
310        cx.notify();
311
312        self.pending_poll = Some(cx.spawn(|this, mut cx| async move {
313            let result = Self::update(this.upgrade()?, cx.clone()).await;
314            this.update(&mut cx, |this, cx| {
315                this.pending_poll = None;
316                if let Err(error) = result {
317                    log::error!("auto-update failed: error:{:?}", error);
318                    this.status = AutoUpdateStatus::Errored;
319                    cx.notify();
320                }
321            })
322            .ok()
323        }));
324    }
325
326    pub fn status(&self) -> AutoUpdateStatus {
327        self.status
328    }
329
330    pub fn dismiss_error(&mut self, cx: &mut ModelContext<Self>) {
331        self.status = AutoUpdateStatus::Idle;
332        cx.notify();
333    }
334
335    async fn update(this: Model<Self>, mut cx: AsyncAppContext) -> Result<()> {
336        let (client, current_version) = this.read_with(&cx, |this, _| {
337            (this.http_client.clone(), this.current_version)
338        })?;
339
340        let mut url_string = client.build_url(&format!(
341            "/api/releases/latest?asset=Zed.dmg&os={}&arch={}",
342            OS, ARCH
343        ));
344        cx.update(|cx| {
345            if let Some(param) = ReleaseChannel::try_global(cx)
346                .and_then(|release_channel| release_channel.release_query_param())
347            {
348                url_string += "&";
349                url_string += param;
350            }
351        })?;
352
353        let mut response = client.get(&url_string, Default::default(), true).await?;
354
355        let mut body = Vec::new();
356        response
357            .body_mut()
358            .read_to_end(&mut body)
359            .await
360            .context("error reading release")?;
361        let release: JsonRelease =
362            serde_json::from_slice(body.as_slice()).context("error deserializing release")?;
363
364        let should_download = match *RELEASE_CHANNEL {
365            ReleaseChannel::Nightly => cx
366                .update(|cx| AppCommitSha::try_global(cx).map(|sha| release.version != sha.0))
367                .ok()
368                .flatten()
369                .unwrap_or(true),
370            _ => release.version.parse::<SemanticVersion>()? > current_version,
371        };
372
373        if !should_download {
374            this.update(&mut cx, |this, cx| {
375                this.status = AutoUpdateStatus::Idle;
376                cx.notify();
377            })?;
378            return Ok(());
379        }
380
381        this.update(&mut cx, |this, cx| {
382            this.status = AutoUpdateStatus::Downloading;
383            cx.notify();
384        })?;
385
386        let temp_dir = tempfile::Builder::new()
387            .prefix("zed-auto-update")
388            .tempdir()?;
389        let dmg_path = temp_dir.path().join("Zed.dmg");
390        let mount_path = temp_dir.path().join("Zed");
391        let running_app_path = ZED_APP_PATH
392            .clone()
393            .map_or_else(|| cx.update(|cx| cx.app_path())?, Ok)?;
394        let running_app_filename = running_app_path
395            .file_name()
396            .ok_or_else(|| anyhow!("invalid running app path"))?;
397        let mut mounted_app_path: OsString = mount_path.join(running_app_filename).into();
398        mounted_app_path.push("/");
399
400        let mut dmg_file = File::create(&dmg_path).await?;
401
402        let (installation_id, release_channel, telemetry) = cx.update(|cx| {
403            let installation_id = Client::global(cx).telemetry().installation_id();
404            let release_channel = ReleaseChannel::try_global(cx)
405                .map(|release_channel| release_channel.display_name());
406            let telemetry = TelemetrySettings::get_global(cx).metrics;
407
408            (installation_id, release_channel, telemetry)
409        })?;
410
411        let request_body = AsyncBody::from(serde_json::to_string(&UpdateRequestBody {
412            installation_id,
413            release_channel,
414            telemetry,
415        })?);
416
417        let mut response = client.get(&release.url, request_body, true).await?;
418        smol::io::copy(response.body_mut(), &mut dmg_file).await?;
419        log::info!("downloaded update. path:{:?}", dmg_path);
420
421        this.update(&mut cx, |this, cx| {
422            this.status = AutoUpdateStatus::Installing;
423            cx.notify();
424        })?;
425
426        let output = Command::new("hdiutil")
427            .args(&["attach", "-nobrowse"])
428            .arg(&dmg_path)
429            .arg("-mountroot")
430            .arg(&temp_dir.path())
431            .output()
432            .await?;
433        if !output.status.success() {
434            Err(anyhow!(
435                "failed to mount: {:?}",
436                String::from_utf8_lossy(&output.stderr)
437            ))?;
438        }
439
440        let output = Command::new("rsync")
441            .args(&["-av", "--delete"])
442            .arg(&mounted_app_path)
443            .arg(&running_app_path)
444            .output()
445            .await?;
446        if !output.status.success() {
447            Err(anyhow!(
448                "failed to copy app: {:?}",
449                String::from_utf8_lossy(&output.stderr)
450            ))?;
451        }
452
453        let output = Command::new("hdiutil")
454            .args(&["detach"])
455            .arg(&mount_path)
456            .output()
457            .await?;
458        if !output.status.success() {
459            Err(anyhow!(
460                "failed to unmount: {:?}",
461                String::from_utf8_lossy(&output.stderr)
462            ))?;
463        }
464
465        this.update(&mut cx, |this, cx| {
466            this.set_should_show_update_notification(true, cx)
467                .detach_and_log_err(cx);
468            this.status = AutoUpdateStatus::Updated;
469            cx.notify();
470        })?;
471        Ok(())
472    }
473
474    fn set_should_show_update_notification(
475        &self,
476        should_show: bool,
477        cx: &AppContext,
478    ) -> Task<Result<()>> {
479        cx.background_executor().spawn(async move {
480            if should_show {
481                KEY_VALUE_STORE
482                    .write_kvp(
483                        SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string(),
484                        "".to_string(),
485                    )
486                    .await?;
487            } else {
488                KEY_VALUE_STORE
489                    .delete_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY.to_string())
490                    .await?;
491            }
492            Ok(())
493        })
494    }
495
496    fn should_show_update_notification(&self, cx: &AppContext) -> Task<Result<bool>> {
497        cx.background_executor().spawn(async move {
498            Ok(KEY_VALUE_STORE
499                .read_kvp(SHOULD_SHOW_UPDATE_NOTIFICATION_KEY)?
500                .is_some())
501        })
502    }
503}