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