Visual Studio Code, rebuilt in Rust
Rust
//! debugTaskRunner.ts: the tasks around a debug session (`preLaunchTask`, `postDebugTask`), the prompts after a
//! failed task and the notification for a slow one.
use std::time::Duration;
use futures::channel::oneshot;
use futures::{FutureExt, future::Fuse, select_biased};
use gpui::{AsyncWindowContext, PromptLevel, WeakEntity};
use serde_json::{Map, Value, json};
use super::Workbench;
use super::debug_service::on_workbench;
use super::problems_view::MARKERS_VIEW_ID;
use super::task_service::{DebugTaskWait, find_task};
use crate::commands::Outcome;
use crate::markers::{ERROR, ReadOptions};
use crate::notifications::{Action, Notification, Progress, Run, Severity};
const DEBUG_TASK_ERROR_CHOICE_KEY: &str = "debug.taskerrorchoice";
const DEBUG_ANYWAY_LABEL: &str = "Debug Anyway";
const ABORT_LABEL: &str = "Abort";
/// `IRunnerTaskSummary`.
#[derive(Debug, PartialEq)]
pub(super) struct TaskSummary {
pub exit_code: Option<i32>,
pub cancelled: bool,
}
const CANCELLED: TaskSummary = TaskSummary { exit_code: None, cancelled: true };
/// Which tasks a start runs before the launch.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum DebugTasks {
PreLaunch,
/// debugService.ts `restartSession`'s `runTasks`.
Restart,
/// An automatic restart (`restartData`) runs none.
None,
}
/// The tasks of `tasks` from the configuration: whether the session may start.
pub(super) async fn run_debug_tasks(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, tasks: DebugTasks, config: &Value) -> Result<bool, String> {
match tasks {
DebugTasks::None => Ok(true),
DebugTasks::PreLaunch => run_task_and_check_errors(this, cx, &config["preLaunchTask"]).await,
DebugTasks::Restart => {
run_task(this, cx, &config["preRestartTask"]).await?;
run_task(this, cx, &config["postDebugTask"]).await?;
if !run_task_and_check_errors(this, cx, &config["preLaunchTask"]).await? {
return Ok(false);
}
run_task_and_check_errors(this, cx, &config["postRestartTask"]).await
}
}
}
/// `runTaskAndCheckErrors`: whether the session may start (`TaskRunResult.Success`).
pub(super) async fn run_task_and_check_errors(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, task_id: &Value) -> Result<bool, String> {
if no_task(task_id) {
return Ok(true);
}
let summary = match run_task(this, cx, task_id).await {
Ok(summary) => summary,
Err(message) => return task_error_choice(this, cx, message).await,
};
if summary.as_ref().is_some_and(|summary| summary.exit_code.is_none() || summary.cancelled) {
return Ok(false);
}
let (error_count, on_task_errors) = on_workbench(this, cx, |workbench, _, _| {
let errors = workbench.diagnostics.service.read(ReadOptions { severities: Some(ERROR), take: Some(2), ..Default::default() }).len();
(errors, workbench.setting("debug.onTaskErrors"))
})?;
let exit_code = summary.as_ref().and_then(|summary| summary.exit_code);
let failure_exit_code = summary.is_some() && exit_code != Some(0);
if exit_code == Some(0) || on_task_errors == "debugAnyway" || (error_count == 0 && !failure_exit_code) {
return Ok(true);
}
if on_task_errors == "showErrors" {
on_workbench(this, cx, |workbench, _, cx| workbench.open_panel_view(MARKERS_VIEW_ID, cx))?;
return Ok(false);
}
if on_task_errors == "abort" {
return Ok(false);
}
let label = task_id.as_str().or(task_id["name"].as_str()).unwrap_or_default();
let message = match (error_count, exit_code) {
(2.., _) => format!("Errors exist after running preLaunchTask '{label}'."),
(1, _) => format!("Error exists after running preLaunchTask '{label}'."),
(_, Some(code)) => format!("The preLaunchTask '{label}' terminated with exit code {code}."),
_ => format!("The preLaunchTask '{label}' terminated."),
};
let answer = on_workbench(this, cx, |_, window, cx| {
crate::dialog::show_message_box(window, crate::dialog::InTests::Refuse, PromptLevel::Warning, &message, None, &[DEBUG_ANYWAY_LABEL, "Show Errors", ABORT_LABEL], Some("Remember my choice in user settings"), cx)
})?;
let (choice, remember) = answer.await.unwrap_or((2, false));
on_workbench(this, cx, |workbench, _, cx| {
if remember {
let value = ["debugAnyway", "showErrors", "abort"][choice];
workbench.update_setting("debug.onTaskErrors", json!(value));
}
if choice == 1 {
workbench.open_panel_view(MARKERS_VIEW_ID, cx);
}
})?;
Ok(choice == 0)
}
/// The `catch` of `runTaskAndCheckErrors`: the choice remembered for this message, else Debug Anyway, Configure Task
/// or Cancel.
async fn task_error_choice(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, message: String) -> Result<bool, String> {
let mut choices: Map<String, Value> = on_workbench(this, cx, |workbench, _, _| {
workbench.workspace_storage.lock().unwrap().get(DEBUG_TASK_ERROR_CHOICE_KEY).and_then(|raw| serde_json::from_str(raw).ok()).unwrap_or_default()
})?;
let choice = match choices.get(&message).and_then(Value::as_u64) {
Some(choice) => choice as usize,
None => {
let answer = on_workbench(this, cx, |_, window, cx| {
crate::dialog::show_message_box(window, crate::dialog::InTests::Refuse, PromptLevel::Critical, &message, None, &[DEBUG_ANYWAY_LABEL, "Configure Task", "Cancel"], Some("Remember my choice for this task"), cx)
})?;
let (choice, remember) = answer.await.unwrap_or((2, false));
if remember {
choices.insert(message, json!(choice));
let stored = Value::Object(choices).to_string();
on_workbench(this, cx, |workbench, _, _| workbench.workspace_storage.lock().unwrap().set(DEBUG_TASK_ERROR_CHOICE_KEY, stored))?;
}
choice
}
};
if choice == 1 {
on_workbench(this, cx, |workbench, window, cx| workbench.run_configure_tasks(window, cx))?;
}
Ok(choice == 0)
}
/// `runTask`: the summary of the task's run, `None` with no task or when it did not need to run; an error for a
/// task that cannot be found or a background task that never reports its start.
pub(super) async fn run_task(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, task_id: &Value) -> Result<Option<TaskSummary>, String> {
if no_task(task_id) {
return Ok(None);
}
let fetched = on_workbench(this, cx, |workbench, _, cx| workbench.fetch_tasks(None, cx))?;
let tasks = fetched.await.unwrap_or_default();
let Some(task) = find_task(&tasks, task_id) else {
return Err(match task_id.as_str() {
Some(name) => format!("Could not find the task '{name}'."),
None => "Could not find the specified task.".into(),
});
};
// `ITaskService.run` asks for workspace trust first and, refused, resolves with no summary.
let trust = on_workbench(this, cx, |workbench, window, cx| workbench.with_task_trust(window, cx, |_, _, _| Outcome::Ready(Ok(json!(true)))))?;
let trusted = match trust {
Outcome::Ready(answer) => answer == Ok(json!(true)),
Outcome::Pending(answer) => answer.await == Ok(Ok(json!(true))),
};
if !trusted {
return Ok(None);
}
let (wait, mut cancelled) = on_workbench(this, cx, |workbench, window, cx| {
let (cancel, cancelled) = oneshot::channel();
workbench.debug.task_cancels.retain(|cancel| !cancel.is_canceled());
workbench.debug.task_cancels.push(cancel);
(workbench.run_task_for_debug(task.clone(), window, cx), cancelled)
})?;
let mut done = async move {
match wait {
DebugTaskWait::Idle => None,
DebugTaskWait::Exit(ended) => Some(TaskSummary { exit_code: ended.await.ok().flatten(), cancelled: false }),
DebugTaskWait::Inactive(inactive) => match inactive.await {
Ok(false) => None,
Ok(true) => Some(TaskSummary { exit_code: None, cancelled: false }),
// A background task that ended with an exit code and never went inactive: upstream waits on.
Err(_) => std::future::pending().await,
},
}
}
.boxed_local()
.fuse();
let timer = |cx: &AsyncWindowContext, seconds| cx.background_executor().timer(Duration::from_secs(seconds)).fuse();
// The timers start once the task has its input (`AcquiredInput`): until it launched they start again.
let wait_time = if task.is_background { 5 } else { 10 };
let mut not_tracked = timer(cx, wait_time);
let mut slow = timer(cx, 10);
let mut slow_choice: Fuse<oneshot::Receiver<Result<Value, Value>>> = Fuse::terminated();
let mut slow_notification = None;
let terminate = |this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, configure: bool| {
on_workbench(this, cx, |workbench, window, cx| {
workbench.terminate_task(&task, window, cx);
if configure {
workbench.open_task_entry(&task, window, cx);
}
})
};
let result = loop {
select_biased! {
summary = done => break Ok(summary),
_ = cancelled => {
terminate(this, cx, false)?;
break Ok(Some(CANCELLED));
}
_ = not_tracked => match on_workbench(this, cx, |workbench, _, _| workbench.debug_task_started(&task.id))? {
Some(true) => {}
Some(false) => break Err(format!("The task '{}' has not exited and doesn't have a 'problemMatcher' defined. Make sure to define a problem matcher for watch tasks.", task_label(task_id))),
None => not_tracked = timer(cx, wait_time),
},
_ = slow => {
let (launched, hide) = on_workbench(this, cx, |workbench, _, _| (workbench.debug_task_started(&task.id).is_some(), workbench.setting("debug.hideSlowPreLaunchWarning") == true))?;
if !launched {
slow = timer(cx, 10);
} else if !hide {
let can_configure = !super::task_configure::is_contributed(&task);
let (key, choice) = on_workbench(this, cx, |workbench, _, cx| workbench.show_slow_task_notification(&task.name, can_configure, cx))?;
slow_notification = key;
slow_choice = choice.fuse();
}
}
choice = slow_choice => match choice.ok().and_then(Result::ok).and_then(|choice| choice.as_u64()) {
Some(0) => break Ok(Some(TaskSummary { exit_code: Some(0), cancelled: false })),
Some(choice) => {
let can_configure = !super::task_configure::is_contributed(&task);
terminate(this, cx, can_configure && choice == 1)?;
break Ok(Some(CANCELLED));
}
None => {}
},
}
};
if let Some(key) = slow_notification {
on_workbench(this, cx, |workbench, window, cx| {
workbench.notifications.replies.remove(&key);
workbench.close_notification(key, window, cx);
})?;
}
result
}
/// `!taskId`.
fn no_task(task_id: &Value) -> bool {
task_id.is_null() || task_id == ""
}
/// The task's name as the messages show it: the label, or the identifier as JSON.
fn task_label(task_id: &Value) -> String {
match task_id.as_str() {
Some(label) => label.to_owned(),
None => task_id.to_string(),
}
}
impl Workbench {
/// `DebugTaskRunner.cancel`: every task run a debug start waits for ends as cancelled.
pub(super) fn cancel_debug_tasks(&mut self) {
for cancel in self.debug.task_cancels.drain(..) {
let _ = cancel.send(());
}
}
/// "Waiting for preLaunchTask '{0}'...": a notification with progress and Debug Anyway, Configure Task (for a
/// tasks.json task) and Abort; it answers the pressed button's index.
fn show_slow_task_notification(&mut self, name: &str, can_configure: bool, cx: &mut gpui::Context<Self>) -> (Option<u64>, oneshot::Receiver<Result<Value, Value>>) {
let mut buttons = vec![DEBUG_ANYWAY_LABEL, ABORT_LABEL];
if can_configure {
buttons.insert(1, "Configure Task");
}
let mut notification = Notification::new(Severity::Info, format!("Waiting for preLaunchTask '{name}'..."));
notification.primary = buttons.iter().enumerate().map(|(index, label)| Action { id: format!("workbench.notification.choice.{index}"), label: (*label).into(), run: Run::Reply(index as u64) }).collect();
notification.progress = Some(Progress { infinite: true, ..Progress::default() });
let (sender, receiver) = oneshot::channel();
let key = self.notify(notification);
if let Some(key) = key {
self.notifications.replies.insert(key, sender);
}
cx.notify();
(key, receiver)
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use std::sync::mpsc::Receiver;
use gpui::{Entity, TestAppContext, VisualTestContext};
use super::*;
use crate::host_sync::HostMessage;
/// The error a start reaches past the tasks: no adapter is registered for `mock`.
const PAST_THE_TASKS: &str = "Configured debug type 'mock' is not supported.";
fn start_with_pre_launch_task(cx: &mut TestAppContext) -> (Entity<Workbench>, &mut VisualTestContext, Receiver<HostMessage>) {
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 (sender, receiver) = std::sync::mpsc::channel();
// A writable User folder: `debug.onTaskErrors` must reach the settings, or the start prompts.
let user = std::env::temp_dir().join(format!("vsrustium-{}-{}/User", crate::test_name(), std::process::id()));
let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), user, None)));
let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), settings, crate::host_sync::HostSync::new(sender), cx));
workbench.update_in(cx, |workbench, window, cx| {
workbench.tasks.matchers = crate::tasks::problem_matcher::Registry::new(&[]);
workbench.tasks.providers.push((1, "gulp".into()));
let config = json!({ "type": "mock", "request": "launch", "name": "Mock", "preLaunchTask": "gulp: build" });
drop(workbench.start_debugging(None, config, json!({}), DebugTasks::PreLaunch, window, cx));
});
let dto = json!({ "_id": "gulp-build", "name": "build", "definition": { "type": "gulp", "task": "build" }, "source": { "label": "gulp" }, "execution": { "customExecution": "customExecution" }, "problemMatchers": [] });
for _ in 0..4 {
cx.run_until_parked();
for message in receiver.try_iter().filter(|message| message.method == "$provideTasks") {
let _ = message.reply.unwrap().send(Ok(json!({ "tasks": [dto.clone()] })));
}
}
cx.run_until_parked();
(workbench, cx, receiver)
}
fn notifications(workbench: &Entity<Workbench>, cx: &mut VisualTestContext) -> Vec<String> {
workbench.read_with(cx, |workbench, _| workbench.notifications.model.items.iter().map(|item| item.message.text()).collect())
}
fn end_task(workbench: &Entity<Workbench>, cx: &mut VisualTestContext, code: i32) {
workbench.update_in(cx, |workbench, window, cx| {
let task = workbench.running_tasks().pop().expect("the preLaunchTask runs");
let terminal = workbench.task_terminal(&task).unwrap();
workbench.task_process_exited(terminal, Some(code), window, cx);
});
cx.run_until_parked();
}
#[gpui::test]
fn the_session_starts_after_its_pre_launch_task_ends(cx: &mut TestAppContext) {
let (workbench, cx, _host) = start_with_pre_launch_task(cx);
assert!(!notifications(&workbench, cx).contains(&PAST_THE_TASKS.to_owned()), "the start waits for the task");
end_task(&workbench, cx, 0);
assert!(notifications(&workbench, cx).contains(&PAST_THE_TASKS.to_owned()));
}
#[gpui::test]
fn a_failed_pre_launch_task_aborts_the_start_with_on_task_errors_abort(cx: &mut TestAppContext) {
let (workbench, cx, _host) = start_with_pre_launch_task(cx);
workbench.update(cx, |workbench, _| workbench.update_setting("debug.onTaskErrors", json!("abort")));
end_task(&workbench, cx, 3);
assert!(!notifications(&workbench, cx).contains(&PAST_THE_TASKS.to_owned()));
assert!(!workbench.read_with(cx, |workbench, _| workbench.debug.initializing));
}
}