extension_host.rs

   1mod capability_granter;
   2pub mod extension_settings;
   3pub mod headless_host;
   4pub mod wasm_host;
   5
   6#[cfg(test)]
   7mod extension_store_test;
   8
   9use anyhow::{Context as _, Result, anyhow, bail};
  10use async_compression::futures::bufread::GzipDecoder;
  11use async_tar::Archive;
  12use client::ExtensionProvides;
  13use client::{Client, ExtensionMetadata, GetExtensionsResponse, proto, telemetry::Telemetry};
  14use collections::{BTreeMap, BTreeSet, HashMap, HashSet, btree_map};
  15pub use extension::ExtensionManifest;
  16use extension::extension_builder::{CompileExtensionOptions, ExtensionBuilder};
  17use extension::{
  18    ExtensionContextServerProxy, ExtensionDebugAdapterProviderProxy, ExtensionEvents,
  19    ExtensionGrammarProxy, ExtensionHostProxy, ExtensionLanguageProxy,
  20    ExtensionLanguageServerProxy, ExtensionSlashCommandProxy, ExtensionSnippetProxy,
  21    ExtensionThemeProxy,
  22};
  23use fs::{Fs, RemoveOptions};
  24use futures::future::join_all;
  25use futures::{
  26    AsyncReadExt as _, Future, FutureExt as _, StreamExt as _,
  27    channel::{
  28        mpsc::{UnboundedSender, unbounded},
  29        oneshot,
  30    },
  31    io::BufReader,
  32    select_biased,
  33};
  34use gpui::{
  35    App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Global, Task, WeakEntity,
  36    actions,
  37};
  38use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
  39use language::{
  40    LanguageConfig, LanguageMatcher, LanguageName, LanguageQueries, LoadedLanguage,
  41    QUERY_FILENAME_PREFIXES, Rope,
  42};
  43use node_runtime::NodeRuntime;
  44use project::ContextProviderWithTasks;
  45use release_channel::ReleaseChannel;
  46use remote::{RemoteClient, RemoteConnectionOptions};
  47use semantic_version::SemanticVersion;
  48use serde::{Deserialize, Serialize};
  49use settings::Settings;
  50use std::future;
  51use std::ops::RangeInclusive;
  52use std::str::FromStr;
  53use std::{
  54    cmp::Ordering,
  55    path::{self, Path, PathBuf},
  56    sync::Arc,
  57    time::{Duration, Instant},
  58};
  59use url::Url;
  60use util::{ResultExt, paths::RemotePathBuf};
  61use wasm_host::{
  62    WasmExtension, WasmHost,
  63    wit::{is_supported_wasm_api_version, wasm_api_version_range},
  64};
  65
  66pub use extension::{
  67    ExtensionLibraryKind, GrammarManifestEntry, OldExtensionManifest, SchemaVersion,
  68};
  69pub use extension_settings::ExtensionSettings;
  70
  71pub const RELOAD_DEBOUNCE_DURATION: Duration = Duration::from_millis(200);
  72const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
  73
  74/// The current extension [`SchemaVersion`] supported by Zed.
  75const CURRENT_SCHEMA_VERSION: SchemaVersion = SchemaVersion(1);
  76
  77/// Returns the [`SchemaVersion`] range that is compatible with this version of Zed.
  78pub fn schema_version_range() -> RangeInclusive<SchemaVersion> {
  79    SchemaVersion::ZERO..=CURRENT_SCHEMA_VERSION
  80}
  81
  82/// Returns whether the given extension version is compatible with this version of Zed.
  83pub fn is_version_compatible(
  84    release_channel: ReleaseChannel,
  85    extension_version: &ExtensionMetadata,
  86) -> bool {
  87    let schema_version = extension_version.manifest.schema_version.unwrap_or(0);
  88    if CURRENT_SCHEMA_VERSION.0 < schema_version {
  89        return false;
  90    }
  91
  92    if let Some(wasm_api_version) = extension_version
  93        .manifest
  94        .wasm_api_version
  95        .as_ref()
  96        .and_then(|wasm_api_version| SemanticVersion::from_str(wasm_api_version).ok())
  97        && !is_supported_wasm_api_version(release_channel, wasm_api_version)
  98    {
  99        return false;
 100    }
 101
 102    true
 103}
 104
 105pub struct ExtensionStore {
 106    pub proxy: Arc<ExtensionHostProxy>,
 107    pub builder: Arc<ExtensionBuilder>,
 108    pub extension_index: ExtensionIndex,
 109    pub fs: Arc<dyn Fs>,
 110    pub http_client: Arc<HttpClientWithUrl>,
 111    pub telemetry: Option<Arc<Telemetry>>,
 112    pub reload_tx: UnboundedSender<Option<Arc<str>>>,
 113    pub reload_complete_senders: Vec<oneshot::Sender<()>>,
 114    pub installed_dir: PathBuf,
 115    pub outstanding_operations: BTreeMap<Arc<str>, ExtensionOperation>,
 116    pub index_path: PathBuf,
 117    pub modified_extensions: HashSet<Arc<str>>,
 118    pub wasm_host: Arc<WasmHost>,
 119    pub wasm_extensions: Vec<(Arc<ExtensionManifest>, WasmExtension)>,
 120    pub tasks: Vec<Task<()>>,
 121    pub remote_clients: HashMap<RemoteConnectionOptions, WeakEntity<RemoteClient>>,
 122    pub ssh_registered_tx: UnboundedSender<()>,
 123}
 124
 125#[derive(Clone, Copy)]
 126pub enum ExtensionOperation {
 127    Upgrade,
 128    Install,
 129    Remove,
 130}
 131
 132#[derive(Clone)]
 133pub enum Event {
 134    ExtensionsUpdated,
 135    StartedReloading,
 136    ExtensionInstalled(Arc<str>),
 137    ExtensionUninstalled(Arc<str>),
 138    ExtensionFailedToLoad(Arc<str>),
 139}
 140
 141impl EventEmitter<Event> for ExtensionStore {}
 142
 143struct GlobalExtensionStore(Entity<ExtensionStore>);
 144
 145impl Global for GlobalExtensionStore {}
 146
 147#[derive(Debug, Deserialize, Serialize, Default, PartialEq, Eq)]
 148pub struct ExtensionIndex {
 149    pub extensions: BTreeMap<Arc<str>, ExtensionIndexEntry>,
 150    pub themes: BTreeMap<Arc<str>, ExtensionIndexThemeEntry>,
 151    #[serde(default)]
 152    pub icon_themes: BTreeMap<Arc<str>, ExtensionIndexIconThemeEntry>,
 153    pub languages: BTreeMap<LanguageName, ExtensionIndexLanguageEntry>,
 154}
 155
 156#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
 157pub struct ExtensionIndexEntry {
 158    pub manifest: Arc<ExtensionManifest>,
 159    pub dev: bool,
 160}
 161
 162#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
 163pub struct ExtensionIndexThemeEntry {
 164    pub extension: Arc<str>,
 165    pub path: PathBuf,
 166}
 167
 168#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
 169pub struct ExtensionIndexIconThemeEntry {
 170    pub extension: Arc<str>,
 171    pub path: PathBuf,
 172}
 173
 174#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
 175pub struct ExtensionIndexLanguageEntry {
 176    pub extension: Arc<str>,
 177    pub path: PathBuf,
 178    pub matcher: LanguageMatcher,
 179    pub hidden: bool,
 180    pub grammar: Option<Arc<str>>,
 181}
 182
 183actions!(
 184    zed,
 185    [
 186        /// Reloads all installed extensions.
 187        ReloadExtensions
 188    ]
 189);
 190
 191pub fn init(
 192    extension_host_proxy: Arc<ExtensionHostProxy>,
 193    fs: Arc<dyn Fs>,
 194    client: Arc<Client>,
 195    node_runtime: NodeRuntime,
 196    cx: &mut App,
 197) {
 198    ExtensionSettings::register(cx);
 199
 200    let store = cx.new(move |cx| {
 201        ExtensionStore::new(
 202            paths::extensions_dir().clone(),
 203            None,
 204            extension_host_proxy,
 205            fs,
 206            client.http_client(),
 207            client.http_client(),
 208            Some(client.telemetry().clone()),
 209            node_runtime,
 210            cx,
 211        )
 212    });
 213
 214    cx.on_action(|_: &ReloadExtensions, cx| {
 215        let store = cx.global::<GlobalExtensionStore>().0.clone();
 216        store.update(cx, |store, cx| drop(store.reload(None, cx)));
 217    });
 218
 219    cx.set_global(GlobalExtensionStore(store));
 220}
 221
 222impl ExtensionStore {
 223    pub fn try_global(cx: &App) -> Option<Entity<Self>> {
 224        cx.try_global::<GlobalExtensionStore>()
 225            .map(|store| store.0.clone())
 226    }
 227
 228    pub fn global(cx: &App) -> Entity<Self> {
 229        cx.global::<GlobalExtensionStore>().0.clone()
 230    }
 231
 232    pub fn new(
 233        extensions_dir: PathBuf,
 234        build_dir: Option<PathBuf>,
 235        extension_host_proxy: Arc<ExtensionHostProxy>,
 236        fs: Arc<dyn Fs>,
 237        http_client: Arc<HttpClientWithUrl>,
 238        builder_client: Arc<dyn HttpClient>,
 239        telemetry: Option<Arc<Telemetry>>,
 240        node_runtime: NodeRuntime,
 241        cx: &mut Context<Self>,
 242    ) -> Self {
 243        let work_dir = extensions_dir.join("work");
 244        let build_dir = build_dir.unwrap_or_else(|| extensions_dir.join("build"));
 245        let installed_dir = extensions_dir.join("installed");
 246        let index_path = extensions_dir.join("index.json");
 247
 248        let (reload_tx, mut reload_rx) = unbounded();
 249        let (connection_registered_tx, mut connection_registered_rx) = unbounded();
 250        let mut this = Self {
 251            proxy: extension_host_proxy.clone(),
 252            extension_index: Default::default(),
 253            installed_dir,
 254            index_path,
 255            builder: Arc::new(ExtensionBuilder::new(builder_client, build_dir)),
 256            outstanding_operations: Default::default(),
 257            modified_extensions: Default::default(),
 258            reload_complete_senders: Vec::new(),
 259            wasm_host: WasmHost::new(
 260                fs.clone(),
 261                http_client.clone(),
 262                node_runtime,
 263                extension_host_proxy,
 264                work_dir,
 265                cx,
 266            ),
 267            wasm_extensions: Vec::new(),
 268            fs,
 269            http_client,
 270            telemetry,
 271            reload_tx,
 272            tasks: Vec::new(),
 273
 274            remote_clients: HashMap::default(),
 275            ssh_registered_tx: connection_registered_tx,
 276        };
 277
 278        // The extensions store maintains an index file, which contains a complete
 279        // list of the installed extensions and the resources that they provide.
 280        // This index is loaded synchronously on startup.
 281        let (index_content, index_metadata, extensions_metadata) =
 282            cx.foreground_executor().block_on(async {
 283                futures::join!(
 284                    this.fs.load(&this.index_path),
 285                    this.fs.metadata(&this.index_path),
 286                    this.fs.metadata(&this.installed_dir),
 287                )
 288            });
 289
 290        // Normally, there is no need to rebuild the index. But if the index file
 291        // is invalid or is out-of-date according to the filesystem mtimes, then
 292        // it must be asynchronously rebuilt.
 293        let mut extension_index = ExtensionIndex::default();
 294        let mut extension_index_needs_rebuild = true;
 295        if let Ok(index_content) = index_content
 296            && let Some(index) = serde_json::from_str(&index_content).log_err()
 297        {
 298            extension_index = index;
 299            if let (Ok(Some(index_metadata)), Ok(Some(extensions_metadata))) =
 300                (index_metadata, extensions_metadata)
 301                && index_metadata
 302                    .mtime
 303                    .bad_is_greater_than(extensions_metadata.mtime)
 304            {
 305                extension_index_needs_rebuild = false;
 306            }
 307        }
 308
 309        // Immediately load all of the extensions in the initial manifest. If the
 310        // index needs to be rebuild, then enqueue
 311        let load_initial_extensions = this.extensions_updated(extension_index, cx);
 312        let mut reload_future = None;
 313        if extension_index_needs_rebuild {
 314            reload_future = Some(this.reload(None, cx));
 315        }
 316
 317        cx.spawn(async move |this, cx| {
 318            if let Some(future) = reload_future {
 319                future.await;
 320            }
 321            this.update(cx, |this, cx| this.auto_install_extensions(cx))
 322                .ok();
 323            this.update(cx, |this, cx| this.check_for_updates(cx)).ok();
 324        })
 325        .detach();
 326
 327        // Perform all extension loading in a single task to ensure that we
 328        // never attempt to simultaneously load/unload extensions from multiple
 329        // parallel tasks.
 330        this.tasks.push(cx.spawn(async move |this, cx| {
 331            async move {
 332                load_initial_extensions.await;
 333
 334                let mut index_changed = false;
 335                let mut debounce_timer = future::pending().boxed().fuse();
 336                loop {
 337                    select_biased! {
 338                        _ = debounce_timer => {
 339                            if index_changed {
 340                                let index = this
 341                                    .update(cx, |this, cx| this.rebuild_extension_index(cx))?
 342                                    .await;
 343                                this.update( cx, |this, cx| this.extensions_updated(index, cx))?
 344                                    .await;
 345                                index_changed = false;
 346                            }
 347
 348                            Self::update_ssh_clients(&this, cx).await?;
 349                        }
 350                        _ = connection_registered_rx.next() => {
 351                            debounce_timer = cx
 352                                .background_executor()
 353                                .timer(RELOAD_DEBOUNCE_DURATION)
 354                                .boxed()
 355                                .fuse();
 356                        }
 357                        extension_id = reload_rx.next() => {
 358                            let Some(extension_id) = extension_id else { break; };
 359                            this.update( cx, |this, _| {
 360                                this.modified_extensions.extend(extension_id);
 361                            })?;
 362                            index_changed = true;
 363                            debounce_timer = cx
 364                                .background_executor()
 365                                .timer(RELOAD_DEBOUNCE_DURATION)
 366                                .boxed()
 367                                .fuse();
 368                        }
 369                    }
 370                }
 371
 372                anyhow::Ok(())
 373            }
 374            .map(drop)
 375            .await;
 376        }));
 377
 378        // Watch the installed extensions directory for changes. Whenever changes are
 379        // detected, rebuild the extension index, and load/unload any extensions that
 380        // have been added, removed, or modified.
 381        this.tasks.push(cx.background_spawn({
 382            let fs = this.fs.clone();
 383            let reload_tx = this.reload_tx.clone();
 384            let installed_dir = this.installed_dir.clone();
 385            async move {
 386                let (mut paths, _) = fs.watch(&installed_dir, FS_WATCH_LATENCY).await;
 387                while let Some(events) = paths.next().await {
 388                    for event in events {
 389                        let Ok(event_path) = event.path.strip_prefix(&installed_dir) else {
 390                            continue;
 391                        };
 392
 393                        if let Some(path::Component::Normal(extension_dir_name)) =
 394                            event_path.components().next()
 395                            && let Some(extension_id) = extension_dir_name.to_str()
 396                        {
 397                            reload_tx.unbounded_send(Some(extension_id.into())).ok();
 398                        }
 399                    }
 400                }
 401            }
 402        }));
 403
 404        this
 405    }
 406
 407    pub fn reload(
 408        &mut self,
 409        modified_extension: Option<Arc<str>>,
 410        cx: &mut Context<Self>,
 411    ) -> impl Future<Output = ()> + use<> {
 412        let (tx, rx) = oneshot::channel();
 413        self.reload_complete_senders.push(tx);
 414        self.reload_tx
 415            .unbounded_send(modified_extension)
 416            .expect("reload task exited");
 417        cx.emit(Event::StartedReloading);
 418
 419        async move {
 420            rx.await.ok();
 421        }
 422    }
 423
 424    fn extensions_dir(&self) -> PathBuf {
 425        self.installed_dir.clone()
 426    }
 427
 428    pub fn outstanding_operations(&self) -> &BTreeMap<Arc<str>, ExtensionOperation> {
 429        &self.outstanding_operations
 430    }
 431
 432    pub fn installed_extensions(&self) -> &BTreeMap<Arc<str>, ExtensionIndexEntry> {
 433        &self.extension_index.extensions
 434    }
 435
 436    pub fn dev_extensions(&self) -> impl Iterator<Item = &Arc<ExtensionManifest>> {
 437        self.extension_index
 438            .extensions
 439            .values()
 440            .filter_map(|extension| extension.dev.then_some(&extension.manifest))
 441    }
 442
 443    pub fn extension_manifest_for_id(&self, extension_id: &str) -> Option<&Arc<ExtensionManifest>> {
 444        self.extension_index
 445            .extensions
 446            .get(extension_id)
 447            .map(|extension| &extension.manifest)
 448    }
 449
 450    /// Returns the names of themes provided by extensions.
 451    pub fn extension_themes<'a>(
 452        &'a self,
 453        extension_id: &'a str,
 454    ) -> impl Iterator<Item = &'a Arc<str>> {
 455        self.extension_index
 456            .themes
 457            .iter()
 458            .filter_map(|(name, theme)| theme.extension.as_ref().eq(extension_id).then_some(name))
 459    }
 460
 461    /// Returns the path to the theme file within an extension, if there is an
 462    /// extension that provides the theme.
 463    pub fn path_to_extension_theme(&self, theme_name: &str) -> Option<PathBuf> {
 464        let entry = self.extension_index.themes.get(theme_name)?;
 465
 466        Some(
 467            self.extensions_dir()
 468                .join(entry.extension.as_ref())
 469                .join(&entry.path),
 470        )
 471    }
 472
 473    /// Returns the names of icon themes provided by extensions.
 474    pub fn extension_icon_themes<'a>(
 475        &'a self,
 476        extension_id: &'a str,
 477    ) -> impl Iterator<Item = &'a Arc<str>> {
 478        self.extension_index
 479            .icon_themes
 480            .iter()
 481            .filter_map(|(name, icon_theme)| {
 482                icon_theme
 483                    .extension
 484                    .as_ref()
 485                    .eq(extension_id)
 486                    .then_some(name)
 487            })
 488    }
 489
 490    /// Returns the path to the icon theme file within an extension, if there is
 491    /// an extension that provides the icon theme.
 492    pub fn path_to_extension_icon_theme(
 493        &self,
 494        icon_theme_name: &str,
 495    ) -> Option<(PathBuf, PathBuf)> {
 496        let entry = self.extension_index.icon_themes.get(icon_theme_name)?;
 497
 498        let icon_theme_path = self
 499            .extensions_dir()
 500            .join(entry.extension.as_ref())
 501            .join(&entry.path);
 502        let icons_root_path = self.extensions_dir().join(entry.extension.as_ref());
 503
 504        Some((icon_theme_path, icons_root_path))
 505    }
 506
 507    pub fn fetch_extensions(
 508        &self,
 509        search: Option<&str>,
 510        provides_filter: Option<&BTreeSet<ExtensionProvides>>,
 511        cx: &mut Context<Self>,
 512    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 513        let version = CURRENT_SCHEMA_VERSION.to_string();
 514        let mut query = vec![("max_schema_version", version.as_str())];
 515        if let Some(search) = search {
 516            query.push(("filter", search));
 517        }
 518
 519        let provides_filter = provides_filter.map(|provides_filter| {
 520            provides_filter
 521                .iter()
 522                .map(|provides| provides.to_string())
 523                .collect::<Vec<_>>()
 524                .join(",")
 525        });
 526        if let Some(provides_filter) = provides_filter.as_deref() {
 527            query.push(("provides", provides_filter));
 528        }
 529
 530        self.fetch_extensions_from_api("/extensions", &query, cx)
 531    }
 532
 533    pub fn fetch_extensions_with_update_available(
 534        &mut self,
 535        cx: &mut Context<Self>,
 536    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 537        let schema_versions = schema_version_range();
 538        let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
 539        let extension_settings = ExtensionSettings::get_global(cx);
 540        let extension_ids = self
 541            .extension_index
 542            .extensions
 543            .iter()
 544            .filter(|(id, entry)| !entry.dev && extension_settings.should_auto_update(id))
 545            .map(|(id, _)| id.as_ref())
 546            .collect::<Vec<_>>()
 547            .join(",");
 548        let task = self.fetch_extensions_from_api(
 549            "/extensions/updates",
 550            &[
 551                ("min_schema_version", &schema_versions.start().to_string()),
 552                ("max_schema_version", &schema_versions.end().to_string()),
 553                (
 554                    "min_wasm_api_version",
 555                    &wasm_api_versions.start().to_string(),
 556                ),
 557                ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
 558                ("ids", &extension_ids),
 559            ],
 560            cx,
 561        );
 562        cx.spawn(async move |this, cx| {
 563            let extensions = task.await?;
 564            this.update(cx, |this, _cx| {
 565                extensions
 566                    .into_iter()
 567                    .filter(|extension| {
 568                        this.extension_index
 569                            .extensions
 570                            .get(&extension.id)
 571                            .is_none_or(|installed_extension| {
 572                                installed_extension.manifest.version != extension.manifest.version
 573                            })
 574                    })
 575                    .collect()
 576            })
 577        })
 578    }
 579
 580    pub fn fetch_extension_versions(
 581        &self,
 582        extension_id: &str,
 583        cx: &mut Context<Self>,
 584    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 585        self.fetch_extensions_from_api(&format!("/extensions/{extension_id}"), &[], cx)
 586    }
 587
 588    /// Installs any extensions that should be included with Zed by default.
 589    ///
 590    /// This can be used to make certain functionality provided by extensions
 591    /// available out-of-the-box.
 592    pub fn auto_install_extensions(&mut self, cx: &mut Context<Self>) {
 593        let extension_settings = ExtensionSettings::get_global(cx);
 594
 595        let extensions_to_install = extension_settings
 596            .auto_install_extensions
 597            .keys()
 598            .filter(|extension_id| extension_settings.should_auto_install(extension_id))
 599            .filter(|extension_id| {
 600                let is_already_installed = self
 601                    .extension_index
 602                    .extensions
 603                    .contains_key(extension_id.as_ref());
 604                !is_already_installed
 605            })
 606            .cloned()
 607            .collect::<Vec<_>>();
 608
 609        cx.spawn(async move |this, cx| {
 610            for extension_id in extensions_to_install {
 611                this.update(cx, |this, cx| {
 612                    this.install_latest_extension(extension_id.clone(), cx);
 613                })
 614                .ok();
 615            }
 616        })
 617        .detach();
 618    }
 619
 620    pub fn check_for_updates(&mut self, cx: &mut Context<Self>) {
 621        let task = self.fetch_extensions_with_update_available(cx);
 622        cx.spawn(async move |this, cx| Self::upgrade_extensions(this, task.await?, cx).await)
 623            .detach();
 624    }
 625
 626    async fn upgrade_extensions(
 627        this: WeakEntity<Self>,
 628        extensions: Vec<ExtensionMetadata>,
 629        cx: &mut AsyncApp,
 630    ) -> Result<()> {
 631        for extension in extensions {
 632            let task = this.update(cx, |this, cx| {
 633                if let Some(installed_extension) =
 634                    this.extension_index.extensions.get(&extension.id)
 635                {
 636                    let installed_version =
 637                        SemanticVersion::from_str(&installed_extension.manifest.version).ok()?;
 638                    let latest_version =
 639                        SemanticVersion::from_str(&extension.manifest.version).ok()?;
 640
 641                    if installed_version >= latest_version {
 642                        return None;
 643                    }
 644                }
 645
 646                Some(this.upgrade_extension(extension.id, extension.manifest.version, cx))
 647            })?;
 648
 649            if let Some(task) = task {
 650                task.await.log_err();
 651            }
 652        }
 653        anyhow::Ok(())
 654    }
 655
 656    fn fetch_extensions_from_api(
 657        &self,
 658        path: &str,
 659        query: &[(&str, &str)],
 660        cx: &mut Context<ExtensionStore>,
 661    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 662        let url = self.http_client.build_zed_api_url(path, query);
 663        let http_client = self.http_client.clone();
 664        cx.spawn(async move |_, _| {
 665            let mut response = http_client
 666                .get(url?.as_ref(), AsyncBody::empty(), true)
 667                .await?;
 668
 669            let mut body = Vec::new();
 670            response
 671                .body_mut()
 672                .read_to_end(&mut body)
 673                .await
 674                .context("error reading extensions")?;
 675
 676            if response.status().is_client_error() {
 677                let text = String::from_utf8_lossy(body.as_slice());
 678                bail!(
 679                    "status error {}, response: {text:?}",
 680                    response.status().as_u16()
 681                );
 682            }
 683
 684            let response: GetExtensionsResponse = serde_json::from_slice(&body)?;
 685            Ok(response.data)
 686        })
 687    }
 688
 689    pub fn install_extension(
 690        &mut self,
 691        extension_id: Arc<str>,
 692        version: Arc<str>,
 693        cx: &mut Context<Self>,
 694    ) {
 695        self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Install, cx)
 696            .detach_and_log_err(cx);
 697    }
 698
 699    fn install_or_upgrade_extension_at_endpoint(
 700        &mut self,
 701        extension_id: Arc<str>,
 702        url: Url,
 703        operation: ExtensionOperation,
 704        cx: &mut Context<Self>,
 705    ) -> Task<Result<()>> {
 706        let extension_dir = self.installed_dir.join(extension_id.as_ref());
 707        let http_client = self.http_client.clone();
 708        let fs = self.fs.clone();
 709
 710        match self.outstanding_operations.entry(extension_id.clone()) {
 711            btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
 712            btree_map::Entry::Vacant(e) => e.insert(operation),
 713        };
 714        cx.notify();
 715
 716        cx.spawn(async move |this, cx| {
 717            let _finish = cx.on_drop(&this, {
 718                let extension_id = extension_id.clone();
 719                move |this, cx| {
 720                    this.outstanding_operations.remove(extension_id.as_ref());
 721                    cx.notify();
 722                }
 723            });
 724
 725            let mut response = http_client
 726                .get(url.as_ref(), Default::default(), true)
 727                .await
 728                .context("downloading extension")?;
 729
 730            fs.remove_dir(
 731                &extension_dir,
 732                RemoveOptions {
 733                    recursive: true,
 734                    ignore_if_not_exists: true,
 735                },
 736            )
 737            .await?;
 738
 739            let content_length = response
 740                .headers()
 741                .get(http_client::http::header::CONTENT_LENGTH)
 742                .and_then(|value| value.to_str().ok()?.parse::<usize>().ok());
 743
 744            let mut body = BufReader::new(response.body_mut());
 745            let mut tar_gz_bytes = Vec::new();
 746            body.read_to_end(&mut tar_gz_bytes).await?;
 747
 748            if let Some(content_length) = content_length {
 749                let actual_len = tar_gz_bytes.len();
 750                if content_length != actual_len {
 751                    bail!("downloaded extension size {actual_len} does not match content length {content_length}");
 752                }
 753            }
 754            let decompressed_bytes = GzipDecoder::new(BufReader::new(tar_gz_bytes.as_slice()));
 755            let archive = Archive::new(decompressed_bytes);
 756            archive.unpack(extension_dir).await?;
 757            this.update( cx, |this, cx| {
 758                this.reload(Some(extension_id.clone()), cx)
 759            })?
 760            .await;
 761
 762            if let ExtensionOperation::Install = operation {
 763                this.update( cx, |this, cx| {
 764                    cx.emit(Event::ExtensionInstalled(extension_id.clone()));
 765                    if let Some(events) = ExtensionEvents::try_global(cx)
 766                        && let Some(manifest) = this.extension_manifest_for_id(&extension_id) {
 767                            events.update(cx, |this, cx| {
 768                                this.emit(
 769                                    extension::Event::ExtensionInstalled(manifest.clone()),
 770                                    cx,
 771                                )
 772                            });
 773                        }
 774                })
 775                .ok();
 776            }
 777
 778            anyhow::Ok(())
 779        })
 780    }
 781
 782    pub fn install_latest_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
 783        log::info!("installing extension {extension_id} latest version");
 784
 785        let schema_versions = schema_version_range();
 786        let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
 787
 788        let Some(url) = self
 789            .http_client
 790            .build_zed_api_url(
 791                &format!("/extensions/{extension_id}/download"),
 792                &[
 793                    ("min_schema_version", &schema_versions.start().to_string()),
 794                    ("max_schema_version", &schema_versions.end().to_string()),
 795                    (
 796                        "min_wasm_api_version",
 797                        &wasm_api_versions.start().to_string(),
 798                    ),
 799                    ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
 800                ],
 801            )
 802            .log_err()
 803        else {
 804            return;
 805        };
 806
 807        self.install_or_upgrade_extension_at_endpoint(
 808            extension_id,
 809            url,
 810            ExtensionOperation::Install,
 811            cx,
 812        )
 813        .detach_and_log_err(cx);
 814    }
 815
 816    pub fn upgrade_extension(
 817        &mut self,
 818        extension_id: Arc<str>,
 819        version: Arc<str>,
 820        cx: &mut Context<Self>,
 821    ) -> Task<Result<()>> {
 822        self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Upgrade, cx)
 823    }
 824
 825    fn install_or_upgrade_extension(
 826        &mut self,
 827        extension_id: Arc<str>,
 828        version: Arc<str>,
 829        operation: ExtensionOperation,
 830        cx: &mut Context<Self>,
 831    ) -> Task<Result<()>> {
 832        log::info!("installing extension {extension_id} {version}");
 833        let Some(url) = self
 834            .http_client
 835            .build_zed_api_url(
 836                &format!("/extensions/{extension_id}/{version}/download"),
 837                &[],
 838            )
 839            .log_err()
 840        else {
 841            return Task::ready(Ok(()));
 842        };
 843
 844        self.install_or_upgrade_extension_at_endpoint(extension_id, url, operation, cx)
 845    }
 846
 847    pub fn uninstall_extension(
 848        &mut self,
 849        extension_id: Arc<str>,
 850        cx: &mut Context<Self>,
 851    ) -> Task<Result<()>> {
 852        let extension_dir = self.installed_dir.join(extension_id.as_ref());
 853        let work_dir = self.wasm_host.work_dir.join(extension_id.as_ref());
 854        let fs = self.fs.clone();
 855
 856        let extension_manifest = self.extension_manifest_for_id(&extension_id).cloned();
 857
 858        match self.outstanding_operations.entry(extension_id.clone()) {
 859            btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
 860            btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
 861        };
 862
 863        cx.spawn(async move |extension_store, cx| {
 864            let _finish = cx.on_drop(&extension_store, {
 865                let extension_id = extension_id.clone();
 866                move |this, cx| {
 867                    this.outstanding_operations.remove(extension_id.as_ref());
 868                    cx.notify();
 869                }
 870            });
 871
 872            fs.remove_dir(
 873                &extension_dir,
 874                RemoveOptions {
 875                    recursive: true,
 876                    ignore_if_not_exists: true,
 877                },
 878            )
 879            .await
 880            .with_context(|| format!("Removing extension dir {extension_dir:?}"))?;
 881
 882            extension_store
 883                .update(cx, |extension_store, cx| extension_store.reload(None, cx))?
 884                .await;
 885
 886            // There's a race between wasm extension fully stopping and the directory removal.
 887            // On Windows, it's impossible to remove a directory that has a process running in it.
 888            for i in 0..3 {
 889                cx.background_executor()
 890                    .timer(Duration::from_millis(i * 100))
 891                    .await;
 892                let removal_result = fs
 893                    .remove_dir(
 894                        &work_dir,
 895                        RemoveOptions {
 896                            recursive: true,
 897                            ignore_if_not_exists: true,
 898                        },
 899                    )
 900                    .await;
 901                match removal_result {
 902                    Ok(()) => break,
 903                    Err(e) => {
 904                        if i == 2 {
 905                            log::error!("Failed to remove extension work dir {work_dir:?} : {e}");
 906                        }
 907                    }
 908                }
 909            }
 910
 911            extension_store.update(cx, |_, cx| {
 912                cx.emit(Event::ExtensionUninstalled(extension_id.clone()));
 913                if let Some(events) = ExtensionEvents::try_global(cx)
 914                    && let Some(manifest) = extension_manifest
 915                {
 916                    events.update(cx, |this, cx| {
 917                        this.emit(extension::Event::ExtensionUninstalled(manifest.clone()), cx)
 918                    });
 919                }
 920            })?;
 921
 922            anyhow::Ok(())
 923        })
 924    }
 925
 926    pub fn install_dev_extension(
 927        &mut self,
 928        extension_source_path: PathBuf,
 929        cx: &mut Context<Self>,
 930    ) -> Task<Result<()>> {
 931        let extensions_dir = self.extensions_dir();
 932        let fs = self.fs.clone();
 933        let builder = self.builder.clone();
 934
 935        cx.spawn(async move |this, cx| {
 936            let mut extension_manifest =
 937                ExtensionManifest::load(fs.clone(), &extension_source_path).await?;
 938            let extension_id = extension_manifest.id.clone();
 939
 940            if !this.update(cx, |this, cx| {
 941                match this.outstanding_operations.entry(extension_id.clone()) {
 942                    btree_map::Entry::Occupied(_) => return false,
 943                    btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
 944                };
 945                cx.notify();
 946                true
 947            })? {
 948                return Ok(());
 949            }
 950
 951            let _finish = cx.on_drop(&this, {
 952                let extension_id = extension_id.clone();
 953                move |this, cx| {
 954                    this.outstanding_operations.remove(extension_id.as_ref());
 955                    cx.notify();
 956                }
 957            });
 958
 959            cx.background_spawn({
 960                let extension_source_path = extension_source_path.clone();
 961                async move {
 962                    builder
 963                        .compile_extension(
 964                            &extension_source_path,
 965                            &mut extension_manifest,
 966                            CompileExtensionOptions { release: false },
 967                        )
 968                        .await
 969                }
 970            })
 971            .await
 972            .inspect_err(|error| {
 973                util::log_err(error);
 974            })?;
 975
 976            let output_path = &extensions_dir.join(extension_id.as_ref());
 977            if let Some(metadata) = fs.metadata(output_path).await? {
 978                if metadata.is_symlink {
 979                    fs.remove_file(
 980                        output_path,
 981                        RemoveOptions {
 982                            recursive: false,
 983                            ignore_if_not_exists: true,
 984                        },
 985                    )
 986                    .await?;
 987                } else {
 988                    bail!("extension {extension_id} is already installed");
 989                }
 990            }
 991
 992            fs.create_symlink(output_path, extension_source_path)
 993                .await?;
 994
 995            this.update(cx, |this, cx| this.reload(None, cx))?.await;
 996            this.update(cx, |this, cx| {
 997                cx.emit(Event::ExtensionInstalled(extension_id.clone()));
 998                if let Some(events) = ExtensionEvents::try_global(cx)
 999                    && let Some(manifest) = this.extension_manifest_for_id(&extension_id)
1000                {
1001                    events.update(cx, |this, cx| {
1002                        this.emit(extension::Event::ExtensionInstalled(manifest.clone()), cx)
1003                    });
1004                }
1005            })?;
1006
1007            Ok(())
1008        })
1009    }
1010
1011    pub fn rebuild_dev_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
1012        let path = self.installed_dir.join(extension_id.as_ref());
1013        let builder = self.builder.clone();
1014        let fs = self.fs.clone();
1015
1016        match self.outstanding_operations.entry(extension_id.clone()) {
1017            btree_map::Entry::Occupied(_) => return,
1018            btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Upgrade),
1019        };
1020
1021        cx.notify();
1022        let compile = cx.background_spawn(async move {
1023            let mut manifest = ExtensionManifest::load(fs, &path).await?;
1024            builder
1025                .compile_extension(
1026                    &path,
1027                    &mut manifest,
1028                    CompileExtensionOptions { release: true },
1029                )
1030                .await
1031        });
1032
1033        cx.spawn(async move |this, cx| {
1034            let result = compile.await;
1035
1036            this.update(cx, |this, cx| {
1037                this.outstanding_operations.remove(&extension_id);
1038                cx.notify();
1039            })?;
1040
1041            if result.is_ok() {
1042                this.update(cx, |this, cx| this.reload(Some(extension_id), cx))?
1043                    .await;
1044            }
1045
1046            result
1047        })
1048        .detach_and_log_err(cx)
1049    }
1050
1051    /// Updates the set of installed extensions.
1052    ///
1053    /// First, this unloads any themes, languages, or grammars that are
1054    /// no longer in the manifest, or whose files have changed on disk.
1055    /// Then it loads any themes, languages, or grammars that are newly
1056    /// added to the manifest, or whose files have changed on disk.
1057    fn extensions_updated(
1058        &mut self,
1059        mut new_index: ExtensionIndex,
1060        cx: &mut Context<Self>,
1061    ) -> Task<()> {
1062        let old_index = &self.extension_index;
1063
1064        // Determine which extensions need to be loaded and unloaded, based
1065        // on the changes to the manifest and the extensions that we know have been
1066        // modified.
1067        let mut extensions_to_unload = Vec::default();
1068        let mut extensions_to_load = Vec::default();
1069        {
1070            let mut old_keys = old_index.extensions.iter().peekable();
1071            let mut new_keys = new_index.extensions.iter().peekable();
1072            loop {
1073                match (old_keys.peek(), new_keys.peek()) {
1074                    (None, None) => break,
1075                    (None, Some(_)) => {
1076                        extensions_to_load.push(new_keys.next().unwrap().0.clone());
1077                    }
1078                    (Some(_), None) => {
1079                        extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1080                    }
1081                    (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(new_key) {
1082                        Ordering::Equal => {
1083                            let (old_key, old_value) = old_keys.next().unwrap();
1084                            let (new_key, new_value) = new_keys.next().unwrap();
1085                            if old_value != new_value || self.modified_extensions.contains(old_key)
1086                            {
1087                                extensions_to_unload.push(old_key.clone());
1088                                extensions_to_load.push(new_key.clone());
1089                            }
1090                        }
1091                        Ordering::Less => {
1092                            extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1093                        }
1094                        Ordering::Greater => {
1095                            extensions_to_load.push(new_keys.next().unwrap().0.clone());
1096                        }
1097                    },
1098                }
1099            }
1100            self.modified_extensions.clear();
1101        }
1102
1103        if extensions_to_load.is_empty() && extensions_to_unload.is_empty() {
1104            return Task::ready(());
1105        }
1106
1107        let reload_count = extensions_to_unload
1108            .iter()
1109            .filter(|id| extensions_to_load.contains(id))
1110            .count();
1111
1112        log::info!(
1113            "extensions updated. loading {}, reloading {}, unloading {}",
1114            extensions_to_load.len() - reload_count,
1115            reload_count,
1116            extensions_to_unload.len() - reload_count
1117        );
1118
1119        let extension_ids = extensions_to_load
1120            .iter()
1121            .filter_map(|id| {
1122                Some((
1123                    id.clone(),
1124                    new_index.extensions.get(id)?.manifest.version.clone(),
1125                ))
1126            })
1127            .collect::<Vec<_>>();
1128
1129        telemetry::event!("Extensions Loaded", id_and_versions = extension_ids);
1130
1131        let themes_to_remove = old_index
1132            .themes
1133            .iter()
1134            .filter_map(|(name, entry)| {
1135                if extensions_to_unload.contains(&entry.extension) {
1136                    Some(name.clone().into())
1137                } else {
1138                    None
1139                }
1140            })
1141            .collect::<Vec<_>>();
1142        let icon_themes_to_remove = old_index
1143            .icon_themes
1144            .iter()
1145            .filter_map(|(name, entry)| {
1146                if extensions_to_unload.contains(&entry.extension) {
1147                    Some(name.clone().into())
1148                } else {
1149                    None
1150                }
1151            })
1152            .collect::<Vec<_>>();
1153        let languages_to_remove = old_index
1154            .languages
1155            .iter()
1156            .filter_map(|(name, entry)| {
1157                if extensions_to_unload.contains(&entry.extension) {
1158                    Some(name.clone())
1159                } else {
1160                    None
1161                }
1162            })
1163            .collect::<Vec<_>>();
1164        let mut grammars_to_remove = Vec::new();
1165        let mut server_removal_tasks = Vec::with_capacity(extensions_to_unload.len());
1166        for extension_id in &extensions_to_unload {
1167            let Some(extension) = old_index.extensions.get(extension_id) else {
1168                continue;
1169            };
1170            grammars_to_remove.extend(extension.manifest.grammars.keys().cloned());
1171            for (language_server_name, config) in &extension.manifest.language_servers {
1172                for language in config.languages() {
1173                    server_removal_tasks.push(self.proxy.remove_language_server(
1174                        &language,
1175                        language_server_name,
1176                        cx,
1177                    ));
1178                }
1179            }
1180
1181            for server_id in extension.manifest.context_servers.keys() {
1182                self.proxy.unregister_context_server(server_id.clone(), cx);
1183            }
1184            for adapter in extension.manifest.debug_adapters.keys() {
1185                self.proxy.unregister_debug_adapter(adapter.clone());
1186            }
1187            for locator in extension.manifest.debug_locators.keys() {
1188                self.proxy.unregister_debug_locator(locator.clone());
1189            }
1190            for command_name in extension.manifest.slash_commands.keys() {
1191                self.proxy.unregister_slash_command(command_name.clone());
1192            }
1193        }
1194
1195        self.wasm_extensions
1196            .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
1197        self.proxy.remove_user_themes(themes_to_remove);
1198        self.proxy.remove_icon_themes(icon_themes_to_remove);
1199        self.proxy
1200            .remove_languages(&languages_to_remove, &grammars_to_remove);
1201
1202        let mut grammars_to_add = Vec::new();
1203        let mut themes_to_add = Vec::new();
1204        let mut icon_themes_to_add = Vec::new();
1205        let mut snippets_to_add = Vec::new();
1206        for extension_id in &extensions_to_load {
1207            let Some(extension) = new_index.extensions.get(extension_id) else {
1208                continue;
1209            };
1210
1211            grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
1212                let mut grammar_path = self.installed_dir.clone();
1213                grammar_path.extend([extension_id.as_ref(), "grammars"]);
1214                grammar_path.push(grammar_name.as_ref());
1215                grammar_path.set_extension("wasm");
1216                (grammar_name.clone(), grammar_path)
1217            }));
1218            themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
1219                let mut path = self.installed_dir.clone();
1220                path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1221                path
1222            }));
1223            icon_themes_to_add.extend(extension.manifest.icon_themes.iter().map(
1224                |icon_theme_path| {
1225                    let mut path = self.installed_dir.clone();
1226                    path.extend([Path::new(extension_id.as_ref()), icon_theme_path.as_path()]);
1227
1228                    let mut icons_root_path = self.installed_dir.clone();
1229                    icons_root_path.extend([Path::new(extension_id.as_ref())]);
1230
1231                    (path, icons_root_path)
1232                },
1233            ));
1234            snippets_to_add.extend(extension.manifest.snippets.iter().map(|snippets_path| {
1235                let mut path = self.installed_dir.clone();
1236                path.extend([Path::new(extension_id.as_ref()), snippets_path.as_path()]);
1237                path
1238            }));
1239        }
1240
1241        self.proxy.register_grammars(grammars_to_add);
1242        let languages_to_add = new_index
1243            .languages
1244            .iter_mut()
1245            .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
1246            .collect::<Vec<_>>();
1247        for (language_name, language) in languages_to_add {
1248            let mut language_path = self.installed_dir.clone();
1249            language_path.extend([
1250                Path::new(language.extension.as_ref()),
1251                language.path.as_path(),
1252            ]);
1253            self.proxy.register_language(
1254                language_name.clone(),
1255                language.grammar.clone(),
1256                language.matcher.clone(),
1257                language.hidden,
1258                Arc::new(move || {
1259                    let config = std::fs::read_to_string(language_path.join("config.toml"))?;
1260                    let config: LanguageConfig = ::toml::from_str(&config)?;
1261                    let queries = load_plugin_queries(&language_path);
1262                    let context_provider =
1263                        std::fs::read_to_string(language_path.join("tasks.json"))
1264                            .ok()
1265                            .and_then(|contents| {
1266                                let definitions =
1267                                    serde_json_lenient::from_str(&contents).log_err()?;
1268                                Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1269                            });
1270
1271                    Ok(LoadedLanguage {
1272                        config,
1273                        queries,
1274                        context_provider,
1275                        toolchain_provider: None,
1276                        manifest_name: None,
1277                    })
1278                }),
1279            );
1280        }
1281
1282        let fs = self.fs.clone();
1283        let wasm_host = self.wasm_host.clone();
1284        let root_dir = self.installed_dir.clone();
1285        let proxy = self.proxy.clone();
1286        let extension_entries = extensions_to_load
1287            .iter()
1288            .filter_map(|name| new_index.extensions.get(name).cloned())
1289            .collect::<Vec<_>>();
1290        self.extension_index = new_index;
1291        cx.notify();
1292        cx.emit(Event::ExtensionsUpdated);
1293
1294        cx.spawn(async move |this, cx| {
1295            cx.background_spawn({
1296                let fs = fs.clone();
1297                async move {
1298                    let _ = join_all(server_removal_tasks).await;
1299                    for theme_path in themes_to_add {
1300                        proxy
1301                            .load_user_theme(theme_path, fs.clone())
1302                            .await
1303                            .log_err();
1304                    }
1305
1306                    for (icon_theme_path, icons_root_path) in icon_themes_to_add {
1307                        proxy
1308                            .load_icon_theme(icon_theme_path, icons_root_path, fs.clone())
1309                            .await
1310                            .log_err();
1311                    }
1312
1313                    for snippets_path in &snippets_to_add {
1314                        match fs
1315                            .load(snippets_path)
1316                            .await
1317                            .with_context(|| format!("Loading snippets from {snippets_path:?}"))
1318                        {
1319                            Ok(snippets_contents) => {
1320                                proxy
1321                                    .register_snippet(snippets_path, &snippets_contents)
1322                                    .log_err();
1323                            }
1324                            Err(e) => log::error!("Cannot load snippets: {e:#}"),
1325                        }
1326                    }
1327                }
1328            })
1329            .await;
1330
1331            let mut wasm_extensions = Vec::new();
1332            for extension in extension_entries {
1333                if extension.manifest.lib.kind.is_none() {
1334                    continue;
1335                };
1336
1337                let extension_path = root_dir.join(extension.manifest.id.as_ref());
1338                let wasm_extension = WasmExtension::load(
1339                    &extension_path,
1340                    &extension.manifest,
1341                    wasm_host.clone(),
1342                    cx,
1343                )
1344                .await
1345                .with_context(|| format!("Loading extension from {extension_path:?}"));
1346
1347                match wasm_extension {
1348                    Ok(wasm_extension) => {
1349                        wasm_extensions.push((extension.manifest.clone(), wasm_extension))
1350                    }
1351                    Err(e) => {
1352                        log::error!("Failed to load extension: {e:#}");
1353                        this.update(cx, |_, cx| {
1354                            cx.emit(Event::ExtensionFailedToLoad(extension.manifest.id.clone()))
1355                        })
1356                        .ok();
1357                    }
1358                }
1359            }
1360
1361            this.update(cx, |this, cx| {
1362                this.reload_complete_senders.clear();
1363
1364                for (manifest, wasm_extension) in &wasm_extensions {
1365                    let extension = Arc::new(wasm_extension.clone());
1366
1367                    for (language_server_id, language_server_config) in &manifest.language_servers {
1368                        for language in language_server_config.languages() {
1369                            this.proxy.register_language_server(
1370                                extension.clone(),
1371                                language_server_id.clone(),
1372                                language.clone(),
1373                            );
1374                        }
1375                    }
1376
1377                    for (slash_command_name, slash_command) in &manifest.slash_commands {
1378                        this.proxy.register_slash_command(
1379                            extension.clone(),
1380                            extension::SlashCommand {
1381                                name: slash_command_name.to_string(),
1382                                description: slash_command.description.to_string(),
1383                                // We don't currently expose this as a configurable option, as it currently drives
1384                                // the `menu_text` on the `SlashCommand` trait, which is not used for slash commands
1385                                // defined in extensions, as they are not able to be added to the menu.
1386                                tooltip_text: String::new(),
1387                                requires_argument: slash_command.requires_argument,
1388                            },
1389                        );
1390                    }
1391
1392                    for id in manifest.context_servers.keys() {
1393                        this.proxy
1394                            .register_context_server(extension.clone(), id.clone(), cx);
1395                    }
1396
1397                    for (debug_adapter, meta) in &manifest.debug_adapters {
1398                        let mut path = root_dir.clone();
1399                        path.push(Path::new(manifest.id.as_ref()));
1400                        if let Some(schema_path) = &meta.schema_path {
1401                            path.push(schema_path);
1402                        } else {
1403                            path.push("debug_adapter_schemas");
1404                            path.push(Path::new(debug_adapter.as_ref()).with_extension("json"));
1405                        }
1406
1407                        this.proxy.register_debug_adapter(
1408                            extension.clone(),
1409                            debug_adapter.clone(),
1410                            &path,
1411                        );
1412                    }
1413
1414                    for debug_adapter in manifest.debug_locators.keys() {
1415                        this.proxy
1416                            .register_debug_locator(extension.clone(), debug_adapter.clone());
1417                    }
1418                }
1419
1420                this.wasm_extensions.extend(wasm_extensions);
1421                this.proxy.set_extensions_loaded();
1422                this.proxy.reload_current_theme(cx);
1423                this.proxy.reload_current_icon_theme(cx);
1424
1425                if let Some(events) = ExtensionEvents::try_global(cx) {
1426                    events.update(cx, |this, cx| {
1427                        this.emit(extension::Event::ExtensionsInstalledChanged, cx)
1428                    });
1429                }
1430            })
1431            .ok();
1432        })
1433    }
1434
1435    fn rebuild_extension_index(&self, cx: &mut Context<Self>) -> Task<ExtensionIndex> {
1436        let fs = self.fs.clone();
1437        let work_dir = self.wasm_host.work_dir.clone();
1438        let extensions_dir = self.installed_dir.clone();
1439        let index_path = self.index_path.clone();
1440        let proxy = self.proxy.clone();
1441        cx.background_spawn(async move {
1442            let start_time = Instant::now();
1443            let mut index = ExtensionIndex::default();
1444
1445            fs.create_dir(&work_dir).await.log_err();
1446            fs.create_dir(&extensions_dir).await.log_err();
1447
1448            let extension_paths = fs.read_dir(&extensions_dir).await;
1449            if let Ok(mut extension_paths) = extension_paths {
1450                while let Some(extension_dir) = extension_paths.next().await {
1451                    let Ok(extension_dir) = extension_dir else {
1452                        continue;
1453                    };
1454
1455                    if extension_dir
1456                        .file_name()
1457                        .is_some_and(|file_name| file_name == ".DS_Store")
1458                    {
1459                        continue;
1460                    }
1461
1462                    Self::add_extension_to_index(
1463                        fs.clone(),
1464                        extension_dir,
1465                        &mut index,
1466                        proxy.clone(),
1467                    )
1468                    .await
1469                    .log_err();
1470                }
1471            }
1472
1473            if let Ok(index_json) = serde_json::to_string_pretty(&index) {
1474                fs.save(&index_path, &index_json.as_str().into(), Default::default())
1475                    .await
1476                    .context("failed to save extension index")
1477                    .log_err();
1478            }
1479
1480            log::info!("rebuilt extension index in {:?}", start_time.elapsed());
1481            index
1482        })
1483    }
1484
1485    async fn add_extension_to_index(
1486        fs: Arc<dyn Fs>,
1487        extension_dir: PathBuf,
1488        index: &mut ExtensionIndex,
1489        proxy: Arc<ExtensionHostProxy>,
1490    ) -> Result<()> {
1491        let mut extension_manifest = ExtensionManifest::load(fs.clone(), &extension_dir).await?;
1492        let extension_id = extension_manifest.id.clone();
1493
1494        // TODO: distinguish dev extensions more explicitly, by the absence
1495        // of a checksum file that we'll create when downloading normal extensions.
1496        let is_dev = fs
1497            .metadata(&extension_dir)
1498            .await?
1499            .context("directory does not exist")?
1500            .is_symlink;
1501
1502        if let Ok(mut language_paths) = fs.read_dir(&extension_dir.join("languages")).await {
1503            while let Some(language_path) = language_paths.next().await {
1504                let language_path = language_path?;
1505                let Ok(relative_path) = language_path.strip_prefix(&extension_dir) else {
1506                    continue;
1507                };
1508                let Ok(Some(fs_metadata)) = fs.metadata(&language_path).await else {
1509                    continue;
1510                };
1511                if !fs_metadata.is_dir {
1512                    continue;
1513                }
1514                let config = fs.load(&language_path.join("config.toml")).await?;
1515                let config = ::toml::from_str::<LanguageConfig>(&config)?;
1516
1517                let relative_path = relative_path.to_path_buf();
1518                if !extension_manifest.languages.contains(&relative_path) {
1519                    extension_manifest.languages.push(relative_path.clone());
1520                }
1521
1522                index.languages.insert(
1523                    config.name.clone(),
1524                    ExtensionIndexLanguageEntry {
1525                        extension: extension_id.clone(),
1526                        path: relative_path,
1527                        matcher: config.matcher,
1528                        hidden: config.hidden,
1529                        grammar: config.grammar,
1530                    },
1531                );
1532            }
1533        }
1534
1535        if let Ok(mut theme_paths) = fs.read_dir(&extension_dir.join("themes")).await {
1536            while let Some(theme_path) = theme_paths.next().await {
1537                let theme_path = theme_path?;
1538                let Ok(relative_path) = theme_path.strip_prefix(&extension_dir) else {
1539                    continue;
1540                };
1541
1542                let Some(theme_families) = proxy
1543                    .list_theme_names(theme_path.clone(), fs.clone())
1544                    .await
1545                    .log_err()
1546                else {
1547                    continue;
1548                };
1549
1550                let relative_path = relative_path.to_path_buf();
1551                if !extension_manifest.themes.contains(&relative_path) {
1552                    extension_manifest.themes.push(relative_path.clone());
1553                }
1554
1555                for theme_name in theme_families {
1556                    index.themes.insert(
1557                        theme_name.into(),
1558                        ExtensionIndexThemeEntry {
1559                            extension: extension_id.clone(),
1560                            path: relative_path.clone(),
1561                        },
1562                    );
1563                }
1564            }
1565        }
1566
1567        if let Ok(mut icon_theme_paths) = fs.read_dir(&extension_dir.join("icon_themes")).await {
1568            while let Some(icon_theme_path) = icon_theme_paths.next().await {
1569                let icon_theme_path = icon_theme_path?;
1570                let Ok(relative_path) = icon_theme_path.strip_prefix(&extension_dir) else {
1571                    continue;
1572                };
1573
1574                let Some(icon_theme_families) = proxy
1575                    .list_icon_theme_names(icon_theme_path.clone(), fs.clone())
1576                    .await
1577                    .log_err()
1578                else {
1579                    continue;
1580                };
1581
1582                let relative_path = relative_path.to_path_buf();
1583                if !extension_manifest.icon_themes.contains(&relative_path) {
1584                    extension_manifest.icon_themes.push(relative_path.clone());
1585                }
1586
1587                for icon_theme_name in icon_theme_families {
1588                    index.icon_themes.insert(
1589                        icon_theme_name.into(),
1590                        ExtensionIndexIconThemeEntry {
1591                            extension: extension_id.clone(),
1592                            path: relative_path.clone(),
1593                        },
1594                    );
1595                }
1596            }
1597        }
1598
1599        let extension_wasm_path = extension_dir.join("extension.wasm");
1600        if fs.is_file(&extension_wasm_path).await {
1601            extension_manifest
1602                .lib
1603                .kind
1604                .get_or_insert(ExtensionLibraryKind::Rust);
1605        }
1606
1607        index.extensions.insert(
1608            extension_id.clone(),
1609            ExtensionIndexEntry {
1610                dev: is_dev,
1611                manifest: Arc::new(extension_manifest),
1612            },
1613        );
1614
1615        Ok(())
1616    }
1617
1618    fn prepare_remote_extension(
1619        &mut self,
1620        extension_id: Arc<str>,
1621        is_dev: bool,
1622        tmp_dir: PathBuf,
1623        cx: &mut Context<Self>,
1624    ) -> Task<Result<()>> {
1625        let src_dir = self.extensions_dir().join(extension_id.as_ref());
1626        let Some(loaded_extension) = self.extension_index.extensions.get(&extension_id).cloned()
1627        else {
1628            return Task::ready(Err(anyhow!("extension no longer installed")));
1629        };
1630        let fs = self.fs.clone();
1631        cx.background_spawn(async move {
1632            const EXTENSION_TOML: &str = "extension.toml";
1633            const EXTENSION_WASM: &str = "extension.wasm";
1634            const CONFIG_TOML: &str = "config.toml";
1635
1636            if is_dev {
1637                let manifest_toml = toml::to_string(&loaded_extension.manifest)?;
1638                fs.save(
1639                    &tmp_dir.join(EXTENSION_TOML),
1640                    &Rope::from(manifest_toml),
1641                    language::LineEnding::Unix,
1642                )
1643                .await?;
1644            } else {
1645                fs.copy_file(
1646                    &src_dir.join(EXTENSION_TOML),
1647                    &tmp_dir.join(EXTENSION_TOML),
1648                    fs::CopyOptions::default(),
1649                )
1650                .await?
1651            }
1652
1653            if fs.is_file(&src_dir.join(EXTENSION_WASM)).await {
1654                fs.copy_file(
1655                    &src_dir.join(EXTENSION_WASM),
1656                    &tmp_dir.join(EXTENSION_WASM),
1657                    fs::CopyOptions::default(),
1658                )
1659                .await?
1660            }
1661
1662            for language_path in loaded_extension.manifest.languages.iter() {
1663                if fs
1664                    .is_file(&src_dir.join(language_path).join(CONFIG_TOML))
1665                    .await
1666                {
1667                    fs.create_dir(&tmp_dir.join(language_path)).await?;
1668                    fs.copy_file(
1669                        &src_dir.join(language_path).join(CONFIG_TOML),
1670                        &tmp_dir.join(language_path).join(CONFIG_TOML),
1671                        fs::CopyOptions::default(),
1672                    )
1673                    .await?
1674                }
1675            }
1676
1677            for (adapter_name, meta) in loaded_extension.manifest.debug_adapters.iter() {
1678                let schema_path = &extension::build_debug_adapter_schema_path(adapter_name, meta);
1679
1680                if fs.is_file(&src_dir.join(schema_path)).await {
1681                    if let Some(parent) = schema_path.parent() {
1682                        fs.create_dir(&tmp_dir.join(parent)).await?
1683                    }
1684                    fs.copy_file(
1685                        &src_dir.join(schema_path),
1686                        &tmp_dir.join(schema_path),
1687                        fs::CopyOptions::default(),
1688                    )
1689                    .await?
1690                }
1691            }
1692
1693            Ok(())
1694        })
1695    }
1696
1697    async fn sync_extensions_over_ssh(
1698        this: &WeakEntity<Self>,
1699        client: WeakEntity<RemoteClient>,
1700        cx: &mut AsyncApp,
1701    ) -> Result<()> {
1702        let extensions = this.update(cx, |this, _cx| {
1703            this.extension_index
1704                .extensions
1705                .iter()
1706                .filter_map(|(id, entry)| {
1707                    if !entry.manifest.allow_remote_load() {
1708                        return None;
1709                    }
1710                    Some(proto::Extension {
1711                        id: id.to_string(),
1712                        version: entry.manifest.version.to_string(),
1713                        dev: entry.dev,
1714                    })
1715                })
1716                .collect()
1717        })?;
1718
1719        let response = client
1720            .update(cx, |client, _cx| {
1721                client
1722                    .proto_client()
1723                    .request(proto::SyncExtensions { extensions })
1724            })?
1725            .await?;
1726        let path_style = client.read_with(cx, |client, _| client.path_style())?;
1727
1728        for missing_extension in response.missing_extensions.into_iter() {
1729            let tmp_dir = tempfile::tempdir()?;
1730            this.update(cx, |this, cx| {
1731                this.prepare_remote_extension(
1732                    missing_extension.id.clone().into(),
1733                    missing_extension.dev,
1734                    tmp_dir.path().to_owned(),
1735                    cx,
1736                )
1737            })?
1738            .await?;
1739            let dest_dir = RemotePathBuf::new(
1740                PathBuf::from(&response.tmp_dir).join(missing_extension.clone().id),
1741                path_style,
1742            );
1743            log::info!("Uploading extension {}", missing_extension.clone().id);
1744
1745            client
1746                .update(cx, |client, cx| {
1747                    client.upload_directory(tmp_dir.path().to_owned(), dest_dir.clone(), cx)
1748                })?
1749                .await?;
1750
1751            log::info!(
1752                "Finished uploading extension {}",
1753                missing_extension.clone().id
1754            );
1755
1756            client
1757                .update(cx, |client, _cx| {
1758                    client.proto_client().request(proto::InstallExtension {
1759                        tmp_dir: dest_dir.to_proto(),
1760                        extension: Some(missing_extension),
1761                    })
1762                })?
1763                .await?;
1764        }
1765
1766        anyhow::Ok(())
1767    }
1768
1769    pub async fn update_ssh_clients(this: &WeakEntity<Self>, cx: &mut AsyncApp) -> Result<()> {
1770        let clients = this.update(cx, |this, _cx| {
1771            this.remote_clients.retain(|_k, v| v.upgrade().is_some());
1772            this.remote_clients.values().cloned().collect::<Vec<_>>()
1773        })?;
1774
1775        for client in clients {
1776            Self::sync_extensions_over_ssh(this, client, cx)
1777                .await
1778                .log_err();
1779        }
1780
1781        anyhow::Ok(())
1782    }
1783
1784    pub fn register_remote_client(&mut self, client: Entity<RemoteClient>, cx: &mut Context<Self>) {
1785        let options = client.read(cx).connection_options();
1786
1787        if let Some(existing_client) = self.remote_clients.get(&options)
1788            && existing_client.upgrade().is_some()
1789        {
1790            return;
1791        }
1792
1793        self.remote_clients.insert(options, client.downgrade());
1794        self.ssh_registered_tx.unbounded_send(()).ok();
1795    }
1796}
1797
1798fn load_plugin_queries(root_path: &Path) -> LanguageQueries {
1799    let mut result = LanguageQueries::default();
1800    if let Some(entries) = std::fs::read_dir(root_path).log_err() {
1801        for entry in entries {
1802            let Some(entry) = entry.log_err() else {
1803                continue;
1804            };
1805            let path = entry.path();
1806            if let Some(remainder) = path.strip_prefix(root_path).ok().and_then(|p| p.to_str()) {
1807                if !remainder.ends_with(".scm") {
1808                    continue;
1809                }
1810                for (name, query) in QUERY_FILENAME_PREFIXES {
1811                    if remainder.starts_with(name) {
1812                        if let Some(contents) = std::fs::read_to_string(&path).log_err() {
1813                            match query(&mut result) {
1814                                None => *query(&mut result) = Some(contents.into()),
1815                                Some(r) => r.to_mut().push_str(contents.as_ref()),
1816                            }
1817                        }
1818                        break;
1819                    }
1820                }
1821            }
1822        }
1823    }
1824    result
1825}