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 = ()> {
 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                &work_dir,
 842                RemoveOptions {
 843                    recursive: true,
 844                    ignore_if_not_exists: true,
 845                },
 846            )
 847            .await?;
 848
 849            fs.remove_dir(
 850                &extension_dir,
 851                RemoveOptions {
 852                    recursive: true,
 853                    ignore_if_not_exists: true,
 854                },
 855            )
 856            .await?;
 857
 858            this.update(cx, |this, cx| this.reload(None, cx))?.await;
 859            anyhow::Ok(())
 860        })
 861        .detach_and_log_err(cx)
 862    }
 863
 864    pub fn install_dev_extension(
 865        &mut self,
 866        extension_source_path: PathBuf,
 867        cx: &mut Context<Self>,
 868    ) -> Task<Result<()>> {
 869        let extensions_dir = self.extensions_dir();
 870        let fs = self.fs.clone();
 871        let builder = self.builder.clone();
 872
 873        cx.spawn(async move |this, cx| {
 874            let mut extension_manifest =
 875                ExtensionManifest::load(fs.clone(), &extension_source_path).await?;
 876            let extension_id = extension_manifest.id.clone();
 877
 878            if !this.update(cx, |this, cx| {
 879                match this.outstanding_operations.entry(extension_id.clone()) {
 880                    btree_map::Entry::Occupied(_) => return false,
 881                    btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
 882                };
 883                cx.notify();
 884                true
 885            })? {
 886                return Ok(());
 887            }
 888
 889            let _finish = cx.on_drop(&this, {
 890                let extension_id = extension_id.clone();
 891                move |this, cx| {
 892                    this.outstanding_operations.remove(extension_id.as_ref());
 893                    cx.notify();
 894                }
 895            });
 896
 897            cx.background_spawn({
 898                let extension_source_path = extension_source_path.clone();
 899                async move {
 900                    builder
 901                        .compile_extension(
 902                            &extension_source_path,
 903                            &mut extension_manifest,
 904                            CompileExtensionOptions { release: false },
 905                        )
 906                        .await
 907                }
 908            })
 909            .await?;
 910
 911            let output_path = &extensions_dir.join(extension_id.as_ref());
 912            if let Some(metadata) = fs.metadata(output_path).await? {
 913                if metadata.is_symlink {
 914                    fs.remove_file(
 915                        output_path,
 916                        RemoveOptions {
 917                            recursive: false,
 918                            ignore_if_not_exists: true,
 919                        },
 920                    )
 921                    .await?;
 922                } else {
 923                    bail!("extension {extension_id} is already installed");
 924                }
 925            }
 926
 927            fs.create_symlink(output_path, extension_source_path)
 928                .await?;
 929
 930            this.update(cx, |this, cx| this.reload(None, cx))?.await;
 931            Ok(())
 932        })
 933    }
 934
 935    pub fn rebuild_dev_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
 936        let path = self.installed_dir.join(extension_id.as_ref());
 937        let builder = self.builder.clone();
 938        let fs = self.fs.clone();
 939
 940        match self.outstanding_operations.entry(extension_id.clone()) {
 941            btree_map::Entry::Occupied(_) => return,
 942            btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Upgrade),
 943        };
 944
 945        cx.notify();
 946        let compile = cx.background_spawn(async move {
 947            let mut manifest = ExtensionManifest::load(fs, &path).await?;
 948            builder
 949                .compile_extension(
 950                    &path,
 951                    &mut manifest,
 952                    CompileExtensionOptions { release: true },
 953                )
 954                .await
 955        });
 956
 957        cx.spawn(async move |this, cx| {
 958            let result = compile.await;
 959
 960            this.update(cx, |this, cx| {
 961                this.outstanding_operations.remove(&extension_id);
 962                cx.notify();
 963            })?;
 964
 965            if result.is_ok() {
 966                this.update(cx, |this, cx| this.reload(Some(extension_id), cx))?
 967                    .await;
 968            }
 969
 970            result
 971        })
 972        .detach_and_log_err(cx)
 973    }
 974
 975    /// Updates the set of installed extensions.
 976    ///
 977    /// First, this unloads any themes, languages, or grammars that are
 978    /// no longer in the manifest, or whose files have changed on disk.
 979    /// Then it loads any themes, languages, or grammars that are newly
 980    /// added to the manifest, or whose files have changed on disk.
 981    fn extensions_updated(
 982        &mut self,
 983        new_index: ExtensionIndex,
 984        cx: &mut Context<Self>,
 985    ) -> Task<()> {
 986        let old_index = &self.extension_index;
 987
 988        // Determine which extensions need to be loaded and unloaded, based
 989        // on the changes to the manifest and the extensions that we know have been
 990        // modified.
 991        let mut extensions_to_unload = Vec::default();
 992        let mut extensions_to_load = Vec::default();
 993        {
 994            let mut old_keys = old_index.extensions.iter().peekable();
 995            let mut new_keys = new_index.extensions.iter().peekable();
 996            loop {
 997                match (old_keys.peek(), new_keys.peek()) {
 998                    (None, None) => break,
 999                    (None, Some(_)) => {
1000                        extensions_to_load.push(new_keys.next().unwrap().0.clone());
1001                    }
1002                    (Some(_), None) => {
1003                        extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1004                    }
1005                    (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(new_key) {
1006                        Ordering::Equal => {
1007                            let (old_key, old_value) = old_keys.next().unwrap();
1008                            let (new_key, new_value) = new_keys.next().unwrap();
1009                            if old_value != new_value || self.modified_extensions.contains(old_key)
1010                            {
1011                                extensions_to_unload.push(old_key.clone());
1012                                extensions_to_load.push(new_key.clone());
1013                            }
1014                        }
1015                        Ordering::Less => {
1016                            extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1017                        }
1018                        Ordering::Greater => {
1019                            extensions_to_load.push(new_keys.next().unwrap().0.clone());
1020                        }
1021                    },
1022                }
1023            }
1024            self.modified_extensions.clear();
1025        }
1026
1027        if extensions_to_load.is_empty() && extensions_to_unload.is_empty() {
1028            return Task::ready(());
1029        }
1030
1031        let reload_count = extensions_to_unload
1032            .iter()
1033            .filter(|id| extensions_to_load.contains(id))
1034            .count();
1035
1036        log::info!(
1037            "extensions updated. loading {}, reloading {}, unloading {}",
1038            extensions_to_load.len() - reload_count,
1039            reload_count,
1040            extensions_to_unload.len() - reload_count
1041        );
1042
1043        for extension_id in &extensions_to_load {
1044            if let Some(extension) = new_index.extensions.get(extension_id) {
1045                telemetry::event!(
1046                    "Extension Loaded",
1047                    extension_id,
1048                    version = extension.manifest.version
1049                );
1050            }
1051        }
1052
1053        let themes_to_remove = old_index
1054            .themes
1055            .iter()
1056            .filter_map(|(name, entry)| {
1057                if extensions_to_unload.contains(&entry.extension) {
1058                    Some(name.clone().into())
1059                } else {
1060                    None
1061                }
1062            })
1063            .collect::<Vec<_>>();
1064        let icon_themes_to_remove = old_index
1065            .icon_themes
1066            .iter()
1067            .filter_map(|(name, entry)| {
1068                if extensions_to_unload.contains(&entry.extension) {
1069                    Some(name.clone().into())
1070                } else {
1071                    None
1072                }
1073            })
1074            .collect::<Vec<_>>();
1075        let languages_to_remove = old_index
1076            .languages
1077            .iter()
1078            .filter_map(|(name, entry)| {
1079                if extensions_to_unload.contains(&entry.extension) {
1080                    Some(name.clone())
1081                } else {
1082                    None
1083                }
1084            })
1085            .collect::<Vec<_>>();
1086        let mut grammars_to_remove = Vec::new();
1087        for extension_id in &extensions_to_unload {
1088            let Some(extension) = old_index.extensions.get(extension_id) else {
1089                continue;
1090            };
1091            grammars_to_remove.extend(extension.manifest.grammars.keys().cloned());
1092            for (language_server_name, config) in extension.manifest.language_servers.iter() {
1093                for language in config.languages() {
1094                    self.proxy
1095                        .remove_language_server(&language, language_server_name);
1096                }
1097            }
1098        }
1099
1100        self.wasm_extensions
1101            .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
1102        self.proxy.remove_user_themes(themes_to_remove);
1103        self.proxy.remove_icon_themes(icon_themes_to_remove);
1104        self.proxy
1105            .remove_languages(&languages_to_remove, &grammars_to_remove);
1106
1107        let languages_to_add = new_index
1108            .languages
1109            .iter()
1110            .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
1111            .collect::<Vec<_>>();
1112        let mut grammars_to_add = Vec::new();
1113        let mut themes_to_add = Vec::new();
1114        let mut icon_themes_to_add = Vec::new();
1115        let mut snippets_to_add = Vec::new();
1116        for extension_id in &extensions_to_load {
1117            let Some(extension) = new_index.extensions.get(extension_id) else {
1118                continue;
1119            };
1120
1121            grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
1122                let mut grammar_path = self.installed_dir.clone();
1123                grammar_path.extend([extension_id.as_ref(), "grammars"]);
1124                grammar_path.push(grammar_name.as_ref());
1125                grammar_path.set_extension("wasm");
1126                (grammar_name.clone(), grammar_path)
1127            }));
1128            themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
1129                let mut path = self.installed_dir.clone();
1130                path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1131                path
1132            }));
1133            icon_themes_to_add.extend(extension.manifest.icon_themes.iter().map(
1134                |icon_theme_path| {
1135                    let mut path = self.installed_dir.clone();
1136                    path.extend([Path::new(extension_id.as_ref()), icon_theme_path.as_path()]);
1137
1138                    let mut icons_root_path = self.installed_dir.clone();
1139                    icons_root_path.extend([Path::new(extension_id.as_ref())]);
1140
1141                    (path, icons_root_path)
1142                },
1143            ));
1144            snippets_to_add.extend(extension.manifest.snippets.iter().map(|snippets_path| {
1145                let mut path = self.installed_dir.clone();
1146                path.extend([Path::new(extension_id.as_ref()), snippets_path.as_path()]);
1147                path
1148            }));
1149        }
1150
1151        self.proxy.register_grammars(grammars_to_add);
1152
1153        for (language_name, language) in languages_to_add {
1154            let mut language_path = self.installed_dir.clone();
1155            language_path.extend([
1156                Path::new(language.extension.as_ref()),
1157                language.path.as_path(),
1158            ]);
1159            self.proxy.register_language(
1160                language_name.clone(),
1161                language.grammar.clone(),
1162                language.matcher.clone(),
1163                language.hidden,
1164                Arc::new(move || {
1165                    let config = std::fs::read_to_string(language_path.join("config.toml"))?;
1166                    let config: LanguageConfig = ::toml::from_str(&config)?;
1167                    let queries = load_plugin_queries(&language_path);
1168                    let context_provider =
1169                        std::fs::read_to_string(language_path.join("tasks.json"))
1170                            .ok()
1171                            .and_then(|contents| {
1172                                let definitions =
1173                                    serde_json_lenient::from_str(&contents).log_err()?;
1174                                Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1175                            });
1176
1177                    Ok(LoadedLanguage {
1178                        config,
1179                        queries,
1180                        context_provider,
1181                        toolchain_provider: None,
1182                    })
1183                }),
1184            );
1185        }
1186
1187        let fs = self.fs.clone();
1188        let wasm_host = self.wasm_host.clone();
1189        let root_dir = self.installed_dir.clone();
1190        let proxy = self.proxy.clone();
1191        let extension_entries = extensions_to_load
1192            .iter()
1193            .filter_map(|name| new_index.extensions.get(name).cloned())
1194            .collect::<Vec<_>>();
1195
1196        self.extension_index = new_index;
1197        cx.notify();
1198        cx.emit(Event::ExtensionsUpdated);
1199
1200        cx.spawn(async move |this, cx| {
1201            cx.background_spawn({
1202                let fs = fs.clone();
1203                async move {
1204                    for theme_path in themes_to_add.into_iter() {
1205                        proxy
1206                            .load_user_theme(theme_path, fs.clone())
1207                            .await
1208                            .log_err();
1209                    }
1210
1211                    for (icon_theme_path, icons_root_path) in icon_themes_to_add.into_iter() {
1212                        proxy
1213                            .load_icon_theme(icon_theme_path, icons_root_path, fs.clone())
1214                            .await
1215                            .log_err();
1216                    }
1217
1218                    for snippets_path in &snippets_to_add {
1219                        if let Some(snippets_contents) = fs.load(snippets_path).await.log_err() {
1220                            proxy
1221                                .register_snippet(snippets_path, &snippets_contents)
1222                                .log_err();
1223                        }
1224                    }
1225                }
1226            })
1227            .await;
1228
1229            let mut wasm_extensions = Vec::new();
1230            for extension in extension_entries {
1231                if extension.manifest.lib.kind.is_none() {
1232                    continue;
1233                };
1234
1235                let extension_path = root_dir.join(extension.manifest.id.as_ref());
1236                let wasm_extension = WasmExtension::load(
1237                    extension_path,
1238                    &extension.manifest,
1239                    wasm_host.clone(),
1240                    &cx,
1241                )
1242                .await;
1243
1244                if let Some(wasm_extension) = wasm_extension.log_err() {
1245                    wasm_extensions.push((extension.manifest.clone(), wasm_extension));
1246                } else {
1247                    this.update(cx, |_, cx| {
1248                        cx.emit(Event::ExtensionFailedToLoad(extension.manifest.id.clone()))
1249                    })
1250                    .ok();
1251                }
1252            }
1253
1254            this.update(cx, |this, cx| {
1255                this.reload_complete_senders.clear();
1256
1257                for (manifest, wasm_extension) in &wasm_extensions {
1258                    let extension = Arc::new(wasm_extension.clone());
1259
1260                    for (language_server_id, language_server_config) in &manifest.language_servers {
1261                        for language in language_server_config.languages() {
1262                            this.proxy.register_language_server(
1263                                extension.clone(),
1264                                language_server_id.clone(),
1265                                language.clone(),
1266                            );
1267                        }
1268                    }
1269
1270                    for (slash_command_name, slash_command) in &manifest.slash_commands {
1271                        this.proxy.register_slash_command(
1272                            extension.clone(),
1273                            extension::SlashCommand {
1274                                name: slash_command_name.to_string(),
1275                                description: slash_command.description.to_string(),
1276                                // We don't currently expose this as a configurable option, as it currently drives
1277                                // the `menu_text` on the `SlashCommand` trait, which is not used for slash commands
1278                                // defined in extensions, as they are not able to be added to the menu.
1279                                tooltip_text: String::new(),
1280                                requires_argument: slash_command.requires_argument,
1281                            },
1282                        );
1283                    }
1284
1285                    for (id, _context_server_entry) in &manifest.context_servers {
1286                        this.proxy
1287                            .register_context_server(extension.clone(), id.clone(), cx);
1288                    }
1289
1290                    for (provider_id, _provider) in &manifest.indexed_docs_providers {
1291                        this.proxy
1292                            .register_indexed_docs_provider(extension.clone(), provider_id.clone());
1293                    }
1294                }
1295
1296                this.wasm_extensions.extend(wasm_extensions);
1297                this.proxy.set_extensions_loaded();
1298                this.proxy.reload_current_theme(cx);
1299                this.proxy.reload_current_icon_theme(cx);
1300
1301                if let Some(events) = ExtensionEvents::try_global(cx) {
1302                    events.update(cx, |this, cx| {
1303                        this.emit(extension::Event::ExtensionsInstalledChanged, cx)
1304                    });
1305                }
1306            })
1307            .ok();
1308        })
1309    }
1310
1311    fn rebuild_extension_index(&self, cx: &mut Context<Self>) -> Task<ExtensionIndex> {
1312        let fs = self.fs.clone();
1313        let work_dir = self.wasm_host.work_dir.clone();
1314        let extensions_dir = self.installed_dir.clone();
1315        let index_path = self.index_path.clone();
1316        let proxy = self.proxy.clone();
1317        cx.background_spawn(async move {
1318            let start_time = Instant::now();
1319            let mut index = ExtensionIndex::default();
1320
1321            fs.create_dir(&work_dir).await.log_err();
1322            fs.create_dir(&extensions_dir).await.log_err();
1323
1324            let extension_paths = fs.read_dir(&extensions_dir).await;
1325            if let Ok(mut extension_paths) = extension_paths {
1326                while let Some(extension_dir) = extension_paths.next().await {
1327                    let Ok(extension_dir) = extension_dir else {
1328                        continue;
1329                    };
1330
1331                    if extension_dir
1332                        .file_name()
1333                        .map_or(false, |file_name| file_name == ".DS_Store")
1334                    {
1335                        continue;
1336                    }
1337
1338                    Self::add_extension_to_index(
1339                        fs.clone(),
1340                        extension_dir,
1341                        &mut index,
1342                        proxy.clone(),
1343                    )
1344                    .await
1345                    .log_err();
1346                }
1347            }
1348
1349            if let Ok(index_json) = serde_json::to_string_pretty(&index) {
1350                fs.save(&index_path, &index_json.as_str().into(), Default::default())
1351                    .await
1352                    .context("failed to save extension index")
1353                    .log_err();
1354            }
1355
1356            log::info!("rebuilt extension index in {:?}", start_time.elapsed());
1357            index
1358        })
1359    }
1360
1361    async fn add_extension_to_index(
1362        fs: Arc<dyn Fs>,
1363        extension_dir: PathBuf,
1364        index: &mut ExtensionIndex,
1365        proxy: Arc<ExtensionHostProxy>,
1366    ) -> Result<()> {
1367        let mut extension_manifest = ExtensionManifest::load(fs.clone(), &extension_dir).await?;
1368        let extension_id = extension_manifest.id.clone();
1369
1370        // TODO: distinguish dev extensions more explicitly, by the absence
1371        // of a checksum file that we'll create when downloading normal extensions.
1372        let is_dev = fs
1373            .metadata(&extension_dir)
1374            .await?
1375            .ok_or_else(|| anyhow!("directory does not exist"))?
1376            .is_symlink;
1377
1378        if let Ok(mut language_paths) = fs.read_dir(&extension_dir.join("languages")).await {
1379            while let Some(language_path) = language_paths.next().await {
1380                let language_path = language_path?;
1381                let Ok(relative_path) = language_path.strip_prefix(&extension_dir) else {
1382                    continue;
1383                };
1384                let Ok(Some(fs_metadata)) = fs.metadata(&language_path).await else {
1385                    continue;
1386                };
1387                if !fs_metadata.is_dir {
1388                    continue;
1389                }
1390                let config = fs.load(&language_path.join("config.toml")).await?;
1391                let config = ::toml::from_str::<LanguageConfig>(&config)?;
1392
1393                let relative_path = relative_path.to_path_buf();
1394                if !extension_manifest.languages.contains(&relative_path) {
1395                    extension_manifest.languages.push(relative_path.clone());
1396                }
1397
1398                index.languages.insert(
1399                    config.name.clone(),
1400                    ExtensionIndexLanguageEntry {
1401                        extension: extension_id.clone(),
1402                        path: relative_path,
1403                        matcher: config.matcher,
1404                        hidden: config.hidden,
1405                        grammar: config.grammar,
1406                    },
1407                );
1408            }
1409        }
1410
1411        if let Ok(mut theme_paths) = fs.read_dir(&extension_dir.join("themes")).await {
1412            while let Some(theme_path) = theme_paths.next().await {
1413                let theme_path = theme_path?;
1414                let Ok(relative_path) = theme_path.strip_prefix(&extension_dir) else {
1415                    continue;
1416                };
1417
1418                let Some(theme_families) = proxy
1419                    .list_theme_names(theme_path.clone(), fs.clone())
1420                    .await
1421                    .log_err()
1422                else {
1423                    continue;
1424                };
1425
1426                let relative_path = relative_path.to_path_buf();
1427                if !extension_manifest.themes.contains(&relative_path) {
1428                    extension_manifest.themes.push(relative_path.clone());
1429                }
1430
1431                for theme_name in theme_families {
1432                    index.themes.insert(
1433                        theme_name.into(),
1434                        ExtensionIndexThemeEntry {
1435                            extension: extension_id.clone(),
1436                            path: relative_path.clone(),
1437                        },
1438                    );
1439                }
1440            }
1441        }
1442
1443        if let Ok(mut icon_theme_paths) = fs.read_dir(&extension_dir.join("icon_themes")).await {
1444            while let Some(icon_theme_path) = icon_theme_paths.next().await {
1445                let icon_theme_path = icon_theme_path?;
1446                let Ok(relative_path) = icon_theme_path.strip_prefix(&extension_dir) else {
1447                    continue;
1448                };
1449
1450                let Some(icon_theme_families) = proxy
1451                    .list_icon_theme_names(icon_theme_path.clone(), fs.clone())
1452                    .await
1453                    .log_err()
1454                else {
1455                    continue;
1456                };
1457
1458                let relative_path = relative_path.to_path_buf();
1459                if !extension_manifest.icon_themes.contains(&relative_path) {
1460                    extension_manifest.icon_themes.push(relative_path.clone());
1461                }
1462
1463                for icon_theme_name in icon_theme_families {
1464                    index.icon_themes.insert(
1465                        icon_theme_name.into(),
1466                        ExtensionIndexIconThemeEntry {
1467                            extension: extension_id.clone(),
1468                            path: relative_path.clone(),
1469                        },
1470                    );
1471                }
1472            }
1473        }
1474
1475        let extension_wasm_path = extension_dir.join("extension.wasm");
1476        if fs.is_file(&extension_wasm_path).await {
1477            extension_manifest
1478                .lib
1479                .kind
1480                .get_or_insert(ExtensionLibraryKind::Rust);
1481        }
1482
1483        index.extensions.insert(
1484            extension_id.clone(),
1485            ExtensionIndexEntry {
1486                dev: is_dev,
1487                manifest: Arc::new(extension_manifest),
1488            },
1489        );
1490
1491        Ok(())
1492    }
1493
1494    fn prepare_remote_extension(
1495        &mut self,
1496        extension_id: Arc<str>,
1497        is_dev: bool,
1498        tmp_dir: PathBuf,
1499        cx: &mut Context<Self>,
1500    ) -> Task<Result<()>> {
1501        let src_dir = self.extensions_dir().join(extension_id.as_ref());
1502        let Some(loaded_extension) = self.extension_index.extensions.get(&extension_id).cloned()
1503        else {
1504            return Task::ready(Err(anyhow!("extension no longer installed")));
1505        };
1506        let fs = self.fs.clone();
1507        cx.background_spawn(async move {
1508            const EXTENSION_TOML: &str = "extension.toml";
1509            const EXTENSION_WASM: &str = "extension.wasm";
1510            const CONFIG_TOML: &str = "config.toml";
1511
1512            if is_dev {
1513                let manifest_toml = toml::to_string(&loaded_extension.manifest)?;
1514                fs.save(
1515                    &tmp_dir.join(EXTENSION_TOML),
1516                    &Rope::from(manifest_toml),
1517                    language::LineEnding::Unix,
1518                )
1519                .await?;
1520            } else {
1521                fs.copy_file(
1522                    &src_dir.join(EXTENSION_TOML),
1523                    &tmp_dir.join(EXTENSION_TOML),
1524                    fs::CopyOptions::default(),
1525                )
1526                .await?
1527            }
1528
1529            if fs.is_file(&src_dir.join(EXTENSION_WASM)).await {
1530                fs.copy_file(
1531                    &src_dir.join(EXTENSION_WASM),
1532                    &tmp_dir.join(EXTENSION_WASM),
1533                    fs::CopyOptions::default(),
1534                )
1535                .await?
1536            }
1537
1538            for language_path in loaded_extension.manifest.languages.iter() {
1539                if fs
1540                    .is_file(&src_dir.join(language_path).join(CONFIG_TOML))
1541                    .await
1542                {
1543                    fs.create_dir(&tmp_dir.join(language_path)).await?;
1544                    fs.copy_file(
1545                        &src_dir.join(language_path).join(CONFIG_TOML),
1546                        &tmp_dir.join(language_path).join(CONFIG_TOML),
1547                        fs::CopyOptions::default(),
1548                    )
1549                    .await?
1550                }
1551            }
1552
1553            Ok(())
1554        })
1555    }
1556
1557    async fn sync_extensions_over_ssh(
1558        this: &WeakEntity<Self>,
1559        client: WeakEntity<SshRemoteClient>,
1560        cx: &mut AsyncApp,
1561    ) -> Result<()> {
1562        let extensions = this.update(cx, |this, _cx| {
1563            this.extension_index
1564                .extensions
1565                .iter()
1566                .filter_map(|(id, entry)| {
1567                    if entry.manifest.language_servers.is_empty() {
1568                        return None;
1569                    }
1570                    Some(proto::Extension {
1571                        id: id.to_string(),
1572                        version: entry.manifest.version.to_string(),
1573                        dev: entry.dev,
1574                    })
1575                })
1576                .collect()
1577        })?;
1578
1579        let response = client
1580            .update(cx, |client, _cx| {
1581                client
1582                    .proto_client()
1583                    .request(proto::SyncExtensions { extensions })
1584            })?
1585            .await?;
1586
1587        for missing_extension in response.missing_extensions.into_iter() {
1588            let tmp_dir = tempfile::tempdir()?;
1589            this.update(cx, |this, cx| {
1590                this.prepare_remote_extension(
1591                    missing_extension.id.clone().into(),
1592                    missing_extension.dev,
1593                    tmp_dir.path().to_owned(),
1594                    cx,
1595                )
1596            })?
1597            .await?;
1598            let dest_dir = PathBuf::from(&response.tmp_dir).join(missing_extension.clone().id);
1599            log::info!("Uploading extension {}", missing_extension.clone().id);
1600
1601            client
1602                .update(cx, |client, cx| {
1603                    client.upload_directory(tmp_dir.path().to_owned(), dest_dir.clone(), cx)
1604                })?
1605                .await?;
1606
1607            log::info!(
1608                "Finished uploading extension {}",
1609                missing_extension.clone().id
1610            );
1611
1612            client
1613                .update(cx, |client, _cx| {
1614                    client.proto_client().request(proto::InstallExtension {
1615                        tmp_dir: dest_dir.to_string_lossy().to_string(),
1616                        extension: Some(missing_extension),
1617                    })
1618                })?
1619                .await?;
1620        }
1621
1622        anyhow::Ok(())
1623    }
1624
1625    pub async fn update_ssh_clients(this: &WeakEntity<Self>, cx: &mut AsyncApp) -> Result<()> {
1626        let clients = this.update(cx, |this, _cx| {
1627            this.ssh_clients.retain(|_k, v| v.upgrade().is_some());
1628            this.ssh_clients.values().cloned().collect::<Vec<_>>()
1629        })?;
1630
1631        for client in clients {
1632            Self::sync_extensions_over_ssh(&this, client, cx)
1633                .await
1634                .log_err();
1635        }
1636
1637        anyhow::Ok(())
1638    }
1639
1640    pub fn register_ssh_client(&mut self, client: Entity<SshRemoteClient>, cx: &mut Context<Self>) {
1641        let connection_options = client.read(cx).connection_options();
1642        if self.ssh_clients.contains_key(&connection_options.ssh_url()) {
1643            return;
1644        }
1645
1646        self.ssh_clients
1647            .insert(connection_options.ssh_url(), client.downgrade());
1648        self.ssh_registered_tx.unbounded_send(()).ok();
1649    }
1650}
1651
1652fn load_plugin_queries(root_path: &Path) -> LanguageQueries {
1653    let mut result = LanguageQueries::default();
1654    if let Some(entries) = std::fs::read_dir(root_path).log_err() {
1655        for entry in entries {
1656            let Some(entry) = entry.log_err() else {
1657                continue;
1658            };
1659            let path = entry.path();
1660            if let Some(remainder) = path.strip_prefix(root_path).ok().and_then(|p| p.to_str()) {
1661                if !remainder.ends_with(".scm") {
1662                    continue;
1663                }
1664                for (name, query) in QUERY_FILENAME_PREFIXES {
1665                    if remainder.starts_with(name) {
1666                        if let Some(contents) = std::fs::read_to_string(&path).log_err() {
1667                            match query(&mut result) {
1668                                None => *query(&mut result) = Some(contents.into()),
1669                                Some(r) => r.to_mut().push_str(contents.as_ref()),
1670                            }
1671                        }
1672                        break;
1673                    }
1674                }
1675            }
1676        }
1677    }
1678    result
1679}