Skip to content

Visual Studio Code, rebuilt in Rust

Rust
58.5 KB
Raw Blame
//! mainThreadTask.ts with abstractTaskService.ts and terminalTaskSystem.ts: tasks from tasks.json and from the
//! extensions' providers, run in feature terminals (shell and process) or extension pseudoterminals (custom
//! executions), their dependencies, and problem matchers feeding the markers.

use std::collections::{BTreeMap, HashMap};
use std::io::Write;
use std::path::{Path, PathBuf};

use exthost::session::ForwardedRequest;
use futures::channel::oneshot;
use futures::future::join_all;
use gpui::{AsyncWindowContext, Context, WeakEntity, Window};
use serde_json::{Value, json};

use super::Workbench;
use super::problems_view::MARKERS_VIEW_ID;
use crate::commands::Outcome;
use crate::tasks::configuration::{Task, USER_TASKS_GROUP_KEY, parse_tasks_json};
use crate::tasks::definitions::{TaskDefinition, definitions};
use crate::tasks::problem_collector::{CollectorEvent, MarkerChange, Markers, ProblemCollector};
use crate::tasks::problem_matcher::{Registry, SEVERITY_ERROR, SEVERITY_INFO, SEVERITY_WARNING};
use crate::terminal::{ShellLaunchConfig, TerminalStatus, format_message_for_terminal};

/// taskTerminalStatus.ts `TASK_TERMINAL_STATUS_ID`; its statuses' severities as `Severity` counts them.
const TASK_STATUS: &str = "task_terminal_status";
/// abstractTaskService.ts `OutputChannelId`.
pub(super) const TASKS_OUTPUT_CHANNEL_ID: &str = "tasks";
const STATUS_INFO: u8 = 1;
const STATUS_WARNING: u8 = 2;
const STATUS_ERROR: u8 = 3;

fn task_status(severity: u8, icon: &'static str, tooltip: &'static str) -> TerminalStatus {
    TerminalStatus { id: TASK_STATUS, severity, icon: Some(icon), tooltip: Some(tooltip) }
}

/// tasks.ts `RevealKind`, `RevealProblemKind` and `PanelKind`, as `presentation` numbers them.
const REVEAL_ALWAYS: u64 = 1;
const REVEAL_SILENT: u64 = 2;
const REVEAL_NEVER: u64 = 3;
const REVEAL_PROBLEMS_ON_PROBLEM: u64 = 2;
const REVEAL_PROBLEMS_ALWAYS: u64 = 3;
const PANEL_SHARED: u64 = 1;
const PANEL_DEDICATED: u64 = 2;
const PANEL_NEW: u64 = 3;

/// What a task terminal does after its process (`waitOnExit`): a message, then any key closes it; no message;
/// or it closes.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum WaitOnExit {
    Message(&'static str),
    Wait,
    Close,
}

/// terminalTaskSystem.ts `getWaitOnExitValue`, with `PresentationOptions.defaults` for what `presentation` leaves out.
fn wait_on_exit(presentation: &Value, is_background: bool) -> WaitOnExit {
    let close = presentation["close"].as_bool();
    let reveal = presentation["reveal"].as_u64().unwrap_or(REVEAL_ALWAYS);
    if close != Some(true) && (reveal != REVEAL_NEVER || !is_background || close == Some(false)) {
        if presentation["panel"].as_u64() == Some(PANEL_NEW) {
            return WaitOnExit::Message("Press any key to close the terminal.");
        }
        if presentation["showReuseMessage"] != false {
            return WaitOnExit::Message("Terminal will be reused by tasks, press any key to close it.");
        }
        return WaitOnExit::Wait;
    }
    match close {
        Some(true) => WaitOnExit::Close,
        _ => WaitOnExit::Wait,
    }
}

#[derive(Default)]
pub struct TaskService {
    /// `$registerTaskProvider`: handle and task type.
    pub(super) providers: Vec<(i64, String)>,
    definitions: Vec<TaskDefinition>,
    pub(super) matchers: Registry,
    /// `UUIDMap`: custom task ids by folder and label, stable across reads.
    uuids: HashMap<(PathBuf, String), String>,
    /// Tasks the host referred to by id (`$executeTask` with a DTO), for `$getTaskExecution`.
    known: HashMap<String, Task>,
    pub(super) active: Vec<ActiveTask>,
    /// The last task a user ran, for `reRunTask`.
    pub(super) last: Option<Task>,
    /// `registerSupportedExecutions`: the `customExecutionSupported`, `shellExecutionSupported` and
    /// `processExecutionSupported` context keys, unset until the host registers them.
    supported_executions: [Option<bool>; 3],
    /// `_terminals`: every task terminal by instance id, oldest first.
    terminals: BTreeMap<u32, TaskTerminal>,
    /// `_idleTaskTerminals`: the terminals of ended `shared` tasks by task key, the last one to end first.
    idle_terminals: Vec<(String, u32)>,
    /// `_sameTaskTerminals`: the terminals of ended `dedicated` tasks by task key.
    same_terminals: HashMap<String, u32>,
    /// debugTaskRunner.ts `inactivePromise` by task id: told `false` when the task goes inactive, `true` when its
    /// process ends without an exit code; dropped when it ends with one.
    inactive_waiters: HashMap<String, Vec<oneshot::Sender<bool>>>,
}

/// `ITerminalData`: the `presentation.group` the terminal was created for and the `waitOnExit` of its last task.
struct TaskTerminal {
    group: Option<String>,
    wait_on_exit: WaitOnExit,
}

impl TaskService {
    /// `_createTerminal`: a `dedicated` task takes its own ended terminal back; a `shared` one its own idle terminal,
    /// else the latest idle one created for the same group.
    fn take_terminal_to_reuse(&mut self, key: &str, panel: u64, group: Option<&str>) -> Option<u32> {
        if panel == PANEL_DEDICATED {
            return self.same_terminals.remove(key);
        }
        if panel != PANEL_SHARED {
            return None;
        }
        let index = self.idle_terminals.iter().position(|(task, _)| task == key).or_else(|| {
            self.idle_terminals.iter().position(|(_, terminal)| self.terminals.get(terminal).is_some_and(|data| data.group.as_deref() == group))
        })?;
        Some(self.idle_terminals.remove(index).1)
    }

    /// The task ended in its terminal, which stays for the next run of `panel`.
    fn keep_terminal(&mut self, key: String, terminal: u32, panel: u64) {
        match panel {
            PANEL_DEDICATED => _ = self.same_terminals.insert(key, terminal),
            PANEL_SHARED => {
                self.idle_terminals.retain(|(task, _)| *task != key);
                self.idle_terminals.insert(0, (key, terminal));
            }
            _ => {}
        }
    }

    /// `_deleteTaskAndTerminal`: the terminal went.
    fn forget_terminal(&mut self, terminal: u32) {
        self.terminals.remove(&terminal);
        self.same_terminals.retain(|_, kept| *kept != terminal);
        self.idle_terminals.retain(|(_, kept)| *kept != terminal);
    }
}

pub(super) struct ActiveTask {
    task: Task,
    /// `getMapKey`: the id and the instance number, the count of runs of the task when it started.
    key: String,
    terminal: u32,
    /// `startId` of a custom execution (`reserveCustomExecution`).
    start_id: Option<String>,
    collector: Option<ProblemCollector>,
    /// Who waits for the task's end (`run` and the tasks depending on it), with its exit code.
    waiters: Vec<oneshot::Sender<Option<i32>>>,
    /// `_busyTasks`: a run is going, from its start (a background task from `BackgroundProcessingBegins` to `Ends`).
    busy: bool,
    /// The `Active` event fired: a background task's matcher began once.
    started: bool,
}

/// What the debug task runner waits for (debugTaskRunner.ts `taskDonePromise`).
pub(super) enum DebugTaskWait {
    /// The task already runs and is not busy.
    Idle,
    Exit(oneshot::Receiver<Option<i32>>),
    Inactive(oneshot::Receiver<bool>),
}

/// What `$fetchTasks` and the run commands search: every configured and provided task.
type Fetched = oneshot::Receiver<Vec<Task>>;

impl TaskService {
    pub fn new(contributions: &[(&str, &Value)]) -> Self {
        TaskService { definitions: definitions(contributions), matchers: Registry::new(contributions), ..Default::default() }
    }

    fn definition(&self, task_type: &str) -> Option<&TaskDefinition> {
        self.definitions.iter().find(|definition| definition.task_type == task_type)
    }
}

/// The markers service as the collector sees it.
struct WorkbenchMarkers<'a>(&'a Workbench);

impl Markers for WorkbenchMarkers<'_> {
    fn resources_of(&self, owner: &str) -> Vec<PathBuf> {
        self.0.marker_resources_of(owner)
    }

    fn is_open(&self, resource: &PathBuf) -> bool {
        self.0.editors.all_editors().any(|editor| editor.document().path == *resource)
    }
}

impl Workbench {
    /// The task types, problem patterns and matchers of the running extensions; the run commands.
    pub fn start_tasks(&mut self) {
        let contributions: Vec<(&str, &Value)> = self.extensions.iter().map(|extension| (extension.id.as_str(), &extension.description["contributes"])).collect();
        self.tasks = TaskService::new(&contributions);
        self.commands.register("workbench.action.tasks.runTask", |workbench, args, window, cx| {
            let argument = args.into_iter().next().unwrap_or(Value::Null);
            workbench.with_task_trust(window, cx, move |workbench, window, cx| workbench.run_task_command(argument, window, cx))
        });
        self.register_task_pick_actions();
    }

    pub(super) fn running_tasks(&self) -> Vec<Task> {
        self.tasks.active.iter().map(|active| active.task.clone()).collect()
    }

    pub(super) fn task_terminal(&self, task: &Task) -> Option<u32> {
        self.tasks.active.iter().find(|active| active.task.id == task.id).map(|active| active.terminal)
    }

    pub fn handle_task_request(&mut self, request: ForwardedRequest, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        let arg = |index: usize| request.args.get(index).cloned().unwrap_or(Value::Null);
        match request.method.as_str() {
            "$registerTaskProvider" => {
                self.tasks.providers.push((arg(0).as_i64().unwrap_or_default(), arg(1).as_str().unwrap_or_default().to_owned()));
                Outcome::done()
            }
            "$unregisterTaskProvider" => {
                let handle = arg(0).as_i64();
                self.tasks.providers.retain(|(known, _)| Some(*known) != handle);
                Outcome::done()
            }
            "$createTaskId" => match self.task_from_dto(&arg(0)) {
                Some(task) => Outcome::Ready(Ok(json!(task.id))),
                None => Outcome::error("Task could not be created from DTO"),
            },
            "$fetchTasks" => {
                let filter_type = arg(0)["type"].as_str().map(str::to_owned);
                let fetched = self.fetch_tasks(filter_type.clone(), cx);
                let (reply, receiver) = oneshot::channel();
                cx.background_executor()
                    .spawn(async move {
                        let tasks = fetched.await.unwrap_or_default();
                        let dtos: Vec<Value> = tasks.iter().filter(|task| filter_type.as_ref().is_none_or(|kind| task.definition["type"] == *kind)).map(Task::to_dto).collect();
                        let _ = reply.send(Ok(json!(dtos)));
                    })
                    .detach();
                Outcome::Pending(receiver)
            }
            "$getTaskExecution" | "$executeTask" => {
                let value = arg(0);
                let execute = request.method == "$executeTask";
                // `TaskHandleDTO`: an id and a workspace folder; the task is looked up again.
                if value["id"].is_string() && !value["workspaceFolder"].is_null() {
                    let id = value["id"].as_str().unwrap_or_default().to_owned();
                    let task_type = value["type"].as_str().map(str::to_owned);
                    let fetched = self.fetch_tasks(task_type, cx);
                    let (reply, receiver) = oneshot::channel();
                    cx.spawn_in(window, async move |workbench, cx| {
                        let tasks = fetched.await.unwrap_or_default();
                        let Some(task) = tasks.into_iter().find(|task| task.id == id) else {
                            let _ = reply.send(Err(crate::commands::error_value("Task not found")));
                            return;
                        };
                        let _ = reply.send(Ok(json!({ "id": id, "task": task.to_dto() })));
                        if execute {
                            let _ = workbench.update_in(cx, |workbench, window, cx| drop(workbench.run_task(task, window, cx)));
                        }
                    })
                    .detach();
                    return Outcome::Pending(receiver);
                }
                let Some(task) = self.task_from_dto(&value) else { return Outcome::error("Task could not be created from DTO") };
                let result = json!({ "id": task.id, "task": task.to_dto() });
                self.tasks.known.insert(task.id.clone(), task.clone());
                if execute {
                    drop(self.run_task(task, window, cx));
                }
                Outcome::Ready(Ok(result))
            }
            "$customExecutionComplete" => {
                let id = arg(0).as_str().unwrap_or_default().to_owned();
                let Some(index) = self.tasks.active.iter().position(|active| active.task.id == id) else { return Outcome::error("Task to mark as complete not found") };
                let code = arg(1).as_i64().map(|code| code as i32);
                self.task_ended(index, code, window, cx);
                Outcome::done()
            }
            "$terminateTask" => {
                let id = arg(0).as_str().unwrap_or_default().to_owned();
                let Some(terminal) = self.tasks.active.iter().find(|active| active.task.id == id).map(|active| active.terminal) else {
                    return Outcome::error("Task to terminate not found");
                };
                self.kill_terminal(terminal, window, cx);
                Outcome::done()
            }
            "$registerSupportedExecutions" => {
                for (index, supported) in self.tasks.supported_executions.iter_mut().enumerate() {
                    if let Some(value) = arg(index).as_bool() {
                        *supported = Some(value);
                    }
                }
                cx.notify();
                Outcome::done()
            }
            // `$registerTaskSystem`: the port runs every execution kind locally.
            _ => Outcome::done(),
        }
    }

    /// `taskTypes`: with `task.autoDetect` on, every declared type whose `when` holds.
    pub(super) fn task_types(&self, window: &Window) -> Vec<String> {
        if self.setting("task.autoDetect") == "off" {
            return Vec::new();
        }
        let context = self.key_context(window);
        let enabled = |when: &Option<String>| when.as_deref().and_then(crate::contextkey::Expr::deserialize).is_none_or(|when| when.evaluate(&context));
        self.tasks.definitions.iter().filter(|definition| enabled(&definition.when)).map(|definition| definition.task_type.clone()).collect()
    }

    pub(super) fn task_context(&self, context: &mut HashMap<String, Value>) {
        for (key, supported) in ["customExecutionSupported", "shellExecutionSupported", "processExecutionSupported"].into_iter().zip(self.tasks.supported_executions) {
            if let Some(supported) = supported {
                context.insert(key.into(), Value::Bool(supported));
            }
        }
    }

    fn task_from_dto(&self, dto: &Value) -> Option<Task> {
        let task_type = dto["definition"]["type"].as_str().unwrap_or_default();
        let folder = self.workspace().and_then(|workspace| workspace.folders.first()).map(|folder| folder.path.clone());
        Task::from_dto(dto, self.tasks.definition(task_type), folder.as_deref())
    }

    /// `getWorkspaceTasks` then the providers (`_getGroupedTasks`): tasks.json of each folder, the provided tasks
    /// of `task_type` (every type without one), and the configurations merged into the tasks they configure.
    pub(super) fn fetch_tasks(&mut self, task_type: Option<String>, cx: &mut Context<Self>) -> Fetched {
        let configured = self.configured_tasks();
        // `_activateTaskProviders`: the run command's event and `onTaskType:` of the type, or of every type.
        let mut events = vec!["onCommand:workbench.action.tasks.runTask".to_owned()];
        match &task_type {
            Some(task_type) => events.push(format!("onTaskType:{task_type}")),
            None => events.extend(self.tasks.definitions.iter().map(|definition| format!("onTaskType:{}", definition.task_type))),
        }
        let activations: Vec<_> = events.iter().map(|event| self.host.activate_by_event(event)).collect();
        let (reply, receiver) = oneshot::channel();
        cx.spawn(async move |workbench, cx| {
            let timeout = cx.background_executor().timer(std::time::Duration::from_secs(5));
            futures::future::select(join_all(activations), timeout).await;
            let Ok(requests) = workbench.update(cx, |workbench, _| workbench.provide_tasks(task_type.as_deref())) else { return };
            let provided = requests.await;
            let _ = reply.send(merge_tasks(configured, provided));
        })
        .detach();
        receiver
    }

    /// `$provideTasks` of the providers registered for `task_type` (all without one).
    fn provide_tasks(&self, task_type: Option<&str>) -> impl std::future::Future<Output = Vec<Task>> + use<> {
        let mut requests = Vec::new();
        for (handle, provider_type) in &self.tasks.providers {
            if task_type.is_some_and(|wanted| wanted != provider_type) {
                continue;
            }
            let valid_types: serde_json::Map<String, Value> = self.tasks.definitions.iter().map(|definition| (definition.task_type.clone(), json!(true))).chain([("shell".into(), json!(true)), ("process".into(), json!(true))]).collect();
            requests.push(self.host.call("ExtHostTask", "$provideTasks", vec![json!(handle), Value::Object(valid_types)]));
        }
        let definitions = self.tasks.definitions.clone();
        let folder = self.workspace().and_then(|workspace| workspace.folders.first()).map(|folder| folder.path.clone());
        async move {
            let mut provided = Vec::new();
            for set in join_all(requests).await.into_iter().flatten().flatten() {
                for dto in set["tasks"].as_array().into_iter().flatten() {
                    let definition = definitions.iter().find(|definition| definition.task_type == dto["definition"]["type"].as_str().unwrap_or_default());
                    if let Some(task) = Task::from_dto(dto, definition, folder.as_deref()) {
                        provided.push(task);
                    }
                }
            }
            provided
        }
    }


    /// tasks.json of each folder through the configuration service (`.vscode/` and `.vsrustium/`), then
    /// `_computeUserTasks`: the profile's tasks.json in the first folder, or the user home in an empty window.
    pub(super) fn configured_tasks(&mut self) -> Vec<Task> {
        let folders: Vec<PathBuf> = self.workspace().map(|workspace| workspace.folders.iter().map(|folder| folder.path.clone()).collect()).unwrap_or_default();
        let mut tasks = Vec::new();
        for folder in &folders {
            let inspected = self.settings.lock().unwrap().configuration.inspect("tasks", &config::configuration::Overrides { resource: Some(folder), override_identifier: None });
            let Some(config) = inspected.workspace_folder.value.or(inspected.workspace.value) else { continue };
            tasks.extend(self.parse_configured_tasks(&config, folder, folder.clone()));
        }
        let user_folder = folders.first().cloned().or_else(std::env::home_dir);
        let user_config = self.settings.lock().unwrap().configuration.inspect("tasks", &Default::default()).user_local.value;
        if let (Some(config), Some(folder)) = (user_config, user_folder) {
            let mut user_tasks = self.parse_configured_tasks(&config, &folder, PathBuf::from(USER_TASKS_GROUP_KEY));
            for task in &mut user_tasks {
                // TaskSourceDTO.from of a `TaskSourceKind.User` task: the label alone.
                task.source = json!({ "label": "User" });
            }
            tasks.extend(user_tasks);
        }
        tasks
    }

    /// `_computeTasksForSingleConfig`: the tasks of one tasks.json value; `uuid_scope` keeps each file's task ids apart.
    fn parse_configured_tasks(&mut self, config: &Value, folder: &Path, uuid_scope: PathBuf) -> Vec<Task> {
        let folder_uri = json!({ "$mid": 1, "scheme": "file", "path": folder });
        let uuids = &mut self.tasks.uuids;
        let (parsed, errors) = parse_tasks_json(config, folder, &folder_uri, &self.tasks.definitions, &mut |label| uuids.entry((uuid_scope.clone(), label.to_owned())).or_insert_with(exthost::main_thread_storage::generate_uuid).clone());
        for error in errors {
            self.log_task_error(&error);
        }
        parsed
    }

    /// `_outputChannel.append`: configuration errors go to the Tasks output channel.
    fn log_task_error(&self, message: &str) {
        let Some(channel) = self.output.channel(TASKS_OUTPUT_CHANNEL_ID) else { return };
        let appended = std::fs::create_dir_all(channel.file.parent().expect("an output folder")).and_then(|()| {
            std::fs::OpenOptions::new().create(true).append(true).open(&channel.file)?.write_all(format!("{message}\n").as_bytes())
        });
        if let Err(error) = appended {
            eprintln!("[tasks] {message} ({error})");
        }
    }

    /// `run`: dependencies first, then the task; the receiver gets its exit code once it ends.
    pub(super) fn run_task(&mut self, task: Task, window: &mut Window, cx: &mut Context<Self>) -> oneshot::Receiver<Option<i32>> {
        let (reply, receiver) = oneshot::channel();
        // `CustomExecutionAccepted` (`reserveCustomExecution`): the host keeps a custom execution's callback from
        // the moment the run is accepted, before its dependencies, until `$OnDidEndTask` with the start id.
        let custom = task.execution.as_ref().is_some_and(|execution| execution["customExecution"] == "customExecution");
        let start_id = custom.then(exthost::main_thread_storage::generate_uuid);
        if let Some(start_id) = &start_id {
            self.host.send("ExtHostTask", "$onWillStartTask", vec![json!(task.id), json!(start_id)]);
        }
        if task.depends_on.is_empty() {
            self.start_task(task, start_id, reply, window, cx);
            return receiver;
        }
        let fetched = self.fetch_tasks(None, cx);
        cx.spawn_in(window, async move |workbench, cx| {
            let all = fetched.await.unwrap_or_default();
            let dependencies: Vec<Task> = task.depends_on.iter().filter_map(|reference| find_task(&all, reference)).collect();
            let ok = run_dependencies(&workbench, cx, dependencies, task.depends_in_sequence).await;
            if !ok {
                // `executeTask` resolves with no exit code when a dependency failed; `CustomExecutionFinished`.
                if let Some(start_id) = start_id {
                    let execution = json!({ "id": task.id, "task": task.to_dto() });
                    let _ = workbench.update(cx, |workbench, _| workbench.host.send("ExtHostTask", "$OnDidEndTask", vec![execution, json!(start_id)]));
                }
                let _ = reply.send(None);
                return;
            }
            let _ = workbench.update_in(cx, |workbench, window, cx| workbench.start_task(task, start_id, reply, window, cx));
        })
        .detach();
        receiver
    }

    /// `_executeCommand`: the task's `${command:...}` and `${input:...}` are asked for first (`_acquireInput`), then it
    /// runs with them replaced; a cancelled prompt ends the task without running it.
    fn start_task(&mut self, task: Task, start_id: Option<String>, reply: oneshot::Sender<Option<i32>>, window: &mut Window, cx: &mut Context<Self>) {
        let Some(variables) = super::configuration_resolver::task_interactive_variables(&task) else {
            return self.launch_task(task, start_id, reply, window, cx);
        };
        // `resolveWithInteraction` with ConfigurationTarget.USER for a user task: the inputs of the profile's tasks.json.
        let inputs = match task.is_user() {
            true => self.settings.lock().unwrap().configuration.inspect("tasks", &Default::default()).user_local.value.and_then(|tasks| tasks["inputs"].as_array().cloned()),
            false => self.task_inputs(task.workspace_folder.as_deref()),
        };
        cx.spawn_in(window, async move |workbench, cx| {
            let resolved = super::configuration_resolver::resolve_with_interaction(&workbench, cx, &variables, "tasks", inputs.as_deref(), &Default::default()).await;
            let _ = workbench.update_in(cx, |workbench, window, cx| match resolved {
                Ok(Some(resolved)) => workbench.launch_task(super::configuration_resolver::task_with_variables(task, &resolved), start_id, reply, window, cx),
                outcome => {
                    if let Err(message) = outcome {
                        workbench.notify_error(message);
                    }
                    if let Some(start_id) = start_id {
                        workbench.host.send("ExtHostTask", "$OnDidEndTask", vec![json!({ "id": task.id, "task": task.to_dto() }), json!(start_id)]);
                    }
                    let _ = reply.send(Some(0));
                }
            });
        })
        .detach();
    }

    /// terminalTaskSystem.ts `_executeInTerminal`: a terminal named after the task runs it.
    fn launch_task(&mut self, task: Task, start_id: Option<String>, reply: oneshot::Sender<Option<i32>>, window: &mut Window, cx: &mut Context<Self>) {
        // `run`: past `runOptions.instanceLimit` (1 by default) the task does not start again; the caller waits for the
        // newest instance and `_handleInstancePolicy` applies.
        let instances: Vec<usize> = (0..self.tasks.active.len()).filter(|&index| self.tasks.active[index].task.id == task.id).collect();
        let limit = task.run_options["instanceLimit"].as_u64().unwrap_or(1) as usize;
        if task.execution.is_some() && instances.len() >= limit {
            let newest = *instances.last().expect("the limit is at least one instance");
            self.tasks.active[newest].waiters.push(reply);
            if let Some(start_id) = start_id {
                self.host.send("ExtHostTask", "$OnDidEndTask", vec![json!({ "id": task.id, "task": task.to_dto() }), json!(start_id)]);
            }
            self.handle_instance_policy(&task, instances, window, cx);
            return;
        }
        let Some(execution) = task.execution.clone() else {
            // A task with only dependencies ends as soon as they did.
            let _ = reply.send(Some(0));
            return;
        };
        let custom = execution["customExecution"] == "customExecution";
        // `resolveVariablesFromSet`: the command, args and options of a shell or process task.
        let execution = match custom {
            true => execution,
            false => match self.resolve_variables(&execution, task.workspace_folder.clone()) {
                Ok(resolved) => resolved,
                Err(message) => {
                    self.notify_error(message);
                    let _ = reply.send(None);
                    return;
                }
            },
        };
        let (mut launch, initial_text) = match custom {
            true => {
                let launch = ShellLaunchConfig { name: Some(task.name.clone()), extension_pty: true, is_feature_terminal: true, cwd: self.terminal_initial_cwd(), ..Default::default() };
                // A custom execution's `initialText` is the message alone, written with `writeln`.
                let echo = (task.presentation["echo"] != false).then(|| format!("{}\r\n", format_message_for_terminal(&format!("Executing task: {}", task.label))));
                (launch, echo.unwrap_or_default())
            }
            false => self.task_launch_config(&task, &execution),
        };
        // terminalTaskSystem.ts: the task's `icon`, `$(tools)` without one (terminalInstance.ts for a Task terminal).
        launch.icon = Some(task.icon["id"].as_str().unwrap_or("tools").to_owned());
        launch.color = task.icon["color"].as_str().map(str::to_owned);
        let presentation = &task.presentation;
        let panel = presentation["panel"].as_u64().unwrap_or(PANEL_SHARED);
        let group = presentation["group"].as_str().map(str::to_owned);
        let key = format!("{}|{}", task.id, instances.len());
        let wait_on_exit = wait_on_exit(presentation, task.is_background);
        let reused = self.tasks.take_terminal_to_reuse(&key, panel, group.as_deref()).filter(|&terminal| self.terminal_view.instance(terminal).is_some());
        let terminal = match reused {
            Some(terminal) => {
                // The reused terminal keeps its nonce, so the echoed command line names it to stay trusted.
                let nonce = self.terminal_view.instance(terminal).map(|instance| instance.launch.nonce.clone()).unwrap_or_default();
                let initial_text = initial_text.replace(&launch.nonce, &nonce);
                self.reuse_terminal(terminal, launch, &initial_text, window, cx);
                if presentation["clear"] == true
                    && let Some(instance) = self.terminal_view.instance_mut(terminal)
                {
                    instance.clear();
                }
                terminal
            }
            None => {
                let terminal = self.add_terminal(launch, None, window, cx);
                if !initial_text.is_empty() {
                    let colors = crate::terminal::colors::TerminalColors::new(&self.theme);
                    if let Some(instance) = self.terminal_view.instance_mut(terminal) {
                        instance.process(initial_text.as_bytes(), &colors);
                    }
                }
                self.tasks.terminals.insert(terminal, TaskTerminal { group, wait_on_exit });
                terminal
            }
        };
        if let Some(data) = self.tasks.terminals.get_mut(&terminal) {
            data.wait_on_exit = wait_on_exit;
        }
        // `revealProblems: always` opens Problems; else `focus` or `reveal: always` shows the terminal, focused with `focus`.
        if presentation["revealProblems"].as_u64() == Some(REVEAL_PROBLEMS_ALWAYS) {
            self.open_panel_view(MARKERS_VIEW_ID, cx);
        } else if presentation["focus"] == true || presentation["reveal"].as_u64().unwrap_or(REVEAL_ALWAYS) == REVEAL_ALWAYS {
            self.terminal_view.set_active(terminal);
            self.open_panel_view(super::terminal_view::TERMINAL_VIEW_ID, cx);
            if task.presentation["focus"] == true {
                window.focus(&self.terminal_view.focus, cx);
            }
            self.sync_terminals_to_host();
        }
        let execution_dto = json!({ "id": task.id, "task": task.to_dto() });
        // `resolvedDefinition`: the definition with its variables resolved, as the custom execution callback sees it.
        let resolved_definition = self.resolve_variables(&task.definition, task.workspace_folder.clone()).unwrap_or_else(|_| task.definition.clone());
        self.host.send("ExtHostTask", "$onDidStartTask", vec![execution_dto.clone(), json!(terminal), resolved_definition, json!(start_id)]);
        let pid = self.terminal_view.instance(terminal).and_then(|instance| instance.pid);
        if let Some(pid) = pid {
            self.host.send("ExtHostTask", "$onDidStartTaskProcess", vec![json!({ "id": task.id, "processId": pid })]);
        }
        let mut collector = self.task_collector(&task);
        if let Some(collector) = &mut collector {
            // `aboutToStart`: background matchers active on start begin with the task.
            collector.about_to_start(&WorkbenchMarkers(self));
        }
        if collector.is_some() {
            self.host.send("ExtHostTask", "$onDidStartTaskProblemMatchers", vec![json!({ "execution": execution_dto })]);
        }
        let has_collector = collector.is_some();
        let busy = !task.is_background;
        self.tasks.active.push(ActiveTask { task, key, terminal, start_id, collector, waiters: vec![reply], busy, started: busy });
        // `addTerminal`, then `ProcessStarted`.
        if let Some(instance) = self.terminal_view.instance_mut(terminal) {
            instance.add_status(TerminalStatus { id: TASK_STATUS, severity: STATUS_INFO, icon: None, tooltip: None });
        }
        self.task_status_active(terminal, has_collector);
    }

    /// `_handleInstancePolicy`: the task's terminal shows, then the newest or oldest instance restarts, nothing
    /// happens, a warning shows, or (`prompt`, the default) the user picks the instance to restart.
    fn handle_instance_policy(&mut self, task: &Task, instances: Vec<usize>, window: &mut Window, cx: &mut Context<Self>) {
        let terminals: Vec<u32> = instances.iter().map(|&index| self.tasks.active[index].terminal).collect();
        let newest = *terminals.last().expect("at least one instance");
        self.terminal_view.set_active(newest);
        self.show_terminal_tab(window, cx);
        match task.run_options["instancePolicy"].as_str() {
            Some("terminateNewest") => self.restart_task_instance(task, newest, window, cx),
            Some("terminateOldest") => self.restart_task_instance(task, terminals[0], window, cx),
            Some("silent") => {}
            Some("warn") => self.notify_warning("The instance limit for this task has been reached."),
            _ => self.show_instance_picker(task, terminals, window, cx),
        }
    }

    /// `_restart` of one instance: its terminal goes (ending the task), then the task runs again.
    pub(super) fn restart_task_instance(&mut self, task: &Task, terminal: u32, window: &mut Window, cx: &mut Context<Self>) {
        self.kill_terminal(terminal, window, cx);
        drop(self.run_task(task.clone(), window, cx));
    }

    /// What `configurationResolverService.resolveAsync` reads: the folders, `folder` for `${workspaceFolder}`, the
    /// active editor's file and cursor.
    pub(super) fn variable_context(&self, folder: Option<PathBuf>) -> crate::variables::VariableContext {
        let folders: Vec<(String, PathBuf)> = self.workspace().map(|workspace| workspace.folders.iter().map(|folder| (folder.name.clone(), folder.path.clone())).collect()).unwrap_or_default();
        let active = self.editors.active().filter(|editor| editor.document().scheme == "file");
        let cursor = active.map(|editor| editor.selections[0].head);
        crate::variables::VariableContext {
            folder: folder.or_else(|| folders.first().map(|(_, path)| path.clone())),
            folders,
            file: active.map(|editor| editor.document().path.clone()),
            line_number: cursor.map(|position| position.line as u32 + 1),
            column_number: cursor.map(|position| position.column as u32 + 1),
            selected_text: self.editors.active().map(|editor| crate::editor::text_between(&editor.document().lines, editor.selection().start(), editor.selection().end())),
            exec_path: std::env::current_exe().ok(),
            cwd: std::env::current_dir().unwrap_or_default(),
            env: std::env::vars().collect(),
            home: std::env::home_dir(),
        }
    }

    /// `resolveAsync` with the configuration service for `${config:...}`.
    pub(super) fn resolve_variables(&self, value: &Value, folder: Option<PathBuf>) -> Result<Value, String> {
        let context = self.variable_context(folder);
        crate::variables::resolve_value(value, &context, &|key| Some(self.setting(key)).filter(|value| !value.is_null()))
    }

    /// `_createShellLaunchConfig` for macOS: the automation shell (`-c` and the command line) or the process.
    /// `_createShellLaunchConfig`: the launch and its `initialText`, the task shell integration sequences around the
    /// echoed command (`taskShellIntegrationStartSequence`, `getTaskShellIntegrationOutputSequence`).
    fn task_launch_config(&self, task: &Task, execution: &Value) -> (ShellLaunchConfig, String) {
        let options = &execution["options"];
        let cwd = options["cwd"].as_str().map(PathBuf::from).or_else(|| task.workspace_folder.clone()).unwrap_or_else(|| self.terminal_initial_cwd());
        let env: HashMap<String, Option<String>> = options["env"].as_object().into_iter().flatten().map(|(key, value)| (key.clone(), value.as_str().map(str::to_owned))).collect();
        let nonce = exthost::main_thread_storage::generate_uuid();
        let (executable, args, echo, command_line_info) = match execution["process"].as_str() {
            Some(process) => {
                let args: Vec<String> = execution["args"].as_array().into_iter().flatten().filter_map(|arg| arg.as_str().map(str::to_owned)).collect();
                let echo = format!("{process} {}", args.join(" "));
                (PathBuf::from(process), args, echo, None)
            }
            None => {
                let command_line = shell_command_line(execution);
                let (executable, mut args) = match options["executable"].as_str() {
                    Some(shell) => (PathBuf::from(shell), options["shellArgs"].as_array().into_iter().flatten().filter_map(|arg| arg.as_str().map(str::to_owned)).collect()),
                    None => {
                        let profile = self.default_terminal_profile();
                        let mut args = profile.args;
                        args.push("-c".into());
                        (profile.path, args)
                    }
                };
                args.push(command_line.clone());
                let info = format!("{};{nonce}", crate::terminal::shell_integration::serialize_message(&command_line));
                (executable, args, command_line, Some(info))
            }
        };
        let message = (task.presentation["echo"] != false).then(|| {
            // `needsFolderQualification`: a .code-workspace names the folder.
            let folder = self.workspace().filter(|workspace| workspace.file.is_some()).and(task.workspace_folder.as_deref()).and_then(Path::file_name);
            match folder {
                Some(folder) => format!("Executing task in folder {}: {echo}", folder.to_string_lossy()),
                None => format!("Executing task: {echo}"),
            }
        });
        let initial_text = crate::terminal::task_initial_text(&cwd, message.as_deref(), command_line_info.as_deref());
        let launch = ShellLaunchConfig {
            name: Some(task.name.clone()),
            executable,
            args,
            cwd,
            env: self.terminal_environment(&env),
            is_feature_terminal: true,
            nonce,
            ..Default::default()
        };
        (launch, initial_text)
    }

    /// The task's problem matchers by name or inline, `None` without any.
    fn task_collector(&self, task: &Task) -> Option<ProblemCollector> {
        let folder = task.workspace_folder.as_ref().map(|folder| folder.to_string_lossy().into_owned());
        let mut matchers = Vec::new();
        for reference in &task.problem_matchers {
            let matcher = match reference {
                Value::String(name) => self.tasks.matchers.get(name.trim_start_matches('$')).cloned(),
                description => {
                    let mut messages = Vec::new();
                    let matcher = self.tasks.matchers.parse(description, &mut messages);
                    messages.iter().for_each(|(_, message)| self.log_task_error(message));
                    matcher
                }
            };
            let Some(mut matcher) = matcher else {
                self.log_task_error(&format!("Problem matcher {reference} can't be resolved. The matcher will be ignored"));
                continue;
            };
            if let (Some(prefix), Some(folder)) = (&matcher.file_prefix, &folder) {
                matcher.file_prefix = Some(prefix.replace("${workspaceFolder}", folder));
            }
            matchers.push(matcher);
        }
        (!matchers.is_empty()).then(|| ProblemCollector::new(matchers, &WorkbenchMarkers(self)))
    }

    /// Task terminal output for its problem collector.
    pub(super) fn task_output(&mut self, terminal: u32, text: &str, cx: &mut Context<Self>) {
        let Some(index) = self.tasks.active.iter().position(|active| active.terminal == terminal) else { return };
        let Some(mut collector) = self.tasks.active[index].collector.take() else { return };
        let mut changes = Vec::new();
        let events = collector.process_output(text, &WorkbenchMarkers(self), &mut changes);
        for event in events {
            match event {
                CollectorEvent::BackgroundProcessingBegins => {
                    self.tasks.active[index].busy = true;
                    self.tasks.active[index].started = true;
                    self.task_status_active(terminal, true);
                }
                CollectorEvent::BackgroundProcessingEnds => {
                    self.tasks.active[index].busy = false;
                    for waiter in self.tasks.inactive_waiters.remove(&self.tasks.active[index].task.id).into_iter().flatten() {
                        let _ = waiter.send(false);
                    }
                    self.task_status_inactive(terminal, &collector);
                    // `ProblemMatcherFoundErrors`: `revealProblems: onProblem` opens Problems, else `reveal: silent` shows the terminal.
                    if collector.number_of_matches > 0 && collector.max_severity == Some(SEVERITY_ERROR) {
                        let presentation = self.tasks.active[index].task.presentation.clone();
                        if presentation["revealProblems"].as_u64() == Some(REVEAL_PROBLEMS_ON_PROBLEM) {
                            self.open_panel_view(MARKERS_VIEW_ID, cx);
                        } else if presentation["reveal"].as_u64() == Some(REVEAL_SILENT) {
                            self.show_task_terminal_silently(terminal, cx);
                        }
                    }
                }
            }
        }
        self.tasks.active[index].collector = Some(collector);
        self.apply_marker_changes(changes, cx);
    }

    /// taskTerminalStatus.ts `eventActive`: the spinner while a run goes, unless a background task has no matchers.
    fn task_status_active(&mut self, terminal: u32, has_collector: bool) {
        let single_run = self.tasks.active.iter().find(|active| active.terminal == terminal).is_some_and(|active| !active.task.is_background);
        let animate = self.setting("terminal.integrated.tabs.enableAnimation") != false;
        let Some(instance) = self.terminal_view.instance_mut(terminal) else { return };
        instance.remove_status(TASK_STATUS);
        if has_collector || single_run {
            // terminalStatusList.ts `_applyAnimationSetting`: without animation the spinner is a play icon.
            instance.add_status(task_status(STATUS_INFO, if animate { "loading~spin" } else { "play" }, "Task is running"));
        }
    }

    /// taskTerminalStatus.ts `eventInactive`: a background run ended, its result by the matches it found.
    fn task_status_inactive(&mut self, terminal: u32, collector: &ProblemCollector) {
        let Some(instance) = self.terminal_view.instance_mut(terminal) else { return };
        instance.remove_status(TASK_STATUS);
        let status = match collector.max_severity {
            _ if collector.number_of_matches == 0 => task_status(STATUS_INFO, "check", "Task succeeded and waiting..."),
            Some(SEVERITY_ERROR) => task_status(STATUS_ERROR, "error", "Task has errors and is waiting..."),
            Some(SEVERITY_WARNING) => task_status(STATUS_WARNING, "warning", "Task has warnings and is waiting..."),
            Some(SEVERITY_INFO) => task_status(STATUS_INFO, "info", "Task has infos and is waiting..."),
            _ => return,
        };
        instance.add_status(status);
    }

    /// taskTerminalStatus.ts `eventEnd`: the result by the exit code and the most severe problem found.
    fn task_status_end(&mut self, terminal: u32, code: Option<i32>, is_background: bool, max_severity: Option<u8>) {
        let Some(instance) = self.terminal_view.instance_mut(terminal) else { return };
        instance.remove_status(TASK_STATUS);
        let status = match (code, max_severity) {
            (Some(0), None | Some(..SEVERITY_WARNING)) if is_background => {
                instance.statuses.clear();
                return;
            }
            (Some(0), None | Some(..SEVERITY_WARNING)) => task_status(STATUS_INFO, "check", "Task succeeded"),
            (Some(code), _) if code != 0 => task_status(STATUS_ERROR, "error", "Task has errors"),
            (_, Some(SEVERITY_ERROR)) => task_status(STATUS_ERROR, "error", "Task has errors"),
            (_, Some(SEVERITY_WARNING)) => task_status(STATUS_WARNING, "warning", "Task has warnings"),
            (_, Some(SEVERITY_INFO)) => task_status(STATUS_INFO, "info", "Task has infos"),
            _ => return,
        };
        instance.add_status(status);
    }

    /// A task terminal's process exited: the task running in it ends. Returns the terminal's `waitOnExit`, `None`
    /// for a terminal of no task.
    pub(super) fn task_process_exited(&mut self, terminal: u32, code: Option<i32>, window: &mut Window, cx: &mut Context<Self>) -> Option<WaitOnExit> {
        let wait_on_exit = self.tasks.terminals.get(&terminal).map(|data| data.wait_on_exit);
        let Some(index) = self.tasks.active.iter().position(|active| active.terminal == terminal) else { return wait_on_exit };
        let active = &self.tasks.active[index];
        if active.start_id.is_none() {
            let mut event = json!({ "id": active.task.id });
            if let Some(code) = code {
                event["exitCode"] = json!(code);
            }
            self.host.send("ExtHostTask", "$onDidEndTaskProcess", vec![event]);
        }
        self.task_ended(index, code, window, cx);
        wait_on_exit
    }

    /// `setActiveInstance` and `showPanel(false)`: the panel shows the terminal without focus.
    fn show_task_terminal_silently(&mut self, terminal: u32, cx: &mut Context<Self>) {
        if self.terminal_view.instance(terminal).is_none() {
            return;
        }
        self.terminal_view.set_active(terminal);
        self.open_panel_view(super::terminal_view::TERMINAL_VIEW_ID, cx);
        self.sync_terminals_to_host();
    }

    pub(super) fn forget_task_terminal(&mut self, terminal: u32) {
        self.tasks.forget_terminal(terminal);
    }

    /// The task's end: problem matchers finish, the host hears `$OnDidEndTask`, the waiters get the exit code.
    fn task_ended(&mut self, index: usize, code: Option<i32>, _window: &mut Window, cx: &mut Context<Self>) {
        let mut active = self.tasks.active.remove(index);
        let presentation = active.task.presentation.clone();
        self.tasks.keep_terminal(active.key.clone(), active.terminal, presentation["panel"].as_u64().unwrap_or(PANEL_SHARED));
        let execution = json!({ "id": active.task.id, "task": active.task.to_dto() });
        let mut max_severity = None;
        let mut number_of_matches = 0;
        if let Some(mut collector) = active.collector.take() {
            let mut changes = Vec::new();
            collector.done(&WorkbenchMarkers(self), &mut changes);
            self.apply_marker_changes(changes, cx);
            self.host.send("ExtHostTask", "$onDidEndTaskProblemMatchers", vec![json!({ "execution": execution, "hasErrors": collector.max_severity == Some(SEVERITY_ERROR) })]);
            max_severity = collector.max_severity;
            number_of_matches = collector.number_of_matches;
        }
        // `revealProblems: onProblem` opens Problems after matches (a background task's as they end, `task_output`);
        // `reveal: silent` shows the terminal after a failure or an error match.
        if !active.task.is_background && presentation["revealProblems"].as_u64() == Some(REVEAL_PROBLEMS_ON_PROBLEM) && number_of_matches > 0 {
            self.open_panel_view(MARKERS_VIEW_ID, cx);
        } else if presentation["reveal"].as_u64() == Some(REVEAL_SILENT) && (code.unwrap_or(0) != 0 || max_severity == Some(SEVERITY_ERROR)) {
            self.show_task_terminal_silently(active.terminal, cx);
        }
        self.task_status_end(active.terminal, code, active.task.is_background, max_severity);
        self.host.send("ExtHostTask", "$OnDidEndTask", vec![execution, json!(active.start_id)]);
        for waiter in active.waiters {
            let _ = waiter.send(code);
        }
        // `ProcessEnded` without an exit code comes first; a busy run then goes `Inactive`.
        let inactive_waiters = self.tasks.inactive_waiters.remove(&active.task.id).unwrap_or_default();
        if code.is_none() || active.busy {
            for waiter in inactive_waiters {
                let _ = waiter.send(code.is_none());
            }
        }
    }

    /// debugTaskRunner.ts `runTask` on the task service: a running instance that is not busy needs nothing, a busy
    /// one is waited for until it goes inactive, else the task runs; a background run is waited for until inactive.
    pub(super) fn run_task_for_debug(&mut self, task: Task, window: &mut Window, cx: &mut Context<Self>) -> DebugTaskWait {
        let running = self.tasks.active.iter().find(|active| active.task.id == task.id).map(|active| active.busy);
        if running == Some(false) {
            return DebugTaskWait::Idle;
        }
        if running.is_none() && !task.is_background {
            return DebugTaskWait::Exit(self.run_task(task, window, cx));
        }
        let (sender, receiver) = oneshot::channel();
        self.tasks.inactive_waiters.entry(task.id.clone()).or_default().push(sender);
        if running.is_none() {
            drop(self.run_task(task, window, cx));
        }
        DebugTaskWait::Inactive(receiver)
    }

    /// Whether a launched task fired `Active` (debugTaskRunner.ts `taskStarted`), `None` before it launched.
    pub(super) fn debug_task_started(&self, id: &str) -> Option<bool> {
        self.tasks.active.iter().find(|active| active.task.id == id).map(|active| active.started)
    }

    fn apply_marker_changes(&mut self, changes: Vec<MarkerChange>, cx: &mut Context<Self>) {
        for change in changes {
            match change {
                MarkerChange::Set { owner, resource, markers } => {
                    let uri = json!({ "$mid": 1, "scheme": "file", "path": resource });
                    self.change_many_markers(&owner, &json!([[uri, markers, false]]), cx);
                }
                MarkerChange::Remove { owner, resources } => {
                    let entries: Vec<Value> = resources.iter().map(|resource| json!([{ "$mid": 1, "scheme": "file", "path": resource }, [], false])).collect();
                    self.change_many_markers(&owner, &json!(entries), cx);
                }
            }
        }
    }

    /// `workbench.action.tasks.runTask`: a label, a task identifier object, or the pick of every task.
    pub(super) fn run_task_command(&mut self, argument: Value, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        if argument.is_null() {
            self.show_run_task_picker(None, window, cx);
            return Outcome::done();
        }
        let fetched = self.fetch_tasks(argument["type"].as_str().map(str::to_owned), cx);
        let (reply, receiver) = oneshot::channel();
        cx.spawn_in(window, async move |workbench, cx| {
            let tasks = fetched.await.unwrap_or_default();
            let Some(task) = find_task(&tasks, &argument) else {
                // `_doRunTaskCommand(tasks, type, name)`: the picker, filtered by the name.
                let name = argument.as_str().map(str::to_owned).or_else(|| argument["task"].as_str().map(str::to_owned));
                let _ = workbench.update_in(cx, |workbench, window, cx| workbench.show_run_task_picker(name, window, cx));
                let _ = reply.send(Ok(Value::Null));
                return;
            };
            // `_runTaskCommand`: a name or identifier the resolver finds runs as it is (`this.run(task)`), with no
            // problem matcher prompt; the prompt is for a name only `configurationProperties.identifier` matches.
            let Ok(ended) = workbench.update_in(cx, |workbench, window, cx| {
                workbench.add_recent_task(&task);
                workbench.run_task(task, window, cx)
            }) else {
                return;
            };
            let code = ended.await.ok().flatten();
            let _ = reply.send(Ok(json!({ "exitCode": code })));
        })
        .detach();
        Outcome::Pending(receiver)
    }
}

async fn run_dependencies(workbench: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, dependencies: Vec<Task>, in_sequence: bool) -> bool {
    if in_sequence {
        for task in dependencies {
            let Ok(ended) = workbench.update_in(cx, |workbench, window, cx| workbench.run_task(task, window, cx)) else { return false };
            if ended.await.ok().flatten() != Some(0) {
                return false;
            }
        }
        return true;
    }
    let mut started = Vec::new();
    for task in dependencies {
        let Ok(ended) = workbench.update_in(cx, |workbench, window, cx| workbench.run_task(task, window, cx)) else { return false };
        started.push(ended);
    }
    join_all(started).await.into_iter().all(|code| code.ok().flatten() == Some(0))
}

/// `getTask`: a label (the configured name or `source: name`) or a task identifier.
pub(super) fn find_task(tasks: &[Task], reference: &Value) -> Option<Task> {
    match reference {
        Value::String(label) => tasks.iter().find(|task| task.label == *label || task.name == *label || task.id == *label).cloned(),
        Value::Object(identifier) => {
            let matches = |task: &Task| identifier.iter().all(|(key, value)| key == "_key" || task.definition.get(key) == Some(value));
            tasks.iter().find(|task| task.configures && matches(task)).or_else(|| tasks.iter().find(|task| matches(task))).cloned()
        }
        _ => None,
    }
}

/// `_getGroupedTasks`: configured tasks replace the provided tasks they configure; the rest stay.
fn merge_tasks(configured: Vec<Task>, provided: Vec<Task>) -> Vec<Task> {
    let mut result: Vec<Task> = Vec::new();
    for task in &provided {
        match configured.iter().find(|configuration| configuration.configures_task(task)) {
            Some(configuration) => result.push(task.customize(configuration)),
            None => result.push(task.clone()),
        }
    }
    result.extend(configured.into_iter().filter(|task| !task.configures));
    result
}

/// `_buildShellCommandLine` for a POSIX shell: the command line, or the command and its arguments quoted where
/// they hold spaces.
fn shell_command_line(execution: &Value) -> String {
    if let Some(command_line) = execution["commandLine"].as_str() {
        return command_line.to_owned();
    }
    let text = |value: &Value| value.as_str().map(str::to_owned).unwrap_or_else(|| value["value"].as_str().unwrap_or_default().to_owned());
    let quote = |value: String| if value.contains(' ') && !value.starts_with('\'') && !value.starts_with('"') { format!("'{value}'") } else { value };
    let mut parts = vec![quote(text(&execution["command"]))];
    parts.extend(execution["args"].as_array().into_iter().flatten().map(|arg| quote(text(arg))));
    parts.join(" ")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn wait_on_exit_follows_get_wait_on_exit_value() {
        let reuse = WaitOnExit::Message("Terminal will be reused by tasks, press any key to close it.");
        assert_eq!(wait_on_exit(&Value::Null, false), reuse);
        assert_eq!(wait_on_exit(&json!({ "panel": PANEL_NEW }), false), WaitOnExit::Message("Press any key to close the terminal."));
        assert_eq!(wait_on_exit(&json!({ "showReuseMessage": false }), false), WaitOnExit::Wait);
        assert_eq!(wait_on_exit(&json!({ "close": true }), false), WaitOnExit::Close);
        assert_eq!(wait_on_exit(&json!({ "reveal": REVEAL_NEVER }), true), WaitOnExit::Wait);
        assert_eq!(wait_on_exit(&json!({ "reveal": REVEAL_NEVER, "close": false }), true), reuse);
    }

    #[test]
    fn a_task_takes_back_its_own_terminal_then_one_of_its_group() {
        let mut tasks = TaskService::default();
        for (terminal, group) in [(1, None), (2, Some("build".to_owned())), (3, None)] {
            tasks.terminals.insert(terminal, TaskTerminal { group, wait_on_exit: WaitOnExit::Wait });
        }
        tasks.keep_terminal("a|0".into(), 1, PANEL_SHARED);
        tasks.keep_terminal("b|0".into(), 2, PANEL_SHARED);
        tasks.keep_terminal("c|0".into(), 3, PANEL_DEDICATED);
        assert_eq!(tasks.take_terminal_to_reuse("c|0", PANEL_SHARED, None), Some(1), "a shared task without a group takes the idle terminal of no group");
        assert_eq!(tasks.take_terminal_to_reuse("c|0", PANEL_DEDICATED, None), Some(3));
        assert_eq!(tasks.take_terminal_to_reuse("c|0", PANEL_DEDICATED, None), None);
        assert_eq!(tasks.take_terminal_to_reuse("b|0", PANEL_NEW, None), None);
        tasks.forget_terminal(2);
        assert_eq!(tasks.take_terminal_to_reuse("b|0", PANEL_SHARED, Some("build")), None);
    }

    #[gpui::test]
    fn tasks_json_errors_go_to_the_tasks_output_channel(cx: &mut gpui::TestAppContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let theme = crate::theme::load_theme(&[exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();
        let dir = std::env::temp_dir().join(format!("code-gpui-task-output-{}", std::process::id()));
        let (sender, _host) = std::sync::mpsc::channel();
        let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), crate::default_settings(), crate::host_sync::HostSync::new(sender), cx));
        let text = workbench.update(cx, |workbench, _| {
            workbench.register_window_log(dir.join("renderer.log"));
            workbench.parse_configured_tasks(&json!({ "version": "2.0.0", "tasks": [{ "type": "missing", "label": "a" }] }), &dir, dir.clone());
            let channel = workbench.output.channel(TASKS_OUTPUT_CHANNEL_ID).expect("the Tasks channel");
            (channel.label.clone(), std::fs::read_to_string(&channel.file).unwrap_or_default())
        });
        let _ = std::fs::remove_dir_all(&dir);
        assert_eq!(text.0, "Tasks");
        assert!(text.1.starts_with("Error: there is no registered task type 'missing'."), "{}", text.1);
    }

    /// problemCollectors.ts `openModels` follows `modelService.onModelAdded`: a file shown only in another group is
    /// open for `applyTo: openDocuments`.
    #[gpui::test]
    fn a_file_in_another_group_is_open_for_the_problem_collector(cx: &mut gpui::TestAppContext) {
        let (dir, workbench, cx) = crate::workbench::editor_groups::tests::workbench_with("task-open-other-group", &["a.txt"], cx);
        crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);
        let open = workbench.read_with(cx, |workbench, _| WorkbenchMarkers(workbench).is_open(&dir.join("a.txt")));
        assert!(open);
        std::fs::remove_dir_all(dir).unwrap();
    }
}