Skip to content

Visual Studio Code, rebuilt in Rust

Rust
17.9 KB
Raw Blame
//! workbench/contrib/update (update.ts `UpdateContribution` and `ProductContribution`, update.contribution.ts) over
//! the app's update service (`crate::update`): the update commands, the Manage menu's update items (menus.rs, group
//! `7_update`) and badge, "There are currently no updates available." after an explicit check, and the release
//! notes after an update. The title bar's entry, which shows an explicit check's error, is update_title_bar.rs.

use gpui::{Context, PromptLevel, Window};

use super::Workbench;
use super::activity::Badge;
use super::lifecycle::quit_all_windows;
use crate::commands::Outcome;
use crate::notifications::Severity;
use crate::update::State;

impl Workbench {
    pub fn register_update_actions(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let service = crate::update::service(cx);
        self.update_state = service.read(cx).state().clone();
        self.update_title_bar_state_changed(window, cx);
        cx.subscribe_in(&service, window, |workbench, _, state, window, cx| workbench.update_state_changed(state, window, cx)).detach();
        self.start_unattended_restart(window, cx);
        for id in ["update.check", "update.checkForUpdate"] {
            self.commands.register(id, |_, _, _, cx| {
                crate::update::service(cx).update(cx, |service, cx| service.check_for_updates(true, cx));
                Outcome::done()
            });
        }
        self.commands.register("update.downloadNow", |_, _, _, cx| {
            crate::update::service(cx).update(cx, |service, cx| service.download_update(true, cx));
            Outcome::done()
        });
        // The disabled menu items' commands, and applyUpdate, which does nothing on macOS.
        for id in ["update.checking", "update.downloading", "update.install", "update.installUpdate"] {
            self.commands.register(id, |_, _, _, _| Outcome::done());
        }
        // update.ts: a stable build only; the menu item is menus.rs'.
        if crate::product::is_stable() {
            self.commands.register("update.showUpdateReleaseNotes", |workbench, _, window, cx| {
                let State::Ready { update, .. } = &workbench.update_state else { return Outcome::done() };
                let version = update.product_version.clone();
                if version.is_empty() {
                    return Outcome::done();
                }
                // `showReleaseNotes`: the notes editor, else the release notes in the browser, as ShowCurrentReleaseNotesAction.
                workbench.execute_command("update.showCurrentReleaseNotes", vec![version.into()], window, cx)
            });
        }
        for id in ["update.restart", "update.restartToUpdate"] {
            self.commands.register(id, |_, _, window, cx| {
                quit_and_install(window, cx);
                Outcome::done()
            });
        }
    }

    /// Hands `update.mode` and `update.releaseChannel` to the service on every render, as `onDidChangeConfiguration`
    /// reconfigures upstream's; the service ignores an unchanged mode.
    pub(super) fn sync_update_settings(&mut self, cx: &mut Context<Self>) {
        let mode = self.setting("update.mode");
        let channel = self.setting("update.releaseChannel");
        let service = crate::update::service(cx);
        service.update(cx, |service, cx| service.reconfigure(mode.as_str().unwrap_or("default"), channel.as_str().unwrap_or("latest"), cx));
    }

    /// `onUpdateStateChange`, then the title bar entry's `onStateChange`.
    pub(super) fn update_state_changed(&mut self, state: &State, window: &mut Window, cx: &mut Context<Self>) {
        self.update_state = state.clone();
        // Shown by the window that had the focus last.
        if let State::Idle { error: None, not_available: true } = state
            && window.is_window_active()
        {
            drop(crate::dialog::show_message_box(window, crate::dialog::InTests::Refuse, PromptLevel::Info, "There are currently no updates available.", None, &["OK"], None, cx));
        }
        self.update_title_bar_state_changed(window, cx);
        cx.notify();
    }

    /// `updateBadge` on the Manage item: 1 while an update waits, a progress badge while checking or downloading;
    /// its description joins the item's hover title. `UpdateGlobalActivityBadgeVisibleContext`: none while the title
    /// bar entry shows beside the activity bar on top (macOS menus are native, so the menu bar counts as visible).
    pub(super) fn update_badge(&self) -> Option<(Badge, String)> {
        if self.update_title_bar_entry_visible() && self.setting("workbench.activityBar.location") == "top" {
            return None;
        }
        let name = crate::product::get("nameShort").as_str().unwrap_or("VSRustium");
        match &self.update_state {
            State::AvailableForDownload { .. } | State::Downloaded { .. } | State::Ready { .. } => Some((Badge::Number(1), format!("New {name} update available."))),
            State::CheckingForUpdates { .. } => Some((Badge::Progress, format!("Checking for {name} updates..."))),
            State::Downloading { .. } => Some((Badge::Progress, format!("Downloading {name} update..."))),
            _ => None,
        }
    }

    /// `ProductContribution`: after an update to a new major or minor version, with `update.showReleaseNotes` on,
    /// `update.showPostInstallInfo` off and no `--skip-release-notes`, the release notes editor; notes that cannot be
    /// shown become a prompt that opens product.json `releaseNotesUrl`.
    pub(crate) fn show_release_notes_after_update(&mut self, skip: bool, window: &mut Window, cx: &mut Context<Self>) {
        let current = crate::product::display_version();
        let url = crate::product::get("releaseNotesUrl").as_str().filter(|_| !skip);
        self.offer_release_notes(&current, url, window, cx);
    }

    fn offer_release_notes(&mut self, current: &str, url: Option<&str>, window: &mut Window, cx: &mut Context<Self>) {
        const KEY: &str = "releaseNotes/lastVersion";
        let last = self.application_storage.lock().unwrap().get(KEY).map(str::to_owned);
        self.application_storage.lock().unwrap().set(KEY, current.to_owned());
        let (Some(last), Some(url)) = (last, url) else { return };
        let wanted = self.setting("update.showReleaseNotes") == true && self.setting("update.showPostInstallInfo") != true;
        if !wanted || !is_major_minor_update(&last, &current) {
            return;
        }
        let shown = self.show_release_notes(url, current.to_owned(), window, cx);
        let (current, url) = (current.to_owned(), url.to_owned());
        cx.spawn(async move |workbench, cx| {
            if shown.await.is_ok() {
                return;
            }
            let Ok(reply) = workbench.update(cx, |workbench, cx| {
                let message = format!("Welcome to {} v{current}! Would you like to read the Release Notes?", crate::product::name_long());
                let reply = workbench.prompt_notification(Severity::Info, message, &["Release Notes"]);
                cx.notify();
                reply
            }) else {
                return;
            };
            if let Ok(Ok(choice)) = reply.await
                && choice == 0
            {
                let _ = cx.update(|cx| cx.open_url(&url));
            }
        })
        .detach();
    }
}

/// `quitAndInstall`: Restarting, then every window's shutdown; a veto puts Ready back. The helper starts when the
/// app quits (`UpdateService::install_on_quit`).
pub(super) fn quit_and_install(window: &mut Window, cx: &mut Context<Workbench>) {
    let service = crate::update::service(cx);
    if !service.update(cx, |service, cx| service.begin_restart(cx)) {
        return;
    }
    cx.spawn_in(window, async move |_, cx| {
        if !quit_all_windows(cx).await {
            let _ = service.update(cx, |service, cx| service.cancel_restart(cx));
        }
    })
    .detach();
}

/// update.ts `isMajorMinorUpdate` over updateUtils.ts `tryParseVersion` (`major.minor.patch` at the start).
pub(super) fn is_major_minor_update(before: &str, after: &str) -> bool {
    let parse = |version: &str| -> Option<(u64, u64)> {
        let mut parts = version.split(['.', '-']);
        let major = parts.next()?.parse().ok()?;
        let minor = parts.next()?.parse().ok()?;
        parts.next()?.parse::<u64>().ok()?;
        Some((major, minor))
    };
    let (Some(before), Some(after)) = (parse(before), parse(after)) else { return false };
    before.0 < after.0 || before.1 < after.1
}

#[cfg(test)]
mod tests {
    use std::path::Path;
    use std::sync::{Arc, Mutex};

    use gpui::{TestAppContext, VisualTestContext};

    use super::*;
    use crate::menus::{MenuAction, MenuId, menu_actions};
    use crate::update::Update;

    fn workbench(cx: &mut TestAppContext) -> (gpui::Entity<Workbench>, &mut VisualTestContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
        let dir = std::env::temp_dir().join(format!("code-gpui-update-{}-{:?}", std::process::id(), std::thread::current().id()));
        std::fs::create_dir_all(dir.join("User")).unwrap();
        let settings = Arc::new(Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None)));
        let host = crate::host_sync::HostSync::new(std::sync::mpsc::channel().0);
        let shared_storage = Arc::new(Mutex::new(storage::Storage::in_memory()));
        cx.update(|cx| cx.set_global(crate::AppState { args: vec!["vsrustium".into()], runtime: exthost::Runtime::Bun, user_data: dir.clone(), app_root: app_root.clone(), builtins: Vec::new(), user_extensions_folder: dir.join("extensions"), shared_storage }));
        let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), settings, host, cx));
        cx.run_until_parked();
        (workbench, cx)
    }

    fn update_titles(workbench: &Workbench, window: &Window) -> Vec<String> {
        let actions = menu_actions(&workbench.menus, MenuId::GlobalActivity, &workbench.key_context(window));
        let titles = actions.into_iter().filter_map(|action| match action {
            MenuAction::Command { id, title, enabled, .. } if id.starts_with("update.") => Some(format!("{title}{}", if enabled { "" } else { " (disabled)" })),
            _ => None,
        });
        titles.collect()
    }

    #[gpui::test]
    fn the_update_state_picks_the_manage_menu_item_and_badge(cx: &mut TestAppContext) {
        let (workbench, cx) = workbench(cx);
        let update = Update { version: "bbbb".into(), product_version: "1.148.0".into(), timestamp: 2, url: "https://example.com/a.zip".into(), sha256hash: "ab".repeat(32) };
        workbench.update_in(cx, |workbench, window, cx| {
            let name = crate::product::get("nameShort").as_str().unwrap_or("VSRustium");
            let steps = [
                (State::Idle { error: None, not_available: false }, "Check for Updates...", None),
                (State::CheckingForUpdates { explicit: true }, "Checking for Updates... (disabled)", Some((Badge::Progress, format!("Checking for {name} updates...")))),
                (State::AvailableForDownload { update: update.clone() }, "Download Update (1)", Some((Badge::Number(1), format!("New {name} update available.")))),
                (State::Downloading { update: update.clone(), explicit: false, downloaded_bytes: 1, total_bytes: Some(2), started_at: std::time::Instant::now() }, "Downloading Update... (disabled)", Some((Badge::Progress, format!("Downloading {name} update...")))),
                (State::Ready { update: update.clone(), app: "/tmp/VSRustium.app".into() }, "Restart to Update (1)", Some((Badge::Number(1), format!("New {name} update available.")))),
            ];
            for (state, title, badge) in steps {
                workbench.update_state_changed(&state, window, cx);
                assert_eq!(update_titles(workbench, window), [title], "{state:?}");
                assert_eq!(workbench.update_badge(), badge);
            }
            assert_eq!(workbench.manage_activity_title(), format!("Manage - New {name} update available."));
            workbench.update_state_changed(&State::Disabled(crate::update::DisablementReason::NotBuilt), window, cx);
            assert!(update_titles(workbench, window).is_empty());
            assert_eq!(workbench.manage_activity_title(), "Manage");
        });
    }

    #[gpui::test]
    fn a_stable_build_shows_the_release_notes_of_a_ready_minor_update(cx: &mut TestAppContext) {
        let update = |product_version: &str| Update { version: "bbbb".into(), product_version: product_version.into(), timestamp: 2, url: "https://example.com/a.zip".into(), sha256hash: "ab".repeat(32) };
        let ready = |product_version: &str| State::Ready { update: update(product_version), app: "/tmp/VSRustium.app".into() };
        // The checkout's product.json version, 1.148.x.
        crate::product::load(Path::new(env!("VSCODE_SRC")), false);
        for quality in [Some("stable"), Some("insider"), None] {
            let _quality = crate::product::test_quality::set(quality);
            let (workbench, cx) = workbench(cx);
            let shown = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
            workbench.update_in(cx, |workbench, window, cx| {
                workbench.register_update_actions(window, cx);
                let spy = shown.clone();
                workbench.commands.register("update.showCurrentReleaseNotes", move |_, args, _, _| {
                    spy.borrow_mut().push(args);
                    Outcome::done()
                });
                let stable = quality == Some("stable");
                let item = |workbench: &Workbench, window: &Window| update_titles(workbench, window).contains(&"Show Update Release Notes".to_owned());
                workbench.update_state_changed(&ready("1.149.0"), window, cx);
                assert_eq!(item(workbench, window), stable, "{quality:?}");
                assert_eq!(workbench.commands.get("update.showUpdateReleaseNotes").is_some(), stable, "{quality:?}");
                if stable {
                    workbench.execute_command("update.showUpdateReleaseNotes", Vec::new(), window, cx);
                    assert_eq!(*shown.borrow(), [vec![serde_json::json!("1.149.0")]]);
                    workbench.update_state_changed(&ready("1.148.9"), window, cx);
                    assert!(!item(workbench, window), "a patch update has no item");
                    workbench.update_state_changed(&State::Idle { error: None, not_available: false }, window, cx);
                    workbench.execute_command("update.showUpdateReleaseNotes", Vec::new(), window, cx);
                    assert_eq!(shown.borrow().len(), 1, "only a ready update has notes to show");
                }
            });
        }
    }

    #[gpui::test]
    fn an_explicit_checks_error_shows_in_the_title_bar_tooltip(cx: &mut TestAppContext) {
        let (workbench, cx) = workbench(cx);
        cx.update(|window, _| window.activate_window());
        cx.run_until_parked();
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.update_state_changed(&State::Idle { error: Some("boom".into()), not_available: false }, window, cx);
            assert!(workbench.notifications.model.items.is_empty());
            assert!(workbench.update_title_bar_entry_visible());
            assert!(workbench.hovers.sticky_shown(super::super::update_title_bar::TOOLTIP));
            workbench.dismiss_hover(cx);
            assert!(!workbench.update_title_bar_entry_visible(), "a dismissed error hides the entry");
            let update = crate::update::Update { version: "b".into(), product_version: "1.148.0".into(), timestamp: 2, url: String::new(), sha256hash: String::new() };
            workbench.update_state_changed(&State::Downloaded { update }, window, cx);
            assert!(workbench.update_title_bar_entry_visible());
        });
    }

    #[gpui::test]
    fn release_notes_are_offered_once_after_a_minor_update(cx: &mut TestAppContext) {
        let (workbench, cx) = workbench(cx);
        // Nothing listens on port 9: the notes cannot be fetched, so the prompt stands in for the editor.
        let url = Some("http://127.0.0.1:9/releases");
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.offer_release_notes("1.147.0", url, window, cx);
            assert!(workbench.notifications.model.items.is_empty(), "the first start only stores its version");
            workbench.offer_release_notes("1.148.0", url, window, cx);
            workbench.offer_release_notes("1.148.0", url, window, cx);
        });
        cx.run_until_parked();
        workbench.update_in(cx, |workbench, window, cx| {
            let messages: Vec<&str> = workbench.notifications.model.items.iter().map(|item| item.message.raw.as_str()).collect();
            assert_eq!(messages, [format!("Welcome to {} v1.148.0! Would you like to read the Release Notes?", crate::product::name_long())]);
            workbench.offer_release_notes("1.148.1", url, window, cx);
        });
        cx.run_until_parked();
        workbench.read_with(cx, |workbench, _| assert_eq!(workbench.notifications.model.items.len(), 1, "a patch update shows nothing"));
    }

    #[test]
    fn release_notes_follow_a_major_or_minor_update_only() {
        assert!(is_major_minor_update("1.147.0", "1.148.0"));
        assert!(is_major_minor_update("1.147.3", "2.0.0"));
        assert!(!is_major_minor_update("1.147.0", "1.147.1"));
        assert!(!is_major_minor_update("1.148.0.1", "1.148.0.2-insider"));
        assert!(is_major_minor_update("1.148.0.9", "1.149.0.1"));
        assert!(!is_major_minor_update("1.147.0", "1.147.0"));
        assert!(!is_major_minor_update("", "1.148.0"));
        // isMajorMinorUpdate compares each part on its own, as upstream does.
        assert!(is_major_minor_update("2.5.0", "1.6.0"));
    }
}