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, HashMap, 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().0,
 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().0,
 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        _: Option<&HashMap<String, String>>,
 547        cx: &mut AppContext,
 548    ) -> Result<TaskVariables> {
 549        let buffer = location.buffer.read(cx);
 550        let buffer_snapshot = buffer.snapshot();
 551        let symbols = buffer_snapshot.symbols_containing(location.range.start, None);
 552        let symbol = symbols.unwrap_or_default().last().map(|symbol| {
 553            let range = symbol
 554                .name_ranges
 555                .last()
 556                .cloned()
 557                .unwrap_or(0..symbol.text.len());
 558            symbol.text[range].to_string()
 559        });
 560
 561        let current_file = buffer
 562            .file()
 563            .and_then(|file| file.as_local())
 564            .map(|file| file.abs_path(cx).to_string_lossy().to_string());
 565        let Point { row, column } = location.range.start.to_point(&buffer_snapshot);
 566        let row = row + 1;
 567        let column = column + 1;
 568        let selected_text = buffer
 569            .chars_for_range(location.range.clone())
 570            .collect::<String>();
 571
 572        let mut task_variables = TaskVariables::from_iter([
 573            (VariableName::Row, row.to_string()),
 574            (VariableName::Column, column.to_string()),
 575        ]);
 576
 577        if let Some(symbol) = symbol {
 578            task_variables.insert(VariableName::Symbol, symbol);
 579        }
 580        if !selected_text.trim().is_empty() {
 581            task_variables.insert(VariableName::SelectedText, selected_text);
 582        }
 583        let worktree_abs_path =
 584            buffer
 585                .file()
 586                .map(|file| file.worktree_id(cx))
 587                .and_then(|worktree_id| {
 588                    self.project
 589                        .read(cx)
 590                        .worktree_for_id(worktree_id, cx)
 591                        .map(|worktree| worktree.read(cx).abs_path())
 592                });
 593        if let Some(worktree_path) = worktree_abs_path {
 594            task_variables.insert(
 595                VariableName::WorktreeRoot,
 596                worktree_path.to_string_lossy().to_string(),
 597            );
 598            if let Some(full_path) = current_file.as_ref() {
 599                let relative_path = pathdiff::diff_paths(full_path, worktree_path);
 600                if let Some(relative_path) = relative_path {
 601                    task_variables.insert(
 602                        VariableName::RelativeFile,
 603                        relative_path.to_string_lossy().into_owned(),
 604                    );
 605                }
 606            }
 607        }
 608
 609        if let Some(path_as_string) = current_file {
 610            let path = Path::new(&path_as_string);
 611            if let Some(filename) = path.file_name().and_then(|f| f.to_str()) {
 612                task_variables.insert(VariableName::Filename, String::from(filename));
 613            }
 614
 615            if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
 616                task_variables.insert(VariableName::Stem, stem.into());
 617            }
 618
 619            if let Some(dirname) = path.parent().and_then(|s| s.to_str()) {
 620                task_variables.insert(VariableName::Dirname, dirname.into());
 621            }
 622
 623            task_variables.insert(VariableName::File, path_as_string);
 624        }
 625
 626        Ok(task_variables)
 627    }
 628}
 629
 630/// A ContextProvider that doesn't provide any task variables on it's own, though it has some associated tasks.
 631pub struct ContextProviderWithTasks {
 632    templates: TaskTemplates,
 633}
 634
 635impl ContextProviderWithTasks {
 636    pub fn new(definitions: TaskTemplates) -> Self {
 637        Self {
 638            templates: definitions,
 639        }
 640    }
 641}
 642
 643impl ContextProvider for ContextProviderWithTasks {
 644    fn associated_tasks(
 645        &self,
 646        _: Option<Arc<dyn language::File>>,
 647        _: &AppContext,
 648    ) -> Option<TaskTemplates> {
 649        Some(self.templates.clone())
 650    }
 651}
 652
 653#[cfg(test)]
 654mod tests {
 655    use gpui::TestAppContext;
 656
 657    use super::test_inventory::*;
 658    use super::*;
 659
 660    #[gpui::test]
 661    async fn test_task_list_sorting(cx: &mut TestAppContext) {
 662        let inventory = cx.update(Inventory::new);
 663        let initial_tasks = resolved_task_names(&inventory, None, cx).await;
 664        assert!(
 665            initial_tasks.is_empty(),
 666            "No tasks expected for empty inventory, but got {initial_tasks:?}"
 667        );
 668        let initial_tasks = task_template_names(&inventory, None, cx);
 669        assert!(
 670            initial_tasks.is_empty(),
 671            "No tasks expected for empty inventory, but got {initial_tasks:?}"
 672        );
 673
 674        inventory.update(cx, |inventory, cx| {
 675            inventory.add_source(
 676                TaskSourceKind::UserInput,
 677                |tx, cx| static_test_source(vec!["3_task".to_string()], tx, cx),
 678                cx,
 679            );
 680        });
 681        inventory.update(cx, |inventory, cx| {
 682            inventory.add_source(
 683                TaskSourceKind::UserInput,
 684                |tx, cx| {
 685                    static_test_source(
 686                        vec![
 687                            "1_task".to_string(),
 688                            "2_task".to_string(),
 689                            "1_a_task".to_string(),
 690                        ],
 691                        tx,
 692                        cx,
 693                    )
 694                },
 695                cx,
 696            );
 697        });
 698        cx.run_until_parked();
 699        let expected_initial_state = [
 700            "1_a_task".to_string(),
 701            "1_task".to_string(),
 702            "2_task".to_string(),
 703            "3_task".to_string(),
 704        ];
 705        assert_eq!(
 706            task_template_names(&inventory, None, cx),
 707            &expected_initial_state,
 708        );
 709        assert_eq!(
 710            resolved_task_names(&inventory, None, cx).await,
 711            &expected_initial_state,
 712            "Tasks with equal amount of usages should be sorted alphanumerically"
 713        );
 714
 715        register_task_used(&inventory, "2_task", cx);
 716        assert_eq!(
 717            task_template_names(&inventory, None, cx),
 718            &expected_initial_state,
 719        );
 720        assert_eq!(
 721            resolved_task_names(&inventory, None, cx).await,
 722            vec![
 723                "2_task".to_string(),
 724                "2_task".to_string(),
 725                "1_a_task".to_string(),
 726                "1_task".to_string(),
 727                "3_task".to_string()
 728            ],
 729        );
 730
 731        register_task_used(&inventory, "1_task", cx);
 732        register_task_used(&inventory, "1_task", cx);
 733        register_task_used(&inventory, "1_task", cx);
 734        register_task_used(&inventory, "3_task", cx);
 735        assert_eq!(
 736            task_template_names(&inventory, None, cx),
 737            &expected_initial_state,
 738        );
 739        assert_eq!(
 740            resolved_task_names(&inventory, None, cx).await,
 741            vec![
 742                "3_task".to_string(),
 743                "1_task".to_string(),
 744                "2_task".to_string(),
 745                "3_task".to_string(),
 746                "1_task".to_string(),
 747                "2_task".to_string(),
 748                "1_a_task".to_string(),
 749            ],
 750        );
 751
 752        inventory.update(cx, |inventory, cx| {
 753            inventory.add_source(
 754                TaskSourceKind::UserInput,
 755                |tx, cx| {
 756                    static_test_source(vec!["10_hello".to_string(), "11_hello".to_string()], tx, cx)
 757                },
 758                cx,
 759            );
 760        });
 761        cx.run_until_parked();
 762        let expected_updated_state = [
 763            "10_hello".to_string(),
 764            "11_hello".to_string(),
 765            "1_a_task".to_string(),
 766            "1_task".to_string(),
 767            "2_task".to_string(),
 768            "3_task".to_string(),
 769        ];
 770        assert_eq!(
 771            task_template_names(&inventory, None, cx),
 772            &expected_updated_state,
 773        );
 774        assert_eq!(
 775            resolved_task_names(&inventory, None, cx).await,
 776            vec![
 777                "3_task".to_string(),
 778                "1_task".to_string(),
 779                "2_task".to_string(),
 780                "3_task".to_string(),
 781                "1_task".to_string(),
 782                "2_task".to_string(),
 783                "1_a_task".to_string(),
 784                "10_hello".to_string(),
 785                "11_hello".to_string(),
 786            ],
 787        );
 788
 789        register_task_used(&inventory, "11_hello", cx);
 790        assert_eq!(
 791            task_template_names(&inventory, None, cx),
 792            &expected_updated_state,
 793        );
 794        assert_eq!(
 795            resolved_task_names(&inventory, None, cx).await,
 796            vec![
 797                "11_hello".to_string(),
 798                "3_task".to_string(),
 799                "1_task".to_string(),
 800                "2_task".to_string(),
 801                "11_hello".to_string(),
 802                "3_task".to_string(),
 803                "1_task".to_string(),
 804                "2_task".to_string(),
 805                "1_a_task".to_string(),
 806                "10_hello".to_string(),
 807            ],
 808        );
 809    }
 810
 811    #[gpui::test]
 812    async fn test_inventory_static_task_filters(cx: &mut TestAppContext) {
 813        let inventory_with_statics = cx.update(Inventory::new);
 814        let common_name = "common_task_name";
 815        let path_1 = Path::new("path_1");
 816        let path_2 = Path::new("path_2");
 817        let worktree_1 = WorktreeId::from_usize(1);
 818        let worktree_path_1 = Path::new("worktree_path_1");
 819        let worktree_2 = WorktreeId::from_usize(2);
 820        let worktree_path_2 = Path::new("worktree_path_2");
 821
 822        inventory_with_statics.update(cx, |inventory, cx| {
 823            inventory.add_source(
 824                TaskSourceKind::UserInput,
 825                |tx, cx| {
 826                    static_test_source(
 827                        vec!["user_input".to_string(), common_name.to_string()],
 828                        tx,
 829                        cx,
 830                    )
 831                },
 832                cx,
 833            );
 834            inventory.add_source(
 835                TaskSourceKind::AbsPath {
 836                    id_base: "test source".into(),
 837                    abs_path: path_1.to_path_buf(),
 838                },
 839                |tx, cx| {
 840                    static_test_source(
 841                        vec!["static_source_1".to_string(), common_name.to_string()],
 842                        tx,
 843                        cx,
 844                    )
 845                },
 846                cx,
 847            );
 848            inventory.add_source(
 849                TaskSourceKind::AbsPath {
 850                    id_base: "test source".into(),
 851                    abs_path: path_2.to_path_buf(),
 852                },
 853                |tx, cx| {
 854                    static_test_source(
 855                        vec!["static_source_2".to_string(), common_name.to_string()],
 856                        tx,
 857                        cx,
 858                    )
 859                },
 860                cx,
 861            );
 862            inventory.add_source(
 863                TaskSourceKind::Worktree {
 864                    id: worktree_1,
 865                    abs_path: worktree_path_1.to_path_buf(),
 866                    id_base: "test_source".into(),
 867                },
 868                |tx, cx| {
 869                    static_test_source(
 870                        vec!["worktree_1".to_string(), common_name.to_string()],
 871                        tx,
 872                        cx,
 873                    )
 874                },
 875                cx,
 876            );
 877            inventory.add_source(
 878                TaskSourceKind::Worktree {
 879                    id: worktree_2,
 880                    abs_path: worktree_path_2.to_path_buf(),
 881                    id_base: "test_source".into(),
 882                },
 883                |tx, cx| {
 884                    static_test_source(
 885                        vec!["worktree_2".to_string(), common_name.to_string()],
 886                        tx,
 887                        cx,
 888                    )
 889                },
 890                cx,
 891            );
 892        });
 893        cx.run_until_parked();
 894        let worktree_independent_tasks = vec![
 895            (
 896                TaskSourceKind::AbsPath {
 897                    id_base: "test source".into(),
 898                    abs_path: path_1.to_path_buf(),
 899                },
 900                "static_source_1".to_string(),
 901            ),
 902            (
 903                TaskSourceKind::AbsPath {
 904                    id_base: "test source".into(),
 905                    abs_path: path_1.to_path_buf(),
 906                },
 907                common_name.to_string(),
 908            ),
 909            (
 910                TaskSourceKind::AbsPath {
 911                    id_base: "test source".into(),
 912                    abs_path: path_2.to_path_buf(),
 913                },
 914                common_name.to_string(),
 915            ),
 916            (
 917                TaskSourceKind::AbsPath {
 918                    id_base: "test source".into(),
 919                    abs_path: path_2.to_path_buf(),
 920                },
 921                "static_source_2".to_string(),
 922            ),
 923            (TaskSourceKind::UserInput, common_name.to_string()),
 924            (TaskSourceKind::UserInput, "user_input".to_string()),
 925        ];
 926        let worktree_1_tasks = [
 927            (
 928                TaskSourceKind::Worktree {
 929                    id: worktree_1,
 930                    abs_path: worktree_path_1.to_path_buf(),
 931                    id_base: "test_source".into(),
 932                },
 933                common_name.to_string(),
 934            ),
 935            (
 936                TaskSourceKind::Worktree {
 937                    id: worktree_1,
 938                    abs_path: worktree_path_1.to_path_buf(),
 939                    id_base: "test_source".into(),
 940                },
 941                "worktree_1".to_string(),
 942            ),
 943        ];
 944        let worktree_2_tasks = [
 945            (
 946                TaskSourceKind::Worktree {
 947                    id: worktree_2,
 948                    abs_path: worktree_path_2.to_path_buf(),
 949                    id_base: "test_source".into(),
 950                },
 951                common_name.to_string(),
 952            ),
 953            (
 954                TaskSourceKind::Worktree {
 955                    id: worktree_2,
 956                    abs_path: worktree_path_2.to_path_buf(),
 957                    id_base: "test_source".into(),
 958                },
 959                "worktree_2".to_string(),
 960            ),
 961        ];
 962
 963        let all_tasks = worktree_1_tasks
 964            .iter()
 965            .chain(worktree_2_tasks.iter())
 966            // worktree-less tasks come later in the list
 967            .chain(worktree_independent_tasks.iter())
 968            .cloned()
 969            .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
 970            .collect::<Vec<_>>();
 971
 972        assert_eq!(
 973            list_tasks(&inventory_with_statics, None, cx).await,
 974            all_tasks
 975        );
 976        assert_eq!(
 977            list_tasks(&inventory_with_statics, Some(worktree_1), cx).await,
 978            worktree_1_tasks
 979                .iter()
 980                .chain(worktree_independent_tasks.iter())
 981                .cloned()
 982                .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
 983                .collect::<Vec<_>>(),
 984        );
 985        assert_eq!(
 986            list_tasks(&inventory_with_statics, Some(worktree_2), cx).await,
 987            worktree_2_tasks
 988                .iter()
 989                .chain(worktree_independent_tasks.iter())
 990                .cloned()
 991                .sorted_by_key(|(kind, label)| (task_source_kind_preference(kind), label.clone()))
 992                .collect::<Vec<_>>(),
 993        );
 994    }
 995
 996    pub(super) async fn resolved_task_names(
 997        inventory: &Model<Inventory>,
 998        worktree: Option<WorktreeId>,
 999        cx: &mut TestAppContext,
1000    ) -> Vec<String> {
1001        let (used, current) = inventory
1002            .update(cx, |inventory, cx| {
1003                inventory.used_and_current_resolved_tasks(
1004                    None,
1005                    worktree,
1006                    None,
1007                    &TaskContext::default(),
1008                    cx,
1009                )
1010            })
1011            .await;
1012        used.into_iter()
1013            .chain(current)
1014            .map(|(_, task)| task.original_task().label.clone())
1015            .collect()
1016    }
1017}