Visual Studio Code, rebuilt in Rust
Rust
//! extensionBisect.ts: `ExtensionBisectService` with its state in the application storage across reloads, the
//! `ExtensionBisectUi` prompt of a window that starts while a bisect runs, and the Start, Continue and Stop
//! Extension Bisect commands.
use gpui::{Context, PromptLevel, Window};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use storage::Storage;
use super::Workbench;
use crate::commands::Outcome;
use crate::dialog::{self, InTests};
use crate::extension_enablement::{Enablement, EnablementState, Identifier};
use crate::notifications::{Action, Notification, Priority, Run, Severity};
const STORAGE_KEY: &str = "extensionBisectState";
const RELOAD_WINDOW: &str = "workbench.action.reloadWindow";
/// `BisectState`: the user extensions at the start; the ones from `mid` up to `high` are disabled.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct BisectState {
pub extensions: Vec<String>,
pub low: usize,
pub high: usize,
pub mid: usize,
}
impl BisectState {
fn new(extensions: Vec<String>, low: usize, high: usize) -> BisectState {
BisectState { extensions, low, high, mid: (low + high) / 2 }
}
/// `BisectState.fromJSON` of the stored state; a state that does not parse is no bisect.
pub fn read(storage: &Storage) -> Option<BisectState> {
serde_json::from_str(storage.get(STORAGE_KEY)?).ok()
}
/// `isDisabledByBisect` for an extension that is not under development.
pub fn is_disabled(&self, id: &str) -> bool {
self.extensions.iter().enumerate().any(|(index, extension)| extension == id && index >= self.mid && index < self.high)
}
/// `disabledCount`.
fn disabled_count(&self) -> usize {
self.high.saturating_sub(self.mid)
}
}
/// `start`: every extension disabled for the first round.
fn start(storage: &mut Storage, extensions: Vec<String>) {
let high = extensions.len();
store(storage, &BisectState { extensions, low: 0, high, mid: 0 });
}
/// `next`: the found extension and whether the problem was still seen, once the search ends; else the next half is
/// stored. An empty id with `bad` means the problem stays with every extension disabled.
fn next(storage: &mut Storage, state: &BisectState, seeing_bad: bool) -> Option<(String, bool)> {
if seeing_bad && state.mid == 0 && state.high == state.extensions.len() {
return Some((String::new(), true));
}
if state.low + 1 == state.high {
reset(storage);
return Some((state.extensions.get(state.low).cloned().unwrap_or_default(), seeing_bad));
}
// The second half is disabled, so a problem still seen is in the first half.
let next = match seeing_bad {
true => BisectState::new(state.extensions.clone(), state.low, state.mid),
false => BisectState::new(state.extensions.clone(), state.mid, state.high),
};
store(storage, &next);
None
}
fn reset(storage: &mut Storage) {
storage.delete(STORAGE_KEY);
}
fn store(storage: &mut Storage, state: &BisectState) {
storage.set(STORAGE_KEY, serde_json::to_string(state).expect("serializable"));
}
/// The detail's reload estimate, `2 + Math.log2(count) | 0` (no extensions: `-Infinity | 0`, 0).
fn reload_estimate(count: usize) -> i64 {
let estimate = 2. + (count as f64).log2();
if estimate.is_finite() { estimate as i64 } else { 0 }
}
fn disabled_message(count: usize) -> String {
match count {
1 => "Extension Bisect is active and has disabled 1 extension. Check if you can still reproduce the problem and proceed by selecting from these options.".into(),
count => format!("Extension Bisect is active and has disabled {count} extensions. Check if you can still reproduce the problem and proceed by selecting from these options."),
}
}
impl Workbench {
pub(super) fn register_extension_bisect_commands(&mut self) {
self.commands.register("extension.bisect.start", |workbench, _, window, cx| workbench.start_extension_bisect(window, cx));
self.commands.register("extension.bisect.next", |workbench, args, window, cx| {
workbench.continue_extension_bisect(args.first().and_then(Value::as_bool), window, cx);
Outcome::done()
});
self.commands.register("extension.bisect.stop", |workbench, _, window, cx| {
reset(&mut workbench.application_storage.lock().unwrap());
workbench.execute_command(RELOAD_WINDOW, Vec::new(), window, cx)
});
}
/// `ExtensionBisectUi`: a window that starts while a bisect runs sets `isExtensionBisectActive` and asks how
/// the problem looks now.
pub(super) fn show_extension_bisect_prompt(&mut self) {
let Some(state) = &self.extensions_viewlet.bisect else { return };
let disabled: Vec<(&str, bool)> = state.extensions.iter().map(|id| (id.as_str(), state.is_disabled(id))).collect();
eprintln!("[extensions] extension BISECT active {disabled:?}");
let message = disabled_message(state.disabled_count());
self.context_keys.insert("isExtensionBisectActive".into(), json!(true));
let action = |id: &str, label: &str, command: &str, args: Vec<Value>| Action { id: id.into(), label: label.into(), run: Run::Command(command.into(), args) };
let primary = vec![
action("good", "I can't reproduce", "extension.bisect.next", vec![json!(false)]),
action("bad", "I can reproduce", "extension.bisect.next", vec![json!(true)]),
action("stop", "Stop Bisect", "extension.bisect.stop", Vec::new()),
];
self.notify(Notification { sticky: true, priority: Priority::Urgent, primary, ..Notification::new(Severity::Info, message) });
}
/// `extension.bisect.start`: the enabled user extensions, after a confirmation, then a reload.
fn start_extension_bisect(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
if self.extensions_viewlet.bisect.is_some() {
return Outcome::error("invalid state");
}
let extensions: Vec<String> = self
.local_extensions()
.into_iter()
.filter(|extension| extension.enablement.is_enabled())
.filter_map(|extension| extension.local)
.filter(|local| local.description["isBuiltin"] != true)
.map(|local| local.id)
.collect();
let detail = format!(
"Extension Bisect will use binary search to find an extension that causes a problem. During the process the window reloads repeatedly (~{} times). Each time you must confirm if you are still seeing problems.",
reload_estimate(extensions.len())
);
let answer = dialog::show_message_box(window, InTests::Confirm, PromptLevel::Info, "Extension Bisect", Some(&detail), &["Start Extension Bisect", "Cancel"], None, cx);
cx.spawn_in(window, async move |workbench, cx| {
if !matches!(answer.await, Ok((0, _))) {
return;
}
let _ = workbench.update_in(cx, |workbench, window, cx| {
start(&mut workbench.application_storage.lock().unwrap(), extensions);
drop(workbench.execute_command(RELOAD_WINDOW, Vec::new(), window, cx));
});
})
.detach();
Outcome::done()
}
/// `extension.bisect.next`: without an answer it asks first; Stop Bisect ends the bisect, Cancel Bisect leaves it.
fn continue_extension_bisect(&mut self, seeing_bad: Option<bool>, window: &mut Window, cx: &mut Context<Self>) {
let Some(state) = self.extensions_viewlet.bisect.clone() else { return };
if let Some(seeing_bad) = seeing_bad {
return self.bisect_step(&state, Some(seeing_bad), window, cx);
}
let buttons = ["I can't reproduce", "I can reproduce", "Stop Bisect", "Cancel Bisect"];
let detail = format!("Extension Bisect is active and has disabled {} extensions. Check if you can still reproduce the problem and proceed by selecting from these options.", state.disabled_count());
let answer = dialog::show_message_box(window, InTests::Refuse, PromptLevel::Info, "Extension Bisect", Some(&detail), &buttons, None, cx);
cx.spawn_in(window, async move |workbench, cx| {
let seeing_bad = match answer.await {
Ok((0, _)) => Some(false),
Ok((1, _)) => Some(true),
Ok((2, _)) => None,
_ => return,
};
let _ = workbench.update_in(cx, |workbench, window, cx| workbench.bisect_step(&state, seeing_bad, window, cx));
})
.detach();
}
/// The rest of `extension.bisect.next`: `None` stops the bisect.
fn bisect_step(&mut self, state: &BisectState, seeing_bad: Option<bool>, window: &mut Window, cx: &mut Context<Self>) {
let storage = self.application_storage.clone();
let done = seeing_bad.and_then(|seeing_bad| next(&mut storage.lock().unwrap(), state, seeing_bad));
let Some((id, bad)) = done else {
if seeing_bad.is_none() {
reset(&mut storage.lock().unwrap());
}
drop(self.execute_command(RELOAD_WINDOW, Vec::new(), window, cx));
return;
};
// The reference's "Report Issue & Continue" opens the issue reporter, removed by decision: Continue alone.
let answer = match bad {
true => {
let detail = format!("Extension Bisect is done but no extension has been identified. This might be a problem with {}.", crate::product::name_short());
dialog::show_message_box(window, InTests::Refuse, PromptLevel::Info, "Extension Bisect", Some(&detail), &["OK"], None, cx)
}
false => {
let detail = format!("Extension Bisect is done and has identified {id} as the extension causing the problem.");
dialog::show_message_box_with_checkbox(window, InTests::Confirm, PromptLevel::Info, "Extension Bisect", Some(&detail), &["Continue"], Some(("Keep this extension disabled", true)), cx)
}
};
cx.spawn_in(window, async move |workbench, cx| {
let keep_disabled = matches!(answer.await, Ok((_, true)));
let _ = workbench.update_in(cx, |workbench, window, cx| {
if keep_disabled {
// `IGlobalExtensionEnablementService.disableExtension`.
let mut profile = workbench.profile_storage.lock().unwrap();
Enablement { profile: &mut profile, workspace: None }.set_user_state(&Identifier { id, uuid: None }, EnablementState::DisabledGlobally);
}
reset(&mut storage.lock().unwrap());
drop(workbench.execute_command(RELOAD_WINDOW, Vec::new(), window, cx));
});
})
.detach();
}
}
#[cfg(test)]
mod tests;