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