extension_host.rs

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