task_inventory.rs

   1//! Project-wide storage of the tasks available, capable of updating itself from the sources set.
   2
   3use std::{
   4    borrow::Cow,
   5    cmp::{self, Reverse},
   6    path::{Path, PathBuf},
   7    sync::Arc,
   8};
   9
  10use anyhow::Result;
  11use collections::{btree_map, BTreeMap, VecDeque};
  12use futures::{
  13    channel::mpsc::{unbounded, UnboundedSender},
  14    StreamExt,
  15};
  16use gpui::{AppContext, Context, Model, ModelContext, Task};
  17use itertools::Itertools;
  18use language::{ContextProvider, File, Language, Location};
  19use task::{
  20    static_source::StaticSource, ResolvedTask, TaskContext, TaskId, TaskTemplate, TaskTemplates,
  21    TaskVariables, VariableName,
  22};
  23use text::{Point, ToPoint};
  24use util::{post_inc, NumericPrefixWithSuffix, ResultExt};
  25use worktree::WorktreeId;
  26
  27use crate::Project;
  28
  29/// Inventory tracks available tasks for a given project.
  30pub struct Inventory {
  31    sources: Vec<SourceInInventory>,
  32    last_scheduled_tasks: VecDeque<(TaskSourceKind, ResolvedTask)>,
  33    update_sender: UnboundedSender<()>,
  34    _update_pooler: Task<anyhow::Result<()>>,
  35}
  36
  37struct SourceInInventory {
  38    source: StaticSource,
  39    kind: TaskSourceKind,
  40}
  41
  42/// Kind of a source the tasks are fetched from, used to display more source information in the UI.
  43#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
  44pub enum TaskSourceKind {
  45    /// bash-like commands spawned by users, not associated with any path
  46    UserInput,
  47    /// Tasks from the worktree's .zed/task.json
  48    Worktree {
  49        id: WorktreeId,
  50        abs_path: PathBuf,
  51        id_base: Cow<'static, str>,
  52    },
  53    /// ~/.config/zed/task.json - like global files with task definitions, applicable to any path
  54    AbsPath {
  55        id_base: Cow<'static, str>,
  56        abs_path: PathBuf,
  57    },
  58    /// Languages-specific tasks coming from extensions.
  59    Language { name: Arc<str> },
  60}
  61
  62impl TaskSourceKind {
  63    pub fn abs_path(&self) -> Option<&Path> {
  64        match self {
  65            Self::AbsPath { abs_path, .. } | Self::Worktree { abs_path, .. } => Some(abs_path),
  66            Self::UserInput | Self::Language { .. } => None,
  67        }
  68    }
  69
  70    pub fn worktree(&self) -> Option<WorktreeId> {
  71        match self {
  72            Self::Worktree { id, .. } => Some(*id),
  73            _ => None,
  74        }
  75    }
  76
  77    pub fn to_id_base(&self) -> String {
  78        match self {
  79            TaskSourceKind::UserInput => "oneshot".to_string(),
  80            TaskSourceKind::AbsPath { id_base, abs_path } => {
  81                format!("{id_base}_{}", abs_path.display())
  82            }
  83            TaskSourceKind::Worktree {
  84                id,
  85                id_base,
  86                abs_path,
  87            } => {
  88                format!("{id_base}_{id}_{}", abs_path.display())
  89            }
  90            TaskSourceKind::Language { name } => format!("language_{name}"),
  91        }
  92    }
  93}
  94
  95impl Inventory {
  96    pub fn new(cx: &mut AppContext) -> Model<Self> {
  97        cx.new_model(|cx| {
  98            let (update_sender, mut rx) = unbounded();
  99            let _update_pooler = cx.spawn(|this, mut cx| async move {
 100                while let Some(()) = rx.next().await {
 101                    this.update(&mut cx, |_, cx| {
 102                        cx.notify();
 103                    })?;
 104                }
 105                Ok(())
 106            });
 107            Self {
 108                sources: Vec::new(),
 109                last_scheduled_tasks: VecDeque::new(),
 110                update_sender,
 111                _update_pooler,
 112            }
 113        })
 114    }
 115
 116    /// If the task with the same path was not added yet,
 117    /// registers a new tasks source to fetch for available tasks later.
 118    /// Unless a source is removed, ignores future additions for the same path.
 119    pub fn add_source(
 120        &mut self,
 121        kind: TaskSourceKind,
 122        create_source: impl FnOnce(UnboundedSender<()>, &mut AppContext) -> StaticSource,
 123        cx: &mut ModelContext<Self>,
 124    ) {
 125        let abs_path = kind.abs_path();
 126        if abs_path.is_some() {
 127            if let Some(a) = self.sources.iter().find(|s| s.kind.abs_path() == abs_path) {
 128                log::debug!("Source for path {abs_path:?} already exists, not adding. Old kind: {OLD_KIND:?}, new kind: {kind:?}", OLD_KIND = a.kind);
 129                return;
 130            }
 131        }
 132        let source = create_source(self.update_sender.clone(), cx);
 133        let source = SourceInInventory { source, kind };
 134        self.sources.push(source);
 135        cx.notify();
 136    }
 137
 138    /// If present, removes the local static source entry that has the given path,
 139    /// making corresponding task definitions unavailable in the fetch results.
 140    ///
 141    /// Now, entry for this path can be re-added again.
 142    pub fn remove_local_static_source(&mut self, abs_path: &Path) {
 143        self.sources.retain(|s| s.kind.abs_path() != Some(abs_path));
 144    }
 145
 146    /// If present, removes the worktree source entry that has the given worktree id,
 147    /// making corresponding task definitions unavailable in the fetch results.
 148    ///
 149    /// Now, entry for this path can be re-added again.
 150    pub fn remove_worktree_sources(&mut self, worktree: WorktreeId) {
 151        self.sources.retain(|s| s.kind.worktree() != Some(worktree));
 152    }
 153
 154    /// Pulls its task sources relevant to the worktree and the language given,
 155    /// returns all task templates with their source kinds, in no specific order.
 156    pub fn list_tasks(
 157        &self,
 158        file: Option<Arc<dyn File>>,
 159        language: Option<Arc<Language>>,
 160        worktree: Option<WorktreeId>,
 161        cx: &AppContext,
 162    ) -> Vec<(TaskSourceKind, TaskTemplate)> {
 163        let task_source_kind = language.as_ref().map(|language| TaskSourceKind::Language {
 164            name: language.name(),
 165        });
 166        let language_tasks = language
 167            .and_then(|language| language.context_provider()?.associated_tasks(file, cx))
 168            .into_iter()
 169            .flat_map(|tasks| tasks.0.into_iter())
 170            .flat_map(|task| Some((task_source_kind.as_ref()?, task)));
 171
 172        self.sources
 173            .iter()
 174            .filter(|source| {
 175                let source_worktree = source.kind.worktree();
 176                worktree.is_none() || source_worktree.is_none() || source_worktree == worktree
 177            })
 178            .flat_map(|source| {
 179                source
 180                    .source
 181                    .tasks_to_schedule()
 182                    .0
 183                    .into_iter()
 184                    .map(|task| (&source.kind, task))
 185            })
 186            .chain(language_tasks)
 187            .map(|(task_source_kind, task)| (task_source_kind.clone(), task))
 188            .collect()
 189    }
 190
 191    /// Pulls its task sources relevant to the worktree and the language given and resolves them with the [`TaskContext`] given.
 192    /// Joins the new resolutions with the resolved tasks that were used (spawned) before,
 193    /// orders them so that the most recently used come first, all equally used ones are ordered so that the most specific tasks come first.
 194    /// Deduplicates the tasks by their labels and splits the ordered list into two: used tasks and the rest, newly resolved tasks.
 195    pub fn used_and_current_resolved_tasks(
 196        &self,
 197        remote_templates_task: Option<Task<Result<Vec<(TaskSourceKind, TaskTemplate)>>>>,
 198        worktree: Option<WorktreeId>,
 199        location: Option<Location>,
 200        task_context: &TaskContext,
 201        cx: &AppContext,
 202    ) -> Task<(
 203        Vec<(TaskSourceKind, ResolvedTask)>,
 204        Vec<(TaskSourceKind, ResolvedTask)>,
 205    )> {
 206        let language = location
 207            .as_ref()
 208            .and_then(|location| location.buffer.read(cx).language_at(location.range.start));
 209        let task_source_kind = language.as_ref().map(|language| TaskSourceKind::Language {
 210            name: language.name(),
 211        });
 212        let file = location
 213            .as_ref()
 214            .and_then(|location| location.buffer.read(cx).file().cloned());
 215        let language_tasks = language
 216            .and_then(|language| language.context_provider()?.associated_tasks(file, cx))
 217            .into_iter()
 218            .flat_map(|tasks| tasks.0.into_iter())
 219            .flat_map(|task| Some((task_source_kind.as_ref()?, task)));
 220
 221        let mut lru_score = 0_u32;
 222        let mut task_usage = self
 223            .last_scheduled_tasks
 224            .iter()
 225            .rev()
 226            .filter(|(task_kind, _)| {
 227                if matches!(task_kind, TaskSourceKind::Language { .. }) {
 228                    Some(task_kind) == task_source_kind.as_ref()
 229                } else {
 230                    true
 231                }
 232            })
 233            .fold(
 234                BTreeMap::default(),
 235                |mut tasks, (task_source_kind, resolved_task)| {
 236                    tasks.entry(&resolved_task.id).or_insert_with(|| {
 237                        (task_source_kind, resolved_task, post_inc(&mut lru_score))
 238                    });
 239                    tasks
 240                },
 241            );
 242        let not_used_score = post_inc(&mut lru_score);
 243        let mut currently_resolved_tasks = self
 244            .sources
 245            .iter()
 246            .filter(|source| {
 247                let source_worktree = source.kind.worktree();
 248                worktree.is_none() || source_worktree.is_none() || source_worktree == worktree
 249            })
 250            .flat_map(|source| {
 251                source
 252                    .source
 253                    .tasks_to_schedule()
 254                    .0
 255                    .into_iter()
 256                    .map(|task| (&source.kind, task))
 257            })
 258            .chain(language_tasks.filter(|_| remote_templates_task.is_none()))
 259            .filter_map(|(kind, task)| {
 260                let id_base = kind.to_id_base();
 261                Some((kind, task.resolve_task(&id_base, task_context)?))
 262            })
 263            .map(|(kind, task)| {
 264                let lru_score = task_usage
 265                    .remove(&task.id)
 266                    .map(|(_, _, lru_score)| lru_score)
 267                    .unwrap_or(not_used_score);
 268                (kind.clone(), task, lru_score)
 269            })
 270            .collect::<Vec<_>>();
 271        let previously_spawned_tasks = task_usage
 272            .into_iter()
 273            .map(|(_, (kind, task, lru_score))| (kind.clone(), task.clone(), lru_score))
 274            .collect::<Vec<_>>();
 275
 276        let task_context = task_context.clone();
 277        cx.spawn(move |_| async move {
 278            let remote_templates = match remote_templates_task {
 279                Some(task) => match task.await.log_err() {
 280                    Some(remote_templates) => remote_templates,
 281                    None => return (Vec::new(), Vec::new()),
 282                },
 283                None => Vec::new(),
 284            };
 285            let remote_tasks = remote_templates.into_iter().filter_map(|(kind, task)| {
 286                let id_base = kind.to_id_base();
 287                Some((
 288                    kind,
 289                    task.resolve_task(&id_base, &task_context)?,
 290                    not_used_score,
 291                ))
 292            });
 293            currently_resolved_tasks.extend(remote_tasks);
 294
 295            let mut tasks_by_label = BTreeMap::default();
 296            tasks_by_label = previously_spawned_tasks.into_iter().fold(
 297                tasks_by_label,
 298                |mut tasks_by_label, (source, task, lru_score)| {
 299                    match tasks_by_label.entry((source, task.resolved_label.clone())) {
 300                        btree_map::Entry::Occupied(mut o) => {
 301                            let (_, previous_lru_score) = o.get();
 302                            if previous_lru_score >= &lru_score {
 303                                o.insert((task, lru_score));
 304                            }
 305                        }
 306                        btree_map::Entry::Vacant(v) => {
 307                            v.insert((task, lru_score));
 308                        }
 309                    }
 310                    tasks_by_label
 311                },
 312            );
 313            tasks_by_label = currently_resolved_tasks.iter().fold(
 314                tasks_by_label,
 315                |mut tasks_by_label, (source, task, lru_score)| {
 316                    match tasks_by_label.entry((source.clone(), task.resolved_label.clone())) {
 317                        btree_map::Entry::Occupied(mut o) => {
 318                            let (previous_task, _) = o.get();
 319                            let new_template = task.original_task();
 320                            if new_template != previous_task.original_task() {
 321                                o.insert((task.clone(), *lru_score));
 322                            }
 323                        }
 324                        btree_map::Entry::Vacant(v) => {
 325                            v.insert((task.clone(), *lru_score));
 326                        }
 327                    }
 328                    tasks_by_label
 329                },
 330            );
 331
 332            let resolved = tasks_by_label
 333                .into_iter()
 334                .map(|((kind, _), (task, lru_score))| (kind, task, lru_score))
 335                .sorted_by(task_lru_comparator)
 336                .filter_map(|(kind, task, lru_score)| {
 337                    if lru_score < not_used_score {
 338                        Some((kind, task))
 339                    } else {
 340                        None
 341                    }
 342                })
 343                .collect::<Vec<_>>();
 344
 345            (
 346                resolved,
 347                currently_resolved_tasks
 348                    .into_iter()
 349                    .sorted_unstable_by(task_lru_comparator)
 350                    .map(|(kind, task, _)| (kind, task))
 351                    .collect(),
 352            )
 353        })
 354    }
 355
 356    /// Returns the last scheduled task by task_id if provided.
 357    /// Otherwise, returns the last scheduled task.
 358    pub fn last_scheduled_task(
 359        &self,
 360        task_id: Option<&TaskId>,
 361    ) -> Option<(TaskSourceKind, ResolvedTask)> {
 362        if let Some(task_id) = task_id {
 363            self.last_scheduled_tasks
 364                .iter()
 365                .find(|(_, task)| &task.id == task_id)
 366                .cloned()
 367        } else {
 368            self.last_scheduled_tasks.back().cloned()
 369        }
 370    }
 371
 372    /// Registers task "usage" as being scheduled – to be used for LRU sorting when listing all tasks.
 373    pub fn task_scheduled(
 374        &mut self,
 375        task_source_kind: TaskSourceKind,
 376        resolved_task: ResolvedTask,
 377    ) {
 378        self.last_scheduled_tasks
 379            .push_back((task_source_kind, resolved_task));
 380        if self.last_scheduled_tasks.len() > 5_000 {
 381            self.last_scheduled_tasks.pop_front();
 382        }
 383    }
 384
 385    /// Deletes a resolved task from history, using its id.
 386    /// A similar may still resurface in `used_and_current_resolved_tasks` when its [`TaskTemplate`] is resolved again.
 387    pub fn delete_previously_used(&mut self, id: &TaskId) {
 388        self.last_scheduled_tasks.retain(|(_, task)| &task.id != id);
 389    }
 390}
 391
 392fn task_lru_comparator(
 393    (kind_a, task_a, lru_score_a): &(TaskSourceKind, ResolvedTask, u32),
 394    (kind_b, task_b, lru_score_b): &(TaskSourceKind, ResolvedTask, u32),
 395) -> cmp::Ordering {
 396    lru_score_a
 397        // First, display recently used templates above all.
 398        .cmp(lru_score_b)
 399        // Then, ensure more specific sources are displayed first.
 400        .then(task_source_kind_preference(kind_a).cmp(&task_source_kind_preference(kind_b)))
 401        // After that, display first more specific tasks, using more template variables.
 402        // Bonus points for tasks with symbol variables.
 403        .then(task_variables_preference(task_a).cmp(&task_variables_preference(task_b)))
 404        // Finally, sort by the resolved label, but a bit more specifically, to avoid mixing letters and digits.
 405        .then({
 406            NumericPrefixWithSuffix::from_numeric_prefixed_str(&task_a.resolved_label)
 407                .cmp(&NumericPrefixWithSuffix::from_numeric_prefixed_str(
 408                    &task_b.resolved_label,
 409                ))
 410                .then(task_a.resolved_label.cmp(&task_b.resolved_label))
 411                .then(kind_a.cmp(kind_b))
 412        })
 413}
 414
 415fn task_source_kind_preference(kind: &TaskSourceKind) -> u32 {
 416    match kind {
 417        TaskSourceKind::Language { .. } => 1,
 418        TaskSourceKind::UserInput => 2,
 419        TaskSourceKind::Worktree { .. } => 3,
 420        TaskSourceKind::AbsPath { .. } => 4,
 421    }
 422}
 423
 424fn task_variables_preference(task: &ResolvedTask) -> Reverse<usize> {
 425    let task_variables = task.substituted_variables();
 426    Reverse(if task_variables.contains(&VariableName::Symbol) {
 427        task_variables.len() + 1
 428    } else {
 429        task_variables.len()
 430    })
 431}
 432
 433#[cfg(test)]
 434mod test_inventory {
 435    use gpui::{AppContext, Model, TestAppContext};
 436    use itertools::Itertools;
 437    use task::{
 438        static_source::{StaticSource, TrackedFile},
 439        TaskContext, TaskTemplate, TaskTemplates,
 440    };
 441    use worktree::WorktreeId;
 442
 443    use crate::Inventory;
 444
 445    use super::{task_source_kind_preference, TaskSourceKind, UnboundedSender};
 446
 447    pub(super) fn static_test_source(
 448        task_names: impl IntoIterator<Item = String>,
 449        updates: UnboundedSender<()>,
 450        cx: &mut AppContext,
 451    ) -> StaticSource {
 452        let tasks = TaskTemplates(
 453            task_names
 454                .into_iter()
 455                .map(|name| TaskTemplate {
 456                    label: name,
 457                    command: "test command".to_owned(),
 458                    ..TaskTemplate::default()
 459                })
 460                .collect(),
 461        );
 462        let (tx, rx) = futures::channel::mpsc::unbounded();
 463        let file = TrackedFile::new(rx, updates, cx);
 464        tx.unbounded_send(serde_json::to_string(&tasks).unwrap())
 465            .unwrap();
 466        StaticSource::new(file)
 467    }
 468
 469    pub(super) fn task_template_names(
 470        inventory: &Model<Inventory>,
 471        worktree: Option<WorktreeId>,
 472        cx: &mut TestAppContext,
 473    ) -> Vec<String> {
 474        inventory.update(cx, |inventory, cx| {
 475            inventory
 476                .list_tasks(None, None, worktree, cx)
 477                .into_iter()
 478                .map(|(_, task)| task.label)
 479                .sorted()
 480                .collect()
 481        })
 482    }
 483
 484    pub(super) fn register_task_used(
 485        inventory: &Model<Inventory>,
 486        task_name: &str,
 487        cx: &mut TestAppContext,
 488    ) {
 489        inventory.update(cx, |inventory, cx| {
 490            let (task_source_kind, task) = inventory
 491                .list_tasks(None, None, None, cx)
 492                .into_iter()
 493                .find(|(_, task)| task.label == task_name)
 494                .unwrap_or_else(|| panic!("Failed to find task with name {task_name}"));
 495            let id_base = task_source_kind.to_id_base();
 496            inventory.task_scheduled(
 497                task_source_kind.clone(),
 498                task.resolve_task(&id_base, &TaskContext::default())
 499                    .unwrap_or_else(|| panic!("Failed to resolve task with name {task_name}")),
 500            );
 501        });
 502    }
 503
 504    pub(super) async fn list_tasks(
 505        inventory: &Model<Inventory>,
 506        worktree: Option<WorktreeId>,
 507        cx: &mut TestAppContext,
 508    ) -> Vec<(TaskSourceKind, String)> {
 509        let (used, current) = inventory
 510            .update(cx, |inventory, cx| {
 511                inventory.used_and_current_resolved_tasks(
 512                    None,
 513                    worktree,
 514                    None,
 515                    &TaskContext::default(),
 516                    cx,
 517                )
 518            })
 519            .await;
 520        let mut all = used;
 521        all.extend(current);
 522        all.into_iter()
 523            .map(|(source_kind, task)| (source_kind, task.resolved_label))
 524            .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
 525            .collect()
 526    }
 527}
 528
 529/// A context provided that tries to provide values for all non-custom [`VariableName`] variants for a currently opened file.
 530/// Applied as a base for every custom [`ContextProvider`] unless explicitly oped out.
 531pub struct BasicContextProvider {
 532    project: Model<Project>,
 533}
 534
 535impl BasicContextProvider {
 536    pub fn new(project: Model<Project>) -> Self {
 537        Self { project }
 538    }
 539}
 540
 541impl ContextProvider for BasicContextProvider {
 542    fn build_context(
 543        &self,
 544        _: &TaskVariables,
 545        location: &Location,
 546        cx: &mut AppContext,
 547    ) -> Result<TaskVariables> {
 548        let buffer = location.buffer.read(cx);
 549        let buffer_snapshot = buffer.snapshot();
 550        let symbols = buffer_snapshot.symbols_containing(location.range.start, None);
 551        let symbol = symbols.unwrap_or_default().last().map(|symbol| {
 552            let range = symbol
 553                .name_ranges
 554                .last()
 555                .cloned()
 556                .unwrap_or(0..symbol.text.len());
 557            symbol.text[range].to_string()
 558        });
 559
 560        let current_file = buffer
 561            .file()
 562            .and_then(|file| file.as_local())
 563            .map(|file| file.abs_path(cx).to_string_lossy().to_string());
 564        let Point { row, column } = location.range.start.to_point(&buffer_snapshot);
 565        let row = row + 1;
 566        let column = column + 1;
 567        let selected_text = buffer
 568            .chars_for_range(location.range.clone())
 569            .collect::<String>();
 570
 571        let mut task_variables = TaskVariables::from_iter([
 572            (VariableName::Row, row.to_string()),
 573            (VariableName::Column, column.to_string()),
 574        ]);
 575
 576        if let Some(symbol) = symbol {
 577            task_variables.insert(VariableName::Symbol, symbol);
 578        }
 579        if !selected_text.trim().is_empty() {
 580            task_variables.insert(VariableName::SelectedText, selected_text);
 581        }
 582        let worktree_abs_path =
 583            buffer
 584                .file()
 585                .map(|file| file.worktree_id(cx))
 586                .and_then(|worktree_id| {
 587                    self.project
 588                        .read(cx)
 589                        .worktree_for_id(worktree_id, cx)
 590                        .map(|worktree| worktree.read(cx).abs_path())
 591                });
 592        if let Some(worktree_path) = worktree_abs_path {
 593            task_variables.insert(
 594                VariableName::WorktreeRoot,
 595                worktree_path.to_string_lossy().to_string(),
 596            );
 597            if let Some(full_path) = current_file.as_ref() {
 598                let relative_path = pathdiff::diff_paths(full_path, worktree_path);
 599                if let Some(relative_path) = relative_path {
 600                    task_variables.insert(
 601                        VariableName::RelativeFile,
 602                        relative_path.to_string_lossy().into_owned(),
 603                    );
 604                }
 605            }
 606        }
 607
 608        if let Some(path_as_string) = current_file {
 609            let path = Path::new(&path_as_string);
 610            if let Some(filename) = path.file_name().and_then(|f| f.to_str()) {
 611                task_variables.insert(VariableName::Filename, String::from(filename));
 612            }
 613
 614            if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
 615                task_variables.insert(VariableName::Stem, stem.into());
 616            }
 617
 618            if let Some(dirname) = path.parent().and_then(|s| s.to_str()) {
 619                task_variables.insert(VariableName::Dirname, dirname.into());
 620            }
 621
 622            task_variables.insert(VariableName::File, path_as_string);
 623        }
 624
 625        Ok(task_variables)
 626    }
 627}
 628
 629/// A ContextProvider that doesn't provide any task variables on it's own, though it has some associated tasks.
 630pub struct ContextProviderWithTasks {
 631    templates: TaskTemplates,
 632}
 633
 634impl ContextProviderWithTasks {
 635    pub fn new(definitions: TaskTemplates) -> Self {
 636        Self {
 637            templates: definitions,
 638        }
 639    }
 640}
 641
 642impl ContextProvider for ContextProviderWithTasks {
 643    fn associated_tasks(
 644        &self,
 645        _: Option<Arc<dyn language::File>>,
 646        _: &AppContext,
 647    ) -> Option<TaskTemplates> {
 648        Some(self.templates.clone())
 649    }
 650}
 651
 652#[cfg(test)]
 653mod tests {
 654    use gpui::TestAppContext;
 655
 656    use super::test_inventory::*;
 657    use super::*;
 658
 659    #[gpui::test]
 660    async fn test_task_list_sorting(cx: &mut TestAppContext) {
 661        let inventory = cx.update(Inventory::new);
 662        let initial_tasks = resolved_task_names(&inventory, None, cx).await;
 663        assert!(
 664            initial_tasks.is_empty(),
 665            "No tasks expected for empty inventory, but got {initial_tasks:?}"
 666        );
 667        let initial_tasks = task_template_names(&inventory, None, cx);
 668        assert!(
 669            initial_tasks.is_empty(),
 670            "No tasks expected for empty inventory, but got {initial_tasks:?}"
 671        );
 672
 673        inventory.update(cx, |inventory, cx| {
 674            inventory.add_source(
 675                TaskSourceKind::UserInput,
 676                |tx, cx| static_test_source(vec!["3_task".to_string()], tx, cx),
 677                cx,
 678            );
 679        });
 680        inventory.update(cx, |inventory, cx| {
 681            inventory.add_source(
 682                TaskSourceKind::UserInput,
 683                |tx, cx| {
 684                    static_test_source(
 685                        vec![
 686                            "1_task".to_string(),
 687                            "2_task".to_string(),
 688                            "1_a_task".to_string(),
 689                        ],
 690                        tx,
 691                        cx,
 692                    )
 693                },
 694                cx,
 695            );
 696        });
 697        cx.run_until_parked();
 698        let expected_initial_state = [
 699            "1_a_task".to_string(),
 700            "1_task".to_string(),
 701            "2_task".to_string(),
 702            "3_task".to_string(),
 703        ];
 704        assert_eq!(
 705            task_template_names(&inventory, None, cx),
 706            &expected_initial_state,
 707        );
 708        assert_eq!(
 709            resolved_task_names(&inventory, None, cx).await,
 710            &expected_initial_state,
 711            "Tasks with equal amount of usages should be sorted alphanumerically"
 712        );
 713
 714        register_task_used(&inventory, "2_task", cx);
 715        assert_eq!(
 716            task_template_names(&inventory, None, cx),
 717            &expected_initial_state,
 718        );
 719        assert_eq!(
 720            resolved_task_names(&inventory, None, cx).await,
 721            vec![
 722                "2_task".to_string(),
 723                "2_task".to_string(),
 724                "1_a_task".to_string(),
 725                "1_task".to_string(),
 726                "3_task".to_string()
 727            ],
 728        );
 729
 730        register_task_used(&inventory, "1_task", cx);
 731        register_task_used(&inventory, "1_task", cx);
 732        register_task_used(&inventory, "1_task", cx);
 733        register_task_used(&inventory, "3_task", cx);
 734        assert_eq!(
 735            task_template_names(&inventory, None, cx),
 736            &expected_initial_state,
 737        );
 738        assert_eq!(
 739            resolved_task_names(&inventory, None, cx).await,
 740            vec![
 741                "3_task".to_string(),
 742                "1_task".to_string(),
 743                "2_task".to_string(),
 744                "3_task".to_string(),
 745                "1_task".to_string(),
 746                "2_task".to_string(),
 747                "1_a_task".to_string(),
 748            ],
 749        );
 750
 751        inventory.update(cx, |inventory, cx| {
 752            inventory.add_source(
 753                TaskSourceKind::UserInput,
 754                |tx, cx| {
 755                    static_test_source(vec!["10_hello".to_string(), "11_hello".to_string()], tx, cx)
 756                },
 757                cx,
 758            );
 759        });
 760        cx.run_until_parked();
 761        let expected_updated_state = [
 762            "10_hello".to_string(),
 763            "11_hello".to_string(),
 764            "1_a_task".to_string(),
 765            "1_task".to_string(),
 766            "2_task".to_string(),
 767            "3_task".to_string(),
 768        ];
 769        assert_eq!(
 770            task_template_names(&inventory, None, cx),
 771            &expected_updated_state,
 772        );
 773        assert_eq!(
 774            resolved_task_names(&inventory, None, cx).await,
 775            vec![
 776                "3_task".to_string(),
 777                "1_task".to_string(),
 778                "2_task".to_string(),
 779                "3_task".to_string(),
 780                "1_task".to_string(),
 781                "2_task".to_string(),
 782                "1_a_task".to_string(),
 783                "10_hello".to_string(),
 784                "11_hello".to_string(),
 785            ],
 786        );
 787
 788        register_task_used(&inventory, "11_hello", cx);
 789        assert_eq!(
 790            task_template_names(&inventory, None, cx),
 791            &expected_updated_state,
 792        );
 793        assert_eq!(
 794            resolved_task_names(&inventory, None, cx).await,
 795            vec![
 796                "11_hello".to_string(),
 797                "3_task".to_string(),
 798                "1_task".to_string(),
 799                "2_task".to_string(),
 800                "11_hello".to_string(),
 801                "3_task".to_string(),
 802                "1_task".to_string(),
 803                "2_task".to_string(),
 804                "1_a_task".to_string(),
 805                "10_hello".to_string(),
 806            ],
 807        );
 808    }
 809
 810    #[gpui::test]
 811    async fn test_inventory_static_task_filters(cx: &mut TestAppContext) {
 812        let inventory_with_statics = cx.update(Inventory::new);
 813        let common_name = "common_task_name";
 814        let path_1 = Path::new("path_1");
 815        let path_2 = Path::new("path_2");
 816        let worktree_1 = WorktreeId::from_usize(1);
 817        let worktree_path_1 = Path::new("worktree_path_1");
 818        let worktree_2 = WorktreeId::from_usize(2);
 819        let worktree_path_2 = Path::new("worktree_path_2");
 820
 821        inventory_with_statics.update(cx, |inventory, cx| {
 822            inventory.add_source(
 823                TaskSourceKind::UserInput,
 824                |tx, cx| {
 825                    static_test_source(
 826                        vec!["user_input".to_string(), common_name.to_string()],
 827                        tx,
 828                        cx,
 829                    )
 830                },
 831                cx,
 832            );
 833            inventory.add_source(
 834                TaskSourceKind::AbsPath {
 835                    id_base: "test source".into(),
 836                    abs_path: path_1.to_path_buf(),
 837                },
 838                |tx, cx| {
 839                    static_test_source(
 840                        vec!["static_source_1".to_string(), common_name.to_string()],
 841                        tx,
 842                        cx,
 843                    )
 844                },
 845                cx,
 846            );
 847            inventory.add_source(
 848                TaskSourceKind::AbsPath {
 849                    id_base: "test source".into(),
 850                    abs_path: path_2.to_path_buf(),
 851                },
 852                |tx, cx| {
 853                    static_test_source(
 854                        vec!["static_source_2".to_string(), common_name.to_string()],
 855                        tx,
 856                        cx,
 857                    )
 858                },
 859                cx,
 860            );
 861            inventory.add_source(
 862                TaskSourceKind::Worktree {
 863                    id: worktree_1,
 864                    abs_path: worktree_path_1.to_path_buf(),
 865                    id_base: "test_source".into(),
 866                },
 867                |tx, cx| {
 868                    static_test_source(
 869                        vec!["worktree_1".to_string(), common_name.to_string()],
 870                        tx,
 871                        cx,
 872                    )
 873                },
 874                cx,
 875            );
 876            inventory.add_source(
 877                TaskSourceKind::Worktree {
 878                    id: worktree_2,
 879                    abs_path: worktree_path_2.to_path_buf(),
 880                    id_base: "test_source".into(),
 881                },
 882                |tx, cx| {
 883                    static_test_source(
 884                        vec!["worktree_2".to_string(), common_name.to_string()],
 885                        tx,
 886                        cx,
 887                    )
 888                },
 889                cx,
 890            );
 891        });
 892        cx.run_until_parked();
 893        let worktree_independent_tasks = vec![
 894            (
 895                TaskSourceKind::AbsPath {
 896                    id_base: "test source".into(),
 897                    abs_path: path_1.to_path_buf(),
 898                },
 899                "static_source_1".to_string(),
 900            ),
 901            (
 902                TaskSourceKind::AbsPath {
 903                    id_base: "test source".into(),
 904                    abs_path: path_1.to_path_buf(),
 905                },
 906                common_name.to_string(),
 907            ),
 908            (
 909                TaskSourceKind::AbsPath {
 910                    id_base: "test source".into(),
 911                    abs_path: path_2.to_path_buf(),
 912                },
 913                common_name.to_string(),
 914            ),
 915            (
 916                TaskSourceKind::AbsPath {
 917                    id_base: "test source".into(),
 918                    abs_path: path_2.to_path_buf(),
 919                },
 920                "static_source_2".to_string(),
 921            ),
 922            (TaskSourceKind::UserInput, common_name.to_string()),
 923            (TaskSourceKind::UserInput, "user_input".to_string()),
 924        ];
 925        let worktree_1_tasks = [
 926            (
 927                TaskSourceKind::Worktree {
 928                    id: worktree_1,
 929                    abs_path: worktree_path_1.to_path_buf(),
 930                    id_base: "test_source".into(),
 931                },
 932                common_name.to_string(),
 933            ),
 934            (
 935                TaskSourceKind::Worktree {
 936                    id: worktree_1,
 937                    abs_path: worktree_path_1.to_path_buf(),
 938                    id_base: "test_source".into(),
 939                },
 940                "worktree_1".to_string(),
 941            ),
 942        ];
 943        let worktree_2_tasks = [
 944            (
 945                TaskSourceKind::Worktree {
 946                    id: worktree_2,
 947                    abs_path: worktree_path_2.to_path_buf(),
 948                    id_base: "test_source".into(),
 949                },
 950                common_name.to_string(),
 951            ),
 952            (
 953                TaskSourceKind::Worktree {
 954                    id: worktree_2,
 955                    abs_path: worktree_path_2.to_path_buf(),
 956                    id_base: "test_source".into(),
 957                },
 958                "worktree_2".to_string(),
 959            ),
 960        ];
 961
 962        let all_tasks = worktree_1_tasks
 963            .iter()
 964            .chain(worktree_2_tasks.iter())
 965            // worktree-less tasks come later in the list
 966            .chain(worktree_independent_tasks.iter())
 967            .cloned()
 968            .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
 969            .collect::<Vec<_>>();
 970
 971        assert_eq!(
 972            list_tasks(&inventory_with_statics, None, cx).await,
 973            all_tasks
 974        );
 975        assert_eq!(
 976            list_tasks(&inventory_with_statics, Some(worktree_1), cx).await,
 977            worktree_1_tasks
 978                .iter()
 979                .chain(worktree_independent_tasks.iter())
 980                .cloned()
 981                .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
 982                .collect::<Vec<_>>(),
 983        );
 984        assert_eq!(
 985            list_tasks(&inventory_with_statics, Some(worktree_2), cx).await,
 986            worktree_2_tasks
 987                .iter()
 988                .chain(worktree_independent_tasks.iter())
 989                .cloned()
 990                .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
 991                .collect::<Vec<_>>(),
 992        );
 993    }
 994
 995    pub(super) async fn resolved_task_names(
 996        inventory: &Model<Inventory>,
 997        worktree: Option<WorktreeId>,
 998        cx: &mut TestAppContext,
 999    ) -> Vec<String> {
1000        let (used, current) = inventory
1001            .update(cx, |inventory, cx| {
1002                inventory.used_and_current_resolved_tasks(
1003                    None,
1004                    worktree,
1005                    None,
1006                    &TaskContext::default(),
1007                    cx,
1008                )
1009            })
1010            .await;
1011        used.into_iter()
1012            .chain(current)
1013            .map(|(_, task)| task.original_task().label.clone())
1014            .collect()
1015    }
1016}