extension_host.rs

   1pub mod extension_lsp_adapter;
   2pub mod extension_settings;
   3pub mod wasm_host;
   4
   5#[cfg(test)]
   6mod extension_store_test;
   7
   8use crate::{extension_lsp_adapter::ExtensionLspAdapter, wasm_host::wit};
   9use anyhow::{anyhow, bail, Context as _, Result};
  10use async_compression::futures::bufread::GzipDecoder;
  11use async_tar::Archive;
  12use client::{telemetry::Telemetry, Client, ExtensionMetadata, GetExtensionsResponse};
  13use collections::{btree_map, BTreeMap, HashSet};
  14use extension::extension_builder::{CompileExtensionOptions, ExtensionBuilder};
  15use extension::Extension;
  16pub use extension::ExtensionManifest;
  17use fs::{Fs, RemoveOptions};
  18use futures::{
  19    channel::{
  20        mpsc::{unbounded, UnboundedSender},
  21        oneshot,
  22    },
  23    io::BufReader,
  24    select_biased, AsyncReadExt as _, Future, FutureExt as _, StreamExt as _,
  25};
  26use gpui::{
  27    actions, AppContext, AsyncAppContext, Context, EventEmitter, Global, Model, ModelContext,
  28    SharedString, Task, WeakModel,
  29};
  30use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
  31use language::{
  32    LanguageConfig, LanguageMatcher, LanguageName, LanguageQueries, LoadedLanguage,
  33    QUERY_FILENAME_PREFIXES,
  34};
  35use lsp::LanguageServerName;
  36use node_runtime::NodeRuntime;
  37use project::ContextProviderWithTasks;
  38use release_channel::ReleaseChannel;
  39use semantic_version::SemanticVersion;
  40use serde::{Deserialize, Serialize};
  41use settings::Settings;
  42use std::ops::RangeInclusive;
  43use std::str::FromStr;
  44use std::{
  45    cmp::Ordering,
  46    path::{self, Path, PathBuf},
  47    sync::Arc,
  48    time::{Duration, Instant},
  49};
  50use url::Url;
  51use util::ResultExt;
  52use wasm_host::{
  53    wit::{is_supported_wasm_api_version, wasm_api_version_range},
  54    WasmExtension, WasmHost,
  55};
  56
  57pub use extension::{
  58    ExtensionLibraryKind, GrammarManifestEntry, OldExtensionManifest, SchemaVersion,
  59};
  60pub use extension_settings::ExtensionSettings;
  61
  62pub const RELOAD_DEBOUNCE_DURATION: Duration = Duration::from_millis(200);
  63const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
  64
  65/// The current extension [`SchemaVersion`] supported by Zed.
  66const CURRENT_SCHEMA_VERSION: SchemaVersion = SchemaVersion(1);
  67
  68/// Returns the [`SchemaVersion`] range that is compatible with this version of Zed.
  69pub fn schema_version_range() -> RangeInclusive<SchemaVersion> {
  70    SchemaVersion::ZERO..=CURRENT_SCHEMA_VERSION
  71}
  72
  73/// Returns whether the given extension version is compatible with this version of Zed.
  74pub fn is_version_compatible(
  75    release_channel: ReleaseChannel,
  76    extension_version: &ExtensionMetadata,
  77) -> bool {
  78    let schema_version = extension_version.manifest.schema_version.unwrap_or(0);
  79    if CURRENT_SCHEMA_VERSION.0 < schema_version {
  80        return false;
  81    }
  82
  83    if let Some(wasm_api_version) = extension_version
  84        .manifest
  85        .wasm_api_version
  86        .as_ref()
  87        .and_then(|wasm_api_version| SemanticVersion::from_str(wasm_api_version).ok())
  88    {
  89        if !is_supported_wasm_api_version(release_channel, wasm_api_version) {
  90            return false;
  91        }
  92    }
  93
  94    true
  95}
  96
  97pub trait ExtensionRegistrationHooks: Send + Sync + 'static {
  98    fn remove_user_themes(&self, _themes: Vec<SharedString>) {}
  99
 100    fn load_user_theme(&self, _theme_path: PathBuf, _fs: Arc<dyn Fs>) -> Task<Result<()>> {
 101        Task::ready(Ok(()))
 102    }
 103
 104    fn list_theme_names(
 105        &self,
 106        _theme_path: PathBuf,
 107        _fs: Arc<dyn Fs>,
 108    ) -> Task<Result<Vec<String>>> {
 109        Task::ready(Ok(Vec::new()))
 110    }
 111
 112    fn reload_current_theme(&self, _cx: &mut AppContext) {}
 113
 114    fn register_language(
 115        &self,
 116        _language: LanguageName,
 117        _grammar: Option<Arc<str>>,
 118        _matcher: language::LanguageMatcher,
 119        _load: Arc<dyn Fn() -> Result<LoadedLanguage> + 'static + Send + Sync>,
 120    ) {
 121    }
 122
 123    fn register_lsp_adapter(&self, _language: LanguageName, _adapter: ExtensionLspAdapter) {}
 124
 125    fn remove_lsp_adapter(&self, _language: &LanguageName, _server_name: &LanguageServerName) {}
 126
 127    fn register_wasm_grammars(&self, _grammars: Vec<(Arc<str>, PathBuf)>) {}
 128
 129    fn remove_languages(
 130        &self,
 131        _languages_to_remove: &[LanguageName],
 132        _grammars_to_remove: &[Arc<str>],
 133    ) {
 134    }
 135
 136    fn register_slash_command(
 137        &self,
 138        _extension: Arc<dyn Extension>,
 139        _command: extension::SlashCommand,
 140    ) {
 141    }
 142
 143    fn register_context_server(
 144        &self,
 145        _id: Arc<str>,
 146        _extension: WasmExtension,
 147        _cx: &mut AppContext,
 148    ) {
 149    }
 150
 151    fn register_docs_provider(&self, _extension: Arc<dyn Extension>, _provider_id: Arc<str>) {}
 152
 153    fn register_snippets(&self, _path: &PathBuf, _snippet_contents: &str) -> Result<()> {
 154        Ok(())
 155    }
 156
 157    fn update_lsp_status(
 158        &self,
 159        _server_name: lsp::LanguageServerName,
 160        _status: language::LanguageServerBinaryStatus,
 161    ) {
 162    }
 163}
 164
 165pub struct ExtensionStore {
 166    pub registration_hooks: Arc<dyn ExtensionRegistrationHooks>,
 167    pub builder: Arc<ExtensionBuilder>,
 168    pub extension_index: ExtensionIndex,
 169    pub fs: Arc<dyn Fs>,
 170    pub http_client: Arc<HttpClientWithUrl>,
 171    pub telemetry: Option<Arc<Telemetry>>,
 172    pub reload_tx: UnboundedSender<Option<Arc<str>>>,
 173    pub reload_complete_senders: Vec<oneshot::Sender<()>>,
 174    pub installed_dir: PathBuf,
 175    pub outstanding_operations: BTreeMap<Arc<str>, ExtensionOperation>,
 176    pub index_path: PathBuf,
 177    pub modified_extensions: HashSet<Arc<str>>,
 178    pub wasm_host: Arc<WasmHost>,
 179    pub wasm_extensions: Vec<(Arc<ExtensionManifest>, WasmExtension)>,
 180    pub tasks: Vec<Task<()>>,
 181}
 182
 183#[derive(Clone, Copy)]
 184pub enum ExtensionOperation {
 185    Upgrade,
 186    Install,
 187    Remove,
 188}
 189
 190#[derive(Clone)]
 191pub enum Event {
 192    ExtensionsUpdated,
 193    StartedReloading,
 194    ExtensionInstalled(Arc<str>),
 195    ExtensionFailedToLoad(Arc<str>),
 196}
 197
 198impl EventEmitter<Event> for ExtensionStore {}
 199
 200struct GlobalExtensionStore(Model<ExtensionStore>);
 201
 202impl Global for GlobalExtensionStore {}
 203
 204#[derive(Debug, Deserialize, Serialize, Default, PartialEq, Eq)]
 205pub struct ExtensionIndex {
 206    pub extensions: BTreeMap<Arc<str>, ExtensionIndexEntry>,
 207    pub themes: BTreeMap<Arc<str>, ExtensionIndexThemeEntry>,
 208    pub languages: BTreeMap<LanguageName, ExtensionIndexLanguageEntry>,
 209}
 210
 211#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
 212pub struct ExtensionIndexEntry {
 213    pub manifest: Arc<ExtensionManifest>,
 214    pub dev: bool,
 215}
 216
 217#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
 218pub struct ExtensionIndexThemeEntry {
 219    pub extension: Arc<str>,
 220    pub path: PathBuf,
 221}
 222
 223#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
 224pub struct ExtensionIndexLanguageEntry {
 225    pub extension: Arc<str>,
 226    pub path: PathBuf,
 227    pub matcher: LanguageMatcher,
 228    pub grammar: Option<Arc<str>>,
 229}
 230
 231actions!(zed, [ReloadExtensions]);
 232
 233pub fn init(
 234    registration_hooks: Arc<dyn ExtensionRegistrationHooks>,
 235    fs: Arc<dyn Fs>,
 236    client: Arc<Client>,
 237    node_runtime: NodeRuntime,
 238    cx: &mut AppContext,
 239) {
 240    ExtensionSettings::register(cx);
 241
 242    let store = cx.new_model(move |cx| {
 243        ExtensionStore::new(
 244            paths::extensions_dir().clone(),
 245            None,
 246            registration_hooks,
 247            fs,
 248            client.http_client().clone(),
 249            client.http_client().clone(),
 250            Some(client.telemetry().clone()),
 251            node_runtime,
 252            cx,
 253        )
 254    });
 255
 256    cx.on_action(|_: &ReloadExtensions, cx| {
 257        let store = cx.global::<GlobalExtensionStore>().0.clone();
 258        store.update(cx, |store, cx| drop(store.reload(None, cx)));
 259    });
 260
 261    cx.set_global(GlobalExtensionStore(store));
 262}
 263
 264impl ExtensionStore {
 265    pub fn try_global(cx: &AppContext) -> Option<Model<Self>> {
 266        cx.try_global::<GlobalExtensionStore>()
 267            .map(|store| store.0.clone())
 268    }
 269
 270    pub fn global(cx: &AppContext) -> Model<Self> {
 271        cx.global::<GlobalExtensionStore>().0.clone()
 272    }
 273
 274    #[allow(clippy::too_many_arguments)]
 275    pub fn new(
 276        extensions_dir: PathBuf,
 277        build_dir: Option<PathBuf>,
 278        extension_api: Arc<dyn ExtensionRegistrationHooks>,
 279        fs: Arc<dyn Fs>,
 280        http_client: Arc<HttpClientWithUrl>,
 281        builder_client: Arc<dyn HttpClient>,
 282        telemetry: Option<Arc<Telemetry>>,
 283        node_runtime: NodeRuntime,
 284        cx: &mut ModelContext<Self>,
 285    ) -> Self {
 286        let work_dir = extensions_dir.join("work");
 287        let build_dir = build_dir.unwrap_or_else(|| extensions_dir.join("build"));
 288        let installed_dir = extensions_dir.join("installed");
 289        let index_path = extensions_dir.join("index.json");
 290
 291        let (reload_tx, mut reload_rx) = unbounded();
 292        let mut this = Self {
 293            registration_hooks: extension_api.clone(),
 294            extension_index: Default::default(),
 295            installed_dir,
 296            index_path,
 297            builder: Arc::new(ExtensionBuilder::new(builder_client, build_dir)),
 298            outstanding_operations: Default::default(),
 299            modified_extensions: Default::default(),
 300            reload_complete_senders: Vec::new(),
 301            wasm_host: WasmHost::new(
 302                fs.clone(),
 303                http_client.clone(),
 304                node_runtime,
 305                extension_api,
 306                work_dir,
 307                cx,
 308            ),
 309            wasm_extensions: Vec::new(),
 310            fs,
 311            http_client,
 312            telemetry,
 313            reload_tx,
 314            tasks: Vec::new(),
 315        };
 316
 317        // The extensions store maintains an index file, which contains a complete
 318        // list of the installed extensions and the resources that they provide.
 319        // This index is loaded synchronously on startup.
 320        let (index_content, index_metadata, extensions_metadata) =
 321            cx.background_executor().block(async {
 322                futures::join!(
 323                    this.fs.load(&this.index_path),
 324                    this.fs.metadata(&this.index_path),
 325                    this.fs.metadata(&this.installed_dir),
 326                )
 327            });
 328
 329        // Normally, there is no need to rebuild the index. But if the index file
 330        // is invalid or is out-of-date according to the filesystem mtimes, then
 331        // it must be asynchronously rebuilt.
 332        let mut extension_index = ExtensionIndex::default();
 333        let mut extension_index_needs_rebuild = true;
 334        if let Ok(index_content) = index_content {
 335            if let Some(index) = serde_json::from_str(&index_content).log_err() {
 336                extension_index = index;
 337                if let (Ok(Some(index_metadata)), Ok(Some(extensions_metadata))) =
 338                    (index_metadata, extensions_metadata)
 339                {
 340                    if index_metadata.mtime > extensions_metadata.mtime {
 341                        extension_index_needs_rebuild = false;
 342                    }
 343                }
 344            }
 345        }
 346
 347        // Immediately load all of the extensions in the initial manifest. If the
 348        // index needs to be rebuild, then enqueue
 349        let load_initial_extensions = this.extensions_updated(extension_index, cx);
 350        let mut reload_future = None;
 351        if extension_index_needs_rebuild {
 352            reload_future = Some(this.reload(None, cx));
 353        }
 354
 355        cx.spawn(|this, mut cx| async move {
 356            if let Some(future) = reload_future {
 357                future.await;
 358            }
 359            this.update(&mut cx, |this, cx| this.auto_install_extensions(cx))
 360                .ok();
 361            this.update(&mut cx, |this, cx| this.check_for_updates(cx))
 362                .ok();
 363        })
 364        .detach();
 365
 366        // Perform all extension loading in a single task to ensure that we
 367        // never attempt to simultaneously load/unload extensions from multiple
 368        // parallel tasks.
 369        this.tasks.push(cx.spawn(|this, mut cx| {
 370            async move {
 371                load_initial_extensions.await;
 372
 373                let mut index_changed = false;
 374                let mut debounce_timer = cx
 375                    .background_executor()
 376                    .spawn(futures::future::pending())
 377                    .fuse();
 378                loop {
 379                    select_biased! {
 380                        _ = debounce_timer => {
 381                            if index_changed {
 382                                let index = this
 383                                    .update(&mut cx, |this, cx| this.rebuild_extension_index(cx))?
 384                                    .await;
 385                                this.update(&mut cx, |this, cx| this.extensions_updated(index, cx))?
 386                                    .await;
 387                                index_changed = false;
 388                            }
 389                        }
 390                        extension_id = reload_rx.next() => {
 391                            let Some(extension_id) = extension_id else { break; };
 392                            this.update(&mut cx, |this, _| {
 393                                this.modified_extensions.extend(extension_id);
 394                            })?;
 395                            index_changed = true;
 396                            debounce_timer = cx
 397                                .background_executor()
 398                                .timer(RELOAD_DEBOUNCE_DURATION)
 399                                .fuse();
 400                        }
 401                    }
 402                }
 403
 404                anyhow::Ok(())
 405            }
 406            .map(drop)
 407        }));
 408
 409        // Watch the installed extensions directory for changes. Whenever changes are
 410        // detected, rebuild the extension index, and load/unload any extensions that
 411        // have been added, removed, or modified.
 412        this.tasks.push(cx.background_executor().spawn({
 413            let fs = this.fs.clone();
 414            let reload_tx = this.reload_tx.clone();
 415            let installed_dir = this.installed_dir.clone();
 416            async move {
 417                let (mut paths, _) = fs.watch(&installed_dir, FS_WATCH_LATENCY).await;
 418                while let Some(events) = paths.next().await {
 419                    for event in events {
 420                        let Ok(event_path) = event.path.strip_prefix(&installed_dir) else {
 421                            continue;
 422                        };
 423
 424                        if let Some(path::Component::Normal(extension_dir_name)) =
 425                            event_path.components().next()
 426                        {
 427                            if let Some(extension_id) = extension_dir_name.to_str() {
 428                                reload_tx.unbounded_send(Some(extension_id.into())).ok();
 429                            }
 430                        }
 431                    }
 432                }
 433            }
 434        }));
 435
 436        this
 437    }
 438
 439    pub fn reload(
 440        &mut self,
 441        modified_extension: Option<Arc<str>>,
 442        cx: &mut ModelContext<Self>,
 443    ) -> impl Future<Output = ()> {
 444        let (tx, rx) = oneshot::channel();
 445        self.reload_complete_senders.push(tx);
 446        self.reload_tx
 447            .unbounded_send(modified_extension)
 448            .expect("reload task exited");
 449        cx.emit(Event::StartedReloading);
 450
 451        async move {
 452            rx.await.ok();
 453        }
 454    }
 455
 456    fn extensions_dir(&self) -> PathBuf {
 457        self.installed_dir.clone()
 458    }
 459
 460    pub fn outstanding_operations(&self) -> &BTreeMap<Arc<str>, ExtensionOperation> {
 461        &self.outstanding_operations
 462    }
 463
 464    pub fn installed_extensions(&self) -> &BTreeMap<Arc<str>, ExtensionIndexEntry> {
 465        &self.extension_index.extensions
 466    }
 467
 468    pub fn dev_extensions(&self) -> impl Iterator<Item = &Arc<ExtensionManifest>> {
 469        self.extension_index
 470            .extensions
 471            .values()
 472            .filter_map(|extension| extension.dev.then_some(&extension.manifest))
 473    }
 474
 475    /// Returns the names of themes provided by extensions.
 476    pub fn extension_themes<'a>(
 477        &'a self,
 478        extension_id: &'a str,
 479    ) -> impl Iterator<Item = &'a Arc<str>> {
 480        self.extension_index
 481            .themes
 482            .iter()
 483            .filter_map(|(name, theme)| theme.extension.as_ref().eq(extension_id).then_some(name))
 484    }
 485
 486    pub fn fetch_extensions(
 487        &self,
 488        search: Option<&str>,
 489        cx: &mut ModelContext<Self>,
 490    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 491        let version = CURRENT_SCHEMA_VERSION.to_string();
 492        let mut query = vec![("max_schema_version", version.as_str())];
 493        if let Some(search) = search {
 494            query.push(("filter", search));
 495        }
 496
 497        self.fetch_extensions_from_api("/extensions", &query, cx)
 498    }
 499
 500    pub fn fetch_extensions_with_update_available(
 501        &mut self,
 502        cx: &mut ModelContext<Self>,
 503    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 504        let schema_versions = schema_version_range();
 505        let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
 506        let extension_settings = ExtensionSettings::get_global(cx);
 507        let extension_ids = self
 508            .extension_index
 509            .extensions
 510            .iter()
 511            .filter(|(id, entry)| !entry.dev && extension_settings.should_auto_update(id))
 512            .map(|(id, _)| id.as_ref())
 513            .collect::<Vec<_>>()
 514            .join(",");
 515        let task = self.fetch_extensions_from_api(
 516            "/extensions/updates",
 517            &[
 518                ("min_schema_version", &schema_versions.start().to_string()),
 519                ("max_schema_version", &schema_versions.end().to_string()),
 520                (
 521                    "min_wasm_api_version",
 522                    &wasm_api_versions.start().to_string(),
 523                ),
 524                ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
 525                ("ids", &extension_ids),
 526            ],
 527            cx,
 528        );
 529        cx.spawn(move |this, mut cx| async move {
 530            let extensions = task.await?;
 531            this.update(&mut cx, |this, _cx| {
 532                extensions
 533                    .into_iter()
 534                    .filter(|extension| {
 535                        this.extension_index.extensions.get(&extension.id).map_or(
 536                            true,
 537                            |installed_extension| {
 538                                installed_extension.manifest.version != extension.manifest.version
 539                            },
 540                        )
 541                    })
 542                    .collect()
 543            })
 544        })
 545    }
 546
 547    pub fn fetch_extension_versions(
 548        &self,
 549        extension_id: &str,
 550        cx: &mut ModelContext<Self>,
 551    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 552        self.fetch_extensions_from_api(&format!("/extensions/{extension_id}"), &[], cx)
 553    }
 554
 555    /// Installs any extensions that should be included with Zed by default.
 556    ///
 557    /// This can be used to make certain functionality provided by extensions
 558    /// available out-of-the-box.
 559    pub fn auto_install_extensions(&mut self, cx: &mut ModelContext<Self>) {
 560        let extension_settings = ExtensionSettings::get_global(cx);
 561
 562        let extensions_to_install = extension_settings
 563            .auto_install_extensions
 564            .keys()
 565            .filter(|extension_id| extension_settings.should_auto_install(extension_id))
 566            .filter(|extension_id| {
 567                let is_already_installed = self
 568                    .extension_index
 569                    .extensions
 570                    .contains_key(extension_id.as_ref());
 571                !is_already_installed
 572            })
 573            .cloned()
 574            .collect::<Vec<_>>();
 575
 576        cx.spawn(move |this, mut cx| async move {
 577            for extension_id in extensions_to_install {
 578                this.update(&mut cx, |this, cx| {
 579                    this.install_latest_extension(extension_id.clone(), cx);
 580                })
 581                .ok();
 582            }
 583        })
 584        .detach();
 585    }
 586
 587    pub fn check_for_updates(&mut self, cx: &mut ModelContext<Self>) {
 588        let task = self.fetch_extensions_with_update_available(cx);
 589        cx.spawn(move |this, mut cx| async move {
 590            Self::upgrade_extensions(this, task.await?, &mut cx).await
 591        })
 592        .detach();
 593    }
 594
 595    async fn upgrade_extensions(
 596        this: WeakModel<Self>,
 597        extensions: Vec<ExtensionMetadata>,
 598        cx: &mut AsyncAppContext,
 599    ) -> Result<()> {
 600        for extension in extensions {
 601            let task = this.update(cx, |this, cx| {
 602                if let Some(installed_extension) =
 603                    this.extension_index.extensions.get(&extension.id)
 604                {
 605                    let installed_version =
 606                        SemanticVersion::from_str(&installed_extension.manifest.version).ok()?;
 607                    let latest_version =
 608                        SemanticVersion::from_str(&extension.manifest.version).ok()?;
 609
 610                    if installed_version >= latest_version {
 611                        return None;
 612                    }
 613                }
 614
 615                Some(this.upgrade_extension(extension.id, extension.manifest.version, cx))
 616            })?;
 617
 618            if let Some(task) = task {
 619                task.await.log_err();
 620            }
 621        }
 622        anyhow::Ok(())
 623    }
 624
 625    fn fetch_extensions_from_api(
 626        &self,
 627        path: &str,
 628        query: &[(&str, &str)],
 629        cx: &mut ModelContext<'_, ExtensionStore>,
 630    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 631        let url = self.http_client.build_zed_api_url(path, query);
 632        let http_client = self.http_client.clone();
 633        cx.spawn(move |_, _| async move {
 634            let mut response = http_client
 635                .get(url?.as_ref(), AsyncBody::empty(), true)
 636                .await?;
 637
 638            let mut body = Vec::new();
 639            response
 640                .body_mut()
 641                .read_to_end(&mut body)
 642                .await
 643                .context("error reading extensions")?;
 644
 645            if response.status().is_client_error() {
 646                let text = String::from_utf8_lossy(body.as_slice());
 647                bail!(
 648                    "status error {}, response: {text:?}",
 649                    response.status().as_u16()
 650                );
 651            }
 652
 653            let response: GetExtensionsResponse = serde_json::from_slice(&body)?;
 654            Ok(response.data)
 655        })
 656    }
 657
 658    pub fn install_extension(
 659        &mut self,
 660        extension_id: Arc<str>,
 661        version: Arc<str>,
 662        cx: &mut ModelContext<Self>,
 663    ) {
 664        self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Install, cx)
 665            .detach_and_log_err(cx);
 666    }
 667
 668    fn install_or_upgrade_extension_at_endpoint(
 669        &mut self,
 670        extension_id: Arc<str>,
 671        url: Url,
 672        operation: ExtensionOperation,
 673        cx: &mut ModelContext<Self>,
 674    ) -> Task<Result<()>> {
 675        let extension_dir = self.installed_dir.join(extension_id.as_ref());
 676        let http_client = self.http_client.clone();
 677        let fs = self.fs.clone();
 678
 679        match self.outstanding_operations.entry(extension_id.clone()) {
 680            btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
 681            btree_map::Entry::Vacant(e) => e.insert(operation),
 682        };
 683        cx.notify();
 684
 685        cx.spawn(move |this, mut cx| async move {
 686            let _finish = util::defer({
 687                let this = this.clone();
 688                let mut cx = cx.clone();
 689                let extension_id = extension_id.clone();
 690                move || {
 691                    this.update(&mut cx, |this, cx| {
 692                        this.outstanding_operations.remove(extension_id.as_ref());
 693                        cx.notify();
 694                    })
 695                    .ok();
 696                }
 697            });
 698
 699            let mut response = http_client
 700                .get(url.as_ref(), Default::default(), true)
 701                .await
 702                .map_err(|err| anyhow!("error downloading extension: {}", err))?;
 703
 704            fs.remove_dir(
 705                &extension_dir,
 706                RemoveOptions {
 707                    recursive: true,
 708                    ignore_if_not_exists: true,
 709                },
 710            )
 711            .await?;
 712
 713            let content_length = response
 714                .headers()
 715                .get(http_client::http::header::CONTENT_LENGTH)
 716                .and_then(|value| value.to_str().ok()?.parse::<usize>().ok());
 717
 718            let mut body = BufReader::new(response.body_mut());
 719            let mut tar_gz_bytes = Vec::new();
 720            body.read_to_end(&mut tar_gz_bytes).await?;
 721
 722            if let Some(content_length) = content_length {
 723                let actual_len = tar_gz_bytes.len();
 724                if content_length != actual_len {
 725                    bail!("downloaded extension size {actual_len} does not match content length {content_length}");
 726                }
 727            }
 728            let decompressed_bytes = GzipDecoder::new(BufReader::new(tar_gz_bytes.as_slice()));
 729            let archive = Archive::new(decompressed_bytes);
 730            archive.unpack(extension_dir).await?;
 731            this.update(&mut cx, |this, cx| {
 732                this.reload(Some(extension_id.clone()), cx)
 733            })?
 734            .await;
 735
 736            if let ExtensionOperation::Install = operation {
 737                this.update(&mut cx, |_, cx| {
 738                    cx.emit(Event::ExtensionInstalled(extension_id));
 739                })
 740                .ok();
 741            }
 742
 743            anyhow::Ok(())
 744        })
 745    }
 746
 747    pub fn install_latest_extension(
 748        &mut self,
 749        extension_id: Arc<str>,
 750        cx: &mut ModelContext<Self>,
 751    ) {
 752        log::info!("installing extension {extension_id} latest version");
 753
 754        let schema_versions = schema_version_range();
 755        let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
 756
 757        let Some(url) = self
 758            .http_client
 759            .build_zed_api_url(
 760                &format!("/extensions/{extension_id}/download"),
 761                &[
 762                    ("min_schema_version", &schema_versions.start().to_string()),
 763                    ("max_schema_version", &schema_versions.end().to_string()),
 764                    (
 765                        "min_wasm_api_version",
 766                        &wasm_api_versions.start().to_string(),
 767                    ),
 768                    ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
 769                ],
 770            )
 771            .log_err()
 772        else {
 773            return;
 774        };
 775
 776        self.install_or_upgrade_extension_at_endpoint(
 777            extension_id,
 778            url,
 779            ExtensionOperation::Install,
 780            cx,
 781        )
 782        .detach_and_log_err(cx);
 783    }
 784
 785    pub fn upgrade_extension(
 786        &mut self,
 787        extension_id: Arc<str>,
 788        version: Arc<str>,
 789        cx: &mut ModelContext<Self>,
 790    ) -> Task<Result<()>> {
 791        self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Upgrade, cx)
 792    }
 793
 794    fn install_or_upgrade_extension(
 795        &mut self,
 796        extension_id: Arc<str>,
 797        version: Arc<str>,
 798        operation: ExtensionOperation,
 799        cx: &mut ModelContext<Self>,
 800    ) -> Task<Result<()>> {
 801        log::info!("installing extension {extension_id} {version}");
 802        let Some(url) = self
 803            .http_client
 804            .build_zed_api_url(
 805                &format!("/extensions/{extension_id}/{version}/download"),
 806                &[],
 807            )
 808            .log_err()
 809        else {
 810            return Task::ready(Ok(()));
 811        };
 812
 813        self.install_or_upgrade_extension_at_endpoint(extension_id, url, operation, cx)
 814    }
 815
 816    pub fn uninstall_extension(&mut self, extension_id: Arc<str>, cx: &mut ModelContext<Self>) {
 817        let extension_dir = self.installed_dir.join(extension_id.as_ref());
 818        let work_dir = self.wasm_host.work_dir.join(extension_id.as_ref());
 819        let fs = self.fs.clone();
 820
 821        match self.outstanding_operations.entry(extension_id.clone()) {
 822            btree_map::Entry::Occupied(_) => return,
 823            btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
 824        };
 825
 826        cx.spawn(move |this, mut cx| async move {
 827            let _finish = util::defer({
 828                let this = this.clone();
 829                let mut cx = cx.clone();
 830                let extension_id = extension_id.clone();
 831                move || {
 832                    this.update(&mut cx, |this, cx| {
 833                        this.outstanding_operations.remove(extension_id.as_ref());
 834                        cx.notify();
 835                    })
 836                    .ok();
 837                }
 838            });
 839
 840            fs.remove_dir(
 841                &work_dir,
 842                RemoveOptions {
 843                    recursive: true,
 844                    ignore_if_not_exists: true,
 845                },
 846            )
 847            .await?;
 848
 849            fs.remove_dir(
 850                &extension_dir,
 851                RemoveOptions {
 852                    recursive: true,
 853                    ignore_if_not_exists: true,
 854                },
 855            )
 856            .await?;
 857
 858            this.update(&mut cx, |this, cx| this.reload(None, cx))?
 859                .await;
 860            anyhow::Ok(())
 861        })
 862        .detach_and_log_err(cx)
 863    }
 864
 865    pub fn install_dev_extension(
 866        &mut self,
 867        extension_source_path: PathBuf,
 868        cx: &mut ModelContext<Self>,
 869    ) -> Task<Result<()>> {
 870        let extensions_dir = self.extensions_dir();
 871        let fs = self.fs.clone();
 872        let builder = self.builder.clone();
 873
 874        cx.spawn(move |this, mut cx| async move {
 875            let mut extension_manifest =
 876                ExtensionManifest::load(fs.clone(), &extension_source_path).await?;
 877            let extension_id = extension_manifest.id.clone();
 878
 879            if !this.update(&mut cx, |this, cx| {
 880                match this.outstanding_operations.entry(extension_id.clone()) {
 881                    btree_map::Entry::Occupied(_) => return false,
 882                    btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
 883                };
 884                cx.notify();
 885                true
 886            })? {
 887                return Ok(());
 888            }
 889
 890            let _finish = util::defer({
 891                let this = this.clone();
 892                let mut cx = cx.clone();
 893                let extension_id = extension_id.clone();
 894                move || {
 895                    this.update(&mut cx, |this, cx| {
 896                        this.outstanding_operations.remove(extension_id.as_ref());
 897                        cx.notify();
 898                    })
 899                    .ok();
 900                }
 901            });
 902
 903            cx.background_executor()
 904                .spawn({
 905                    let extension_source_path = extension_source_path.clone();
 906                    async move {
 907                        builder
 908                            .compile_extension(
 909                                &extension_source_path,
 910                                &mut extension_manifest,
 911                                CompileExtensionOptions { release: false },
 912                            )
 913                            .await
 914                    }
 915                })
 916                .await?;
 917
 918            let output_path = &extensions_dir.join(extension_id.as_ref());
 919            if let Some(metadata) = fs.metadata(output_path).await? {
 920                if metadata.is_symlink {
 921                    fs.remove_file(
 922                        output_path,
 923                        RemoveOptions {
 924                            recursive: false,
 925                            ignore_if_not_exists: true,
 926                        },
 927                    )
 928                    .await?;
 929                } else {
 930                    bail!("extension {extension_id} is already installed");
 931                }
 932            }
 933
 934            fs.create_symlink(output_path, extension_source_path)
 935                .await?;
 936
 937            this.update(&mut cx, |this, cx| this.reload(None, cx))?
 938                .await;
 939            Ok(())
 940        })
 941    }
 942
 943    pub fn rebuild_dev_extension(&mut self, extension_id: Arc<str>, cx: &mut ModelContext<Self>) {
 944        let path = self.installed_dir.join(extension_id.as_ref());
 945        let builder = self.builder.clone();
 946        let fs = self.fs.clone();
 947
 948        match self.outstanding_operations.entry(extension_id.clone()) {
 949            btree_map::Entry::Occupied(_) => return,
 950            btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Upgrade),
 951        };
 952
 953        cx.notify();
 954        let compile = cx.background_executor().spawn(async move {
 955            let mut manifest = ExtensionManifest::load(fs, &path).await?;
 956            builder
 957                .compile_extension(
 958                    &path,
 959                    &mut manifest,
 960                    CompileExtensionOptions { release: true },
 961                )
 962                .await
 963        });
 964
 965        cx.spawn(|this, mut cx| async move {
 966            let result = compile.await;
 967
 968            this.update(&mut cx, |this, cx| {
 969                this.outstanding_operations.remove(&extension_id);
 970                cx.notify();
 971            })?;
 972
 973            if result.is_ok() {
 974                this.update(&mut cx, |this, cx| this.reload(Some(extension_id), cx))?
 975                    .await;
 976            }
 977
 978            result
 979        })
 980        .detach_and_log_err(cx)
 981    }
 982
 983    /// Updates the set of installed extensions.
 984    ///
 985    /// First, this unloads any themes, languages, or grammars that are
 986    /// no longer in the manifest, or whose files have changed on disk.
 987    /// Then it loads any themes, languages, or grammars that are newly
 988    /// added to the manifest, or whose files have changed on disk.
 989    fn extensions_updated(
 990        &mut self,
 991        new_index: ExtensionIndex,
 992        cx: &mut ModelContext<Self>,
 993    ) -> Task<()> {
 994        let old_index = &self.extension_index;
 995
 996        // Determine which extensions need to be loaded and unloaded, based
 997        // on the changes to the manifest and the extensions that we know have been
 998        // modified.
 999        let mut extensions_to_unload = Vec::default();
1000        let mut extensions_to_load = Vec::default();
1001        {
1002            let mut old_keys = old_index.extensions.iter().peekable();
1003            let mut new_keys = new_index.extensions.iter().peekable();
1004            loop {
1005                match (old_keys.peek(), new_keys.peek()) {
1006                    (None, None) => break,
1007                    (None, Some(_)) => {
1008                        extensions_to_load.push(new_keys.next().unwrap().0.clone());
1009                    }
1010                    (Some(_), None) => {
1011                        extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1012                    }
1013                    (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(new_key) {
1014                        Ordering::Equal => {
1015                            let (old_key, old_value) = old_keys.next().unwrap();
1016                            let (new_key, new_value) = new_keys.next().unwrap();
1017                            if old_value != new_value || self.modified_extensions.contains(old_key)
1018                            {
1019                                extensions_to_unload.push(old_key.clone());
1020                                extensions_to_load.push(new_key.clone());
1021                            }
1022                        }
1023                        Ordering::Less => {
1024                            extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1025                        }
1026                        Ordering::Greater => {
1027                            extensions_to_load.push(new_keys.next().unwrap().0.clone());
1028                        }
1029                    },
1030                }
1031            }
1032            self.modified_extensions.clear();
1033        }
1034
1035        if extensions_to_load.is_empty() && extensions_to_unload.is_empty() {
1036            return Task::ready(());
1037        }
1038
1039        let reload_count = extensions_to_unload
1040            .iter()
1041            .filter(|id| extensions_to_load.contains(id))
1042            .count();
1043
1044        log::info!(
1045            "extensions updated. loading {}, reloading {}, unloading {}",
1046            extensions_to_load.len() - reload_count,
1047            reload_count,
1048            extensions_to_unload.len() - reload_count
1049        );
1050
1051        if let Some(telemetry) = &self.telemetry {
1052            for extension_id in &extensions_to_load {
1053                if let Some(extension) = new_index.extensions.get(extension_id) {
1054                    telemetry.report_extension_event(
1055                        extension_id.clone(),
1056                        extension.manifest.version.clone(),
1057                    );
1058                }
1059            }
1060        }
1061
1062        let themes_to_remove = old_index
1063            .themes
1064            .iter()
1065            .filter_map(|(name, entry)| {
1066                if extensions_to_unload.contains(&entry.extension) {
1067                    Some(name.clone().into())
1068                } else {
1069                    None
1070                }
1071            })
1072            .collect::<Vec<_>>();
1073        let languages_to_remove = old_index
1074            .languages
1075            .iter()
1076            .filter_map(|(name, entry)| {
1077                if extensions_to_unload.contains(&entry.extension) {
1078                    Some(name.clone())
1079                } else {
1080                    None
1081                }
1082            })
1083            .collect::<Vec<_>>();
1084        let mut grammars_to_remove = Vec::new();
1085        for extension_id in &extensions_to_unload {
1086            let Some(extension) = old_index.extensions.get(extension_id) else {
1087                continue;
1088            };
1089            grammars_to_remove.extend(extension.manifest.grammars.keys().cloned());
1090            for (language_server_name, config) in extension.manifest.language_servers.iter() {
1091                for language in config.languages() {
1092                    self.registration_hooks
1093                        .remove_lsp_adapter(&language, language_server_name);
1094                }
1095            }
1096        }
1097
1098        self.wasm_extensions
1099            .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
1100        self.registration_hooks.remove_user_themes(themes_to_remove);
1101        self.registration_hooks
1102            .remove_languages(&languages_to_remove, &grammars_to_remove);
1103
1104        let languages_to_add = new_index
1105            .languages
1106            .iter()
1107            .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
1108            .collect::<Vec<_>>();
1109        let mut grammars_to_add = Vec::new();
1110        let mut themes_to_add = Vec::new();
1111        let mut snippets_to_add = Vec::new();
1112        for extension_id in &extensions_to_load {
1113            let Some(extension) = new_index.extensions.get(extension_id) else {
1114                continue;
1115            };
1116
1117            grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
1118                let mut grammar_path = self.installed_dir.clone();
1119                grammar_path.extend([extension_id.as_ref(), "grammars"]);
1120                grammar_path.push(grammar_name.as_ref());
1121                grammar_path.set_extension("wasm");
1122                (grammar_name.clone(), grammar_path)
1123            }));
1124            themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
1125                let mut path = self.installed_dir.clone();
1126                path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1127                path
1128            }));
1129            snippets_to_add.extend(extension.manifest.snippets.iter().map(|snippets_path| {
1130                let mut path = self.installed_dir.clone();
1131                path.extend([Path::new(extension_id.as_ref()), snippets_path.as_path()]);
1132                path
1133            }));
1134        }
1135
1136        self.registration_hooks
1137            .register_wasm_grammars(grammars_to_add);
1138
1139        for (language_name, language) in languages_to_add {
1140            let mut language_path = self.installed_dir.clone();
1141            language_path.extend([
1142                Path::new(language.extension.as_ref()),
1143                language.path.as_path(),
1144            ]);
1145            self.registration_hooks.register_language(
1146                language_name.clone(),
1147                language.grammar.clone(),
1148                language.matcher.clone(),
1149                Arc::new(move || {
1150                    let config = std::fs::read_to_string(language_path.join("config.toml"))?;
1151                    let config: LanguageConfig = ::toml::from_str(&config)?;
1152                    let queries = load_plugin_queries(&language_path);
1153                    let context_provider =
1154                        std::fs::read_to_string(language_path.join("tasks.json"))
1155                            .ok()
1156                            .and_then(|contents| {
1157                                let definitions =
1158                                    serde_json_lenient::from_str(&contents).log_err()?;
1159                                Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1160                            });
1161
1162                    Ok(LoadedLanguage {
1163                        config,
1164                        queries,
1165                        context_provider,
1166                        toolchain_provider: None,
1167                    })
1168                }),
1169            );
1170        }
1171
1172        let fs = self.fs.clone();
1173        let wasm_host = self.wasm_host.clone();
1174        let root_dir = self.installed_dir.clone();
1175        let api = self.registration_hooks.clone();
1176        let extension_entries = extensions_to_load
1177            .iter()
1178            .filter_map(|name| new_index.extensions.get(name).cloned())
1179            .collect::<Vec<_>>();
1180
1181        self.extension_index = new_index;
1182        cx.notify();
1183        cx.emit(Event::ExtensionsUpdated);
1184
1185        cx.spawn(|this, mut cx| async move {
1186            cx.background_executor()
1187                .spawn({
1188                    let fs = fs.clone();
1189                    async move {
1190                        for theme_path in themes_to_add.into_iter() {
1191                            api.load_user_theme(theme_path, fs.clone()).await.log_err();
1192                        }
1193
1194                        for snippets_path in &snippets_to_add {
1195                            if let Some(snippets_contents) = fs.load(snippets_path).await.log_err()
1196                            {
1197                                api.register_snippets(snippets_path, &snippets_contents)
1198                                    .log_err();
1199                            }
1200                        }
1201                    }
1202                })
1203                .await;
1204
1205            let mut wasm_extensions = Vec::new();
1206            for extension in extension_entries {
1207                if extension.manifest.lib.kind.is_none() {
1208                    continue;
1209                };
1210
1211                let extension_path = root_dir.join(extension.manifest.id.as_ref());
1212                let wasm_extension = WasmExtension::load(
1213                    extension_path,
1214                    &extension.manifest,
1215                    wasm_host.clone(),
1216                    &cx,
1217                )
1218                .await;
1219
1220                if let Some(wasm_extension) = wasm_extension.log_err() {
1221                    wasm_extensions.push((extension.manifest.clone(), wasm_extension));
1222                } else {
1223                    this.update(&mut cx, |_, cx| {
1224                        cx.emit(Event::ExtensionFailedToLoad(extension.manifest.id.clone()))
1225                    })
1226                    .ok();
1227                }
1228            }
1229
1230            this.update(&mut cx, |this, cx| {
1231                this.reload_complete_senders.clear();
1232
1233                for (manifest, wasm_extension) in &wasm_extensions {
1234                    let extension = Arc::new(wasm_extension.clone());
1235
1236                    for (language_server_id, language_server_config) in &manifest.language_servers {
1237                        for language in language_server_config.languages() {
1238                            this.registration_hooks.register_lsp_adapter(
1239                                language.clone(),
1240                                ExtensionLspAdapter {
1241                                    extension: wasm_extension.clone(),
1242                                    host: this.wasm_host.clone(),
1243                                    language_server_id: language_server_id.clone(),
1244                                    config: wit::LanguageServerConfig {
1245                                        name: language_server_id.0.to_string(),
1246                                        language_name: language.to_string(),
1247                                    },
1248                                },
1249                            );
1250                        }
1251                    }
1252
1253                    for (slash_command_name, slash_command) in &manifest.slash_commands {
1254                        this.registration_hooks.register_slash_command(
1255                            extension.clone(),
1256                            extension::SlashCommand {
1257                                name: slash_command_name.to_string(),
1258                                description: slash_command.description.to_string(),
1259                                // We don't currently expose this as a configurable option, as it currently drives
1260                                // the `menu_text` on the `SlashCommand` trait, which is not used for slash commands
1261                                // defined in extensions, as they are not able to be added to the menu.
1262                                tooltip_text: String::new(),
1263                                requires_argument: slash_command.requires_argument,
1264                            },
1265                        );
1266                    }
1267
1268                    for (id, _context_server_entry) in &manifest.context_servers {
1269                        this.registration_hooks.register_context_server(
1270                            id.clone(),
1271                            wasm_extension.clone(),
1272                            cx,
1273                        );
1274                    }
1275
1276                    for (provider_id, _provider) in &manifest.indexed_docs_providers {
1277                        this.registration_hooks
1278                            .register_docs_provider(extension.clone(), provider_id.clone());
1279                    }
1280                }
1281
1282                this.wasm_extensions.extend(wasm_extensions);
1283                this.registration_hooks.reload_current_theme(cx);
1284            })
1285            .ok();
1286        })
1287    }
1288
1289    fn rebuild_extension_index(&self, cx: &mut ModelContext<Self>) -> Task<ExtensionIndex> {
1290        let fs = self.fs.clone();
1291        let work_dir = self.wasm_host.work_dir.clone();
1292        let extensions_dir = self.installed_dir.clone();
1293        let index_path = self.index_path.clone();
1294        let extension_api = self.registration_hooks.clone();
1295        cx.background_executor().spawn(async move {
1296            let start_time = Instant::now();
1297            let mut index = ExtensionIndex::default();
1298
1299            fs.create_dir(&work_dir).await.log_err();
1300            fs.create_dir(&extensions_dir).await.log_err();
1301
1302            let extension_paths = fs.read_dir(&extensions_dir).await;
1303            if let Ok(mut extension_paths) = extension_paths {
1304                while let Some(extension_dir) = extension_paths.next().await {
1305                    let Ok(extension_dir) = extension_dir else {
1306                        continue;
1307                    };
1308
1309                    if extension_dir
1310                        .file_name()
1311                        .map_or(false, |file_name| file_name == ".DS_Store")
1312                    {
1313                        continue;
1314                    }
1315
1316                    Self::add_extension_to_index(
1317                        fs.clone(),
1318                        extension_dir,
1319                        &mut index,
1320                        extension_api.clone(),
1321                    )
1322                    .await
1323                    .log_err();
1324                }
1325            }
1326
1327            if let Ok(index_json) = serde_json::to_string_pretty(&index) {
1328                fs.save(&index_path, &index_json.as_str().into(), Default::default())
1329                    .await
1330                    .context("failed to save extension index")
1331                    .log_err();
1332            }
1333
1334            log::info!("rebuilt extension index in {:?}", start_time.elapsed());
1335            index
1336        })
1337    }
1338
1339    async fn add_extension_to_index(
1340        fs: Arc<dyn Fs>,
1341        extension_dir: PathBuf,
1342        index: &mut ExtensionIndex,
1343        extension_api: Arc<dyn ExtensionRegistrationHooks>,
1344    ) -> Result<()> {
1345        let mut extension_manifest = ExtensionManifest::load(fs.clone(), &extension_dir).await?;
1346        let extension_id = extension_manifest.id.clone();
1347
1348        // TODO: distinguish dev extensions more explicitly, by the absence
1349        // of a checksum file that we'll create when downloading normal extensions.
1350        let is_dev = fs
1351            .metadata(&extension_dir)
1352            .await?
1353            .ok_or_else(|| anyhow!("directory does not exist"))?
1354            .is_symlink;
1355
1356        if let Ok(mut language_paths) = fs.read_dir(&extension_dir.join("languages")).await {
1357            while let Some(language_path) = language_paths.next().await {
1358                let language_path = language_path?;
1359                let Ok(relative_path) = language_path.strip_prefix(&extension_dir) else {
1360                    continue;
1361                };
1362                let Ok(Some(fs_metadata)) = fs.metadata(&language_path).await else {
1363                    continue;
1364                };
1365                if !fs_metadata.is_dir {
1366                    continue;
1367                }
1368                let config = fs.load(&language_path.join("config.toml")).await?;
1369                let config = ::toml::from_str::<LanguageConfig>(&config)?;
1370
1371                let relative_path = relative_path.to_path_buf();
1372                if !extension_manifest.languages.contains(&relative_path) {
1373                    extension_manifest.languages.push(relative_path.clone());
1374                }
1375
1376                index.languages.insert(
1377                    config.name.clone(),
1378                    ExtensionIndexLanguageEntry {
1379                        extension: extension_id.clone(),
1380                        path: relative_path,
1381                        matcher: config.matcher,
1382                        grammar: config.grammar,
1383                    },
1384                );
1385            }
1386        }
1387
1388        if let Ok(mut theme_paths) = fs.read_dir(&extension_dir.join("themes")).await {
1389            while let Some(theme_path) = theme_paths.next().await {
1390                let theme_path = theme_path?;
1391                let Ok(relative_path) = theme_path.strip_prefix(&extension_dir) else {
1392                    continue;
1393                };
1394
1395                let Some(theme_families) = extension_api
1396                    .list_theme_names(theme_path.clone(), fs.clone())
1397                    .await
1398                    .log_err()
1399                else {
1400                    continue;
1401                };
1402
1403                let relative_path = relative_path.to_path_buf();
1404                if !extension_manifest.themes.contains(&relative_path) {
1405                    extension_manifest.themes.push(relative_path.clone());
1406                }
1407
1408                for theme_name in theme_families {
1409                    index.themes.insert(
1410                        theme_name.into(),
1411                        ExtensionIndexThemeEntry {
1412                            extension: extension_id.clone(),
1413                            path: relative_path.clone(),
1414                        },
1415                    );
1416                }
1417            }
1418        }
1419
1420        let extension_wasm_path = extension_dir.join("extension.wasm");
1421        if fs.is_file(&extension_wasm_path).await {
1422            extension_manifest
1423                .lib
1424                .kind
1425                .get_or_insert(ExtensionLibraryKind::Rust);
1426        }
1427
1428        index.extensions.insert(
1429            extension_id.clone(),
1430            ExtensionIndexEntry {
1431                dev: is_dev,
1432                manifest: Arc::new(extension_manifest),
1433            },
1434        );
1435
1436        Ok(())
1437    }
1438}
1439
1440fn load_plugin_queries(root_path: &Path) -> LanguageQueries {
1441    let mut result = LanguageQueries::default();
1442    if let Some(entries) = std::fs::read_dir(root_path).log_err() {
1443        for entry in entries {
1444            let Some(entry) = entry.log_err() else {
1445                continue;
1446            };
1447            let path = entry.path();
1448            if let Some(remainder) = path.strip_prefix(root_path).ok().and_then(|p| p.to_str()) {
1449                if !remainder.ends_with(".scm") {
1450                    continue;
1451                }
1452                for (name, query) in QUERY_FILENAME_PREFIXES {
1453                    if remainder.starts_with(name) {
1454                        if let Some(contents) = std::fs::read_to_string(&path).log_err() {
1455                            match query(&mut result) {
1456                                None => *query(&mut result) = Some(contents.into()),
1457                                Some(r) => r.to_mut().push_str(contents.as_ref()),
1458                            }
1459                        }
1460                        break;
1461                    }
1462                }
1463            }
1464        }
1465    }
1466    result
1467}