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(|this, mut cx| async move {
 309            if let Some(future) = reload_future {
 310                future.await;
 311            }
 312            this.update(&mut cx, |this, cx| this.auto_install_extensions(cx))
 313                .ok();
 314            this.update(&mut cx, |this, cx| this.check_for_updates(cx))
 315                .ok();
 316        })
 317        .detach();
 318
 319        // Perform all extension loading in a single task to ensure that we
 320        // never attempt to simultaneously load/unload extensions from multiple
 321        // parallel tasks.
 322        this.tasks.push(cx.spawn(|this, mut cx| {
 323            async move {
 324                load_initial_extensions.await;
 325
 326                let mut index_changed = false;
 327                let mut debounce_timer = cx.background_spawn(futures::future::pending()).fuse();
 328                loop {
 329                    select_biased! {
 330                        _ = debounce_timer => {
 331                            if index_changed {
 332                                let index = this
 333                                    .update(&mut cx, |this, cx| this.rebuild_extension_index(cx))?
 334                                    .await;
 335                                this.update(&mut cx, |this, cx| this.extensions_updated(index, cx))?
 336                                    .await;
 337                                index_changed = false;
 338                            }
 339
 340                            Self::update_ssh_clients(&this, &mut cx).await?;
 341                        }
 342                        _ = connection_registered_rx.next() => {
 343                            debounce_timer = cx
 344                                .background_executor()
 345                                .timer(RELOAD_DEBOUNCE_DURATION)
 346                                .fuse();
 347                        }
 348                        extension_id = reload_rx.next() => {
 349                            let Some(extension_id) = extension_id else { break; };
 350                            this.update(&mut cx, |this, _| {
 351                                this.modified_extensions.extend(extension_id);
 352                            })?;
 353                            index_changed = true;
 354                            debounce_timer = cx
 355                                .background_executor()
 356                                .timer(RELOAD_DEBOUNCE_DURATION)
 357                                .fuse();
 358                        }
 359                    }
 360                }
 361
 362                anyhow::Ok(())
 363            }
 364            .map(drop)
 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(move |this, mut cx| async move {
 546            let extensions = task.await?;
 547            this.update(&mut 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(move |this, mut cx| async move {
 593            for extension_id in extensions_to_install {
 594                this.update(&mut 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(move |this, mut cx| async move {
 606            Self::upgrade_extensions(this, task.await?, &mut cx).await
 607        })
 608        .detach();
 609    }
 610
 611    async fn upgrade_extensions(
 612        this: WeakEntity<Self>,
 613        extensions: Vec<ExtensionMetadata>,
 614        cx: &mut AsyncApp,
 615    ) -> Result<()> {
 616        for extension in extensions {
 617            let task = this.update(cx, |this, cx| {
 618                if let Some(installed_extension) =
 619                    this.extension_index.extensions.get(&extension.id)
 620                {
 621                    let installed_version =
 622                        SemanticVersion::from_str(&installed_extension.manifest.version).ok()?;
 623                    let latest_version =
 624                        SemanticVersion::from_str(&extension.manifest.version).ok()?;
 625
 626                    if installed_version >= latest_version {
 627                        return None;
 628                    }
 629                }
 630
 631                Some(this.upgrade_extension(extension.id, extension.manifest.version, cx))
 632            })?;
 633
 634            if let Some(task) = task {
 635                task.await.log_err();
 636            }
 637        }
 638        anyhow::Ok(())
 639    }
 640
 641    fn fetch_extensions_from_api(
 642        &self,
 643        path: &str,
 644        query: &[(&str, &str)],
 645        cx: &mut Context<'_, ExtensionStore>,
 646    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 647        let url = self.http_client.build_zed_api_url(path, query);
 648        let http_client = self.http_client.clone();
 649        cx.spawn(move |_, _| async move {
 650            let mut response = http_client
 651                .get(url?.as_ref(), AsyncBody::empty(), true)
 652                .await?;
 653
 654            let mut body = Vec::new();
 655            response
 656                .body_mut()
 657                .read_to_end(&mut body)
 658                .await
 659                .context("error reading extensions")?;
 660
 661            if response.status().is_client_error() {
 662                let text = String::from_utf8_lossy(body.as_slice());
 663                bail!(
 664                    "status error {}, response: {text:?}",
 665                    response.status().as_u16()
 666                );
 667            }
 668
 669            let response: GetExtensionsResponse = serde_json::from_slice(&body)?;
 670            Ok(response.data)
 671        })
 672    }
 673
 674    pub fn install_extension(
 675        &mut self,
 676        extension_id: Arc<str>,
 677        version: Arc<str>,
 678        cx: &mut Context<Self>,
 679    ) {
 680        self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Install, cx)
 681            .detach_and_log_err(cx);
 682    }
 683
 684    fn install_or_upgrade_extension_at_endpoint(
 685        &mut self,
 686        extension_id: Arc<str>,
 687        url: Url,
 688        operation: ExtensionOperation,
 689        cx: &mut Context<Self>,
 690    ) -> Task<Result<()>> {
 691        let extension_dir = self.installed_dir.join(extension_id.as_ref());
 692        let http_client = self.http_client.clone();
 693        let fs = self.fs.clone();
 694
 695        match self.outstanding_operations.entry(extension_id.clone()) {
 696            btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
 697            btree_map::Entry::Vacant(e) => e.insert(operation),
 698        };
 699        cx.notify();
 700
 701        cx.spawn(move |this, mut cx| async move {
 702            let _finish = util::defer({
 703                let this = this.clone();
 704                let mut cx = cx.clone();
 705                let extension_id = extension_id.clone();
 706                move || {
 707                    this.update(&mut cx, |this, cx| {
 708                        this.outstanding_operations.remove(extension_id.as_ref());
 709                        cx.notify();
 710                    })
 711                    .ok();
 712                }
 713            });
 714
 715            let mut response = http_client
 716                .get(url.as_ref(), Default::default(), true)
 717                .await
 718                .map_err(|err| anyhow!("error downloading extension: {}", err))?;
 719
 720            fs.remove_dir(
 721                &extension_dir,
 722                RemoveOptions {
 723                    recursive: true,
 724                    ignore_if_not_exists: true,
 725                },
 726            )
 727            .await?;
 728
 729            let content_length = response
 730                .headers()
 731                .get(http_client::http::header::CONTENT_LENGTH)
 732                .and_then(|value| value.to_str().ok()?.parse::<usize>().ok());
 733
 734            let mut body = BufReader::new(response.body_mut());
 735            let mut tar_gz_bytes = Vec::new();
 736            body.read_to_end(&mut tar_gz_bytes).await?;
 737
 738            if let Some(content_length) = content_length {
 739                let actual_len = tar_gz_bytes.len();
 740                if content_length != actual_len {
 741                    bail!("downloaded extension size {actual_len} does not match content length {content_length}");
 742                }
 743            }
 744            let decompressed_bytes = GzipDecoder::new(BufReader::new(tar_gz_bytes.as_slice()));
 745            let archive = Archive::new(decompressed_bytes);
 746            archive.unpack(extension_dir).await?;
 747            this.update(&mut cx, |this, cx| {
 748                this.reload(Some(extension_id.clone()), cx)
 749            })?
 750            .await;
 751
 752            if let ExtensionOperation::Install = operation {
 753                this.update(&mut cx, |_, cx| {
 754                    cx.emit(Event::ExtensionInstalled(extension_id));
 755                })
 756                .ok();
 757            }
 758
 759            anyhow::Ok(())
 760        })
 761    }
 762
 763    pub fn install_latest_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
 764        log::info!("installing extension {extension_id} latest version");
 765
 766        let schema_versions = schema_version_range();
 767        let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
 768
 769        let Some(url) = self
 770            .http_client
 771            .build_zed_api_url(
 772                &format!("/extensions/{extension_id}/download"),
 773                &[
 774                    ("min_schema_version", &schema_versions.start().to_string()),
 775                    ("max_schema_version", &schema_versions.end().to_string()),
 776                    (
 777                        "min_wasm_api_version",
 778                        &wasm_api_versions.start().to_string(),
 779                    ),
 780                    ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
 781                ],
 782            )
 783            .log_err()
 784        else {
 785            return;
 786        };
 787
 788        self.install_or_upgrade_extension_at_endpoint(
 789            extension_id,
 790            url,
 791            ExtensionOperation::Install,
 792            cx,
 793        )
 794        .detach_and_log_err(cx);
 795    }
 796
 797    pub fn upgrade_extension(
 798        &mut self,
 799        extension_id: Arc<str>,
 800        version: Arc<str>,
 801        cx: &mut Context<Self>,
 802    ) -> Task<Result<()>> {
 803        self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Upgrade, cx)
 804    }
 805
 806    fn install_or_upgrade_extension(
 807        &mut self,
 808        extension_id: Arc<str>,
 809        version: Arc<str>,
 810        operation: ExtensionOperation,
 811        cx: &mut Context<Self>,
 812    ) -> Task<Result<()>> {
 813        log::info!("installing extension {extension_id} {version}");
 814        let Some(url) = self
 815            .http_client
 816            .build_zed_api_url(
 817                &format!("/extensions/{extension_id}/{version}/download"),
 818                &[],
 819            )
 820            .log_err()
 821        else {
 822            return Task::ready(Ok(()));
 823        };
 824
 825        self.install_or_upgrade_extension_at_endpoint(extension_id, url, operation, cx)
 826    }
 827
 828    pub fn uninstall_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
 829        let extension_dir = self.installed_dir.join(extension_id.as_ref());
 830        let work_dir = self.wasm_host.work_dir.join(extension_id.as_ref());
 831        let fs = self.fs.clone();
 832
 833        match self.outstanding_operations.entry(extension_id.clone()) {
 834            btree_map::Entry::Occupied(_) => return,
 835            btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
 836        };
 837
 838        cx.spawn(move |this, mut cx| async move {
 839            let _finish = util::defer({
 840                let this = this.clone();
 841                let mut cx = cx.clone();
 842                let extension_id = extension_id.clone();
 843                move || {
 844                    this.update(&mut cx, |this, cx| {
 845                        this.outstanding_operations.remove(extension_id.as_ref());
 846                        cx.notify();
 847                    })
 848                    .ok();
 849                }
 850            });
 851
 852            fs.remove_dir(
 853                &work_dir,
 854                RemoveOptions {
 855                    recursive: true,
 856                    ignore_if_not_exists: true,
 857                },
 858            )
 859            .await?;
 860
 861            fs.remove_dir(
 862                &extension_dir,
 863                RemoveOptions {
 864                    recursive: true,
 865                    ignore_if_not_exists: true,
 866                },
 867            )
 868            .await?;
 869
 870            this.update(&mut cx, |this, cx| this.reload(None, cx))?
 871                .await;
 872            anyhow::Ok(())
 873        })
 874        .detach_and_log_err(cx)
 875    }
 876
 877    pub fn install_dev_extension(
 878        &mut self,
 879        extension_source_path: PathBuf,
 880        cx: &mut Context<Self>,
 881    ) -> Task<Result<()>> {
 882        let extensions_dir = self.extensions_dir();
 883        let fs = self.fs.clone();
 884        let builder = self.builder.clone();
 885
 886        cx.spawn(move |this, mut cx| async move {
 887            let mut extension_manifest =
 888                ExtensionManifest::load(fs.clone(), &extension_source_path).await?;
 889            let extension_id = extension_manifest.id.clone();
 890
 891            if !this.update(&mut cx, |this, cx| {
 892                match this.outstanding_operations.entry(extension_id.clone()) {
 893                    btree_map::Entry::Occupied(_) => return false,
 894                    btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
 895                };
 896                cx.notify();
 897                true
 898            })? {
 899                return Ok(());
 900            }
 901
 902            let _finish = util::defer({
 903                let this = this.clone();
 904                let mut cx = cx.clone();
 905                let extension_id = extension_id.clone();
 906                move || {
 907                    this.update(&mut cx, |this, cx| {
 908                        this.outstanding_operations.remove(extension_id.as_ref());
 909                        cx.notify();
 910                    })
 911                    .ok();
 912                }
 913            });
 914
 915            cx.background_spawn({
 916                let extension_source_path = extension_source_path.clone();
 917                async move {
 918                    builder
 919                        .compile_extension(
 920                            &extension_source_path,
 921                            &mut extension_manifest,
 922                            CompileExtensionOptions { release: false },
 923                        )
 924                        .await
 925                }
 926            })
 927            .await?;
 928
 929            let output_path = &extensions_dir.join(extension_id.as_ref());
 930            if let Some(metadata) = fs.metadata(output_path).await? {
 931                if metadata.is_symlink {
 932                    fs.remove_file(
 933                        output_path,
 934                        RemoveOptions {
 935                            recursive: false,
 936                            ignore_if_not_exists: true,
 937                        },
 938                    )
 939                    .await?;
 940                } else {
 941                    bail!("extension {extension_id} is already installed");
 942                }
 943            }
 944
 945            fs.create_symlink(output_path, extension_source_path)
 946                .await?;
 947
 948            this.update(&mut cx, |this, cx| this.reload(None, cx))?
 949                .await;
 950            Ok(())
 951        })
 952    }
 953
 954    pub fn rebuild_dev_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
 955        let path = self.installed_dir.join(extension_id.as_ref());
 956        let builder = self.builder.clone();
 957        let fs = self.fs.clone();
 958
 959        match self.outstanding_operations.entry(extension_id.clone()) {
 960            btree_map::Entry::Occupied(_) => return,
 961            btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Upgrade),
 962        };
 963
 964        cx.notify();
 965        let compile = cx.background_spawn(async move {
 966            let mut manifest = ExtensionManifest::load(fs, &path).await?;
 967            builder
 968                .compile_extension(
 969                    &path,
 970                    &mut manifest,
 971                    CompileExtensionOptions { release: true },
 972                )
 973                .await
 974        });
 975
 976        cx.spawn(|this, mut cx| async move {
 977            let result = compile.await;
 978
 979            this.update(&mut cx, |this, cx| {
 980                this.outstanding_operations.remove(&extension_id);
 981                cx.notify();
 982            })?;
 983
 984            if result.is_ok() {
 985                this.update(&mut cx, |this, cx| this.reload(Some(extension_id), cx))?
 986                    .await;
 987            }
 988
 989            result
 990        })
 991        .detach_and_log_err(cx)
 992    }
 993
 994    /// Updates the set of installed extensions.
 995    ///
 996    /// First, this unloads any themes, languages, or grammars that are
 997    /// no longer in the manifest, or whose files have changed on disk.
 998    /// Then it loads any themes, languages, or grammars that are newly
 999    /// added to the manifest, or whose files have changed on disk.
1000    fn extensions_updated(
1001        &mut self,
1002        new_index: ExtensionIndex,
1003        cx: &mut Context<Self>,
1004    ) -> Task<()> {
1005        let old_index = &self.extension_index;
1006
1007        // Determine which extensions need to be loaded and unloaded, based
1008        // on the changes to the manifest and the extensions that we know have been
1009        // modified.
1010        let mut extensions_to_unload = Vec::default();
1011        let mut extensions_to_load = Vec::default();
1012        {
1013            let mut old_keys = old_index.extensions.iter().peekable();
1014            let mut new_keys = new_index.extensions.iter().peekable();
1015            loop {
1016                match (old_keys.peek(), new_keys.peek()) {
1017                    (None, None) => break,
1018                    (None, Some(_)) => {
1019                        extensions_to_load.push(new_keys.next().unwrap().0.clone());
1020                    }
1021                    (Some(_), None) => {
1022                        extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1023                    }
1024                    (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(new_key) {
1025                        Ordering::Equal => {
1026                            let (old_key, old_value) = old_keys.next().unwrap();
1027                            let (new_key, new_value) = new_keys.next().unwrap();
1028                            if old_value != new_value || self.modified_extensions.contains(old_key)
1029                            {
1030                                extensions_to_unload.push(old_key.clone());
1031                                extensions_to_load.push(new_key.clone());
1032                            }
1033                        }
1034                        Ordering::Less => {
1035                            extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1036                        }
1037                        Ordering::Greater => {
1038                            extensions_to_load.push(new_keys.next().unwrap().0.clone());
1039                        }
1040                    },
1041                }
1042            }
1043            self.modified_extensions.clear();
1044        }
1045
1046        if extensions_to_load.is_empty() && extensions_to_unload.is_empty() {
1047            return Task::ready(());
1048        }
1049
1050        let reload_count = extensions_to_unload
1051            .iter()
1052            .filter(|id| extensions_to_load.contains(id))
1053            .count();
1054
1055        log::info!(
1056            "extensions updated. loading {}, reloading {}, unloading {}",
1057            extensions_to_load.len() - reload_count,
1058            reload_count,
1059            extensions_to_unload.len() - reload_count
1060        );
1061
1062        for extension_id in &extensions_to_load {
1063            if let Some(extension) = new_index.extensions.get(extension_id) {
1064                telemetry::event!(
1065                    "Extension Loaded",
1066                    extension_id,
1067                    version = extension.manifest.version
1068                );
1069            }
1070        }
1071
1072        let themes_to_remove = old_index
1073            .themes
1074            .iter()
1075            .filter_map(|(name, entry)| {
1076                if extensions_to_unload.contains(&entry.extension) {
1077                    Some(name.clone().into())
1078                } else {
1079                    None
1080                }
1081            })
1082            .collect::<Vec<_>>();
1083        let icon_themes_to_remove = old_index
1084            .icon_themes
1085            .iter()
1086            .filter_map(|(name, entry)| {
1087                if extensions_to_unload.contains(&entry.extension) {
1088                    Some(name.clone().into())
1089                } else {
1090                    None
1091                }
1092            })
1093            .collect::<Vec<_>>();
1094        let languages_to_remove = old_index
1095            .languages
1096            .iter()
1097            .filter_map(|(name, entry)| {
1098                if extensions_to_unload.contains(&entry.extension) {
1099                    Some(name.clone())
1100                } else {
1101                    None
1102                }
1103            })
1104            .collect::<Vec<_>>();
1105        let mut grammars_to_remove = Vec::new();
1106        for extension_id in &extensions_to_unload {
1107            let Some(extension) = old_index.extensions.get(extension_id) else {
1108                continue;
1109            };
1110            grammars_to_remove.extend(extension.manifest.grammars.keys().cloned());
1111            for (language_server_name, config) in extension.manifest.language_servers.iter() {
1112                for language in config.languages() {
1113                    self.proxy
1114                        .remove_language_server(&language, language_server_name);
1115                }
1116            }
1117        }
1118
1119        self.wasm_extensions
1120            .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
1121        self.proxy.remove_user_themes(themes_to_remove);
1122        self.proxy.remove_icon_themes(icon_themes_to_remove);
1123        self.proxy
1124            .remove_languages(&languages_to_remove, &grammars_to_remove);
1125
1126        let languages_to_add = new_index
1127            .languages
1128            .iter()
1129            .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
1130            .collect::<Vec<_>>();
1131        let mut grammars_to_add = Vec::new();
1132        let mut themes_to_add = Vec::new();
1133        let mut icon_themes_to_add = Vec::new();
1134        let mut snippets_to_add = Vec::new();
1135        for extension_id in &extensions_to_load {
1136            let Some(extension) = new_index.extensions.get(extension_id) else {
1137                continue;
1138            };
1139
1140            grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
1141                let mut grammar_path = self.installed_dir.clone();
1142                grammar_path.extend([extension_id.as_ref(), "grammars"]);
1143                grammar_path.push(grammar_name.as_ref());
1144                grammar_path.set_extension("wasm");
1145                (grammar_name.clone(), grammar_path)
1146            }));
1147            themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
1148                let mut path = self.installed_dir.clone();
1149                path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1150                path
1151            }));
1152            icon_themes_to_add.extend(extension.manifest.icon_themes.iter().map(
1153                |icon_theme_path| {
1154                    let mut path = self.installed_dir.clone();
1155                    path.extend([Path::new(extension_id.as_ref()), icon_theme_path.as_path()]);
1156
1157                    let mut icons_root_path = self.installed_dir.clone();
1158                    icons_root_path.extend([Path::new(extension_id.as_ref())]);
1159
1160                    (path, icons_root_path)
1161                },
1162            ));
1163            snippets_to_add.extend(extension.manifest.snippets.iter().map(|snippets_path| {
1164                let mut path = self.installed_dir.clone();
1165                path.extend([Path::new(extension_id.as_ref()), snippets_path.as_path()]);
1166                path
1167            }));
1168        }
1169
1170        self.proxy.register_grammars(grammars_to_add);
1171
1172        for (language_name, language) in languages_to_add {
1173            let mut language_path = self.installed_dir.clone();
1174            language_path.extend([
1175                Path::new(language.extension.as_ref()),
1176                language.path.as_path(),
1177            ]);
1178            self.proxy.register_language(
1179                language_name.clone(),
1180                language.grammar.clone(),
1181                language.matcher.clone(),
1182                language.hidden,
1183                Arc::new(move || {
1184                    let config = std::fs::read_to_string(language_path.join("config.toml"))?;
1185                    let config: LanguageConfig = ::toml::from_str(&config)?;
1186                    let queries = load_plugin_queries(&language_path);
1187                    let context_provider =
1188                        std::fs::read_to_string(language_path.join("tasks.json"))
1189                            .ok()
1190                            .and_then(|contents| {
1191                                let definitions =
1192                                    serde_json_lenient::from_str(&contents).log_err()?;
1193                                Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1194                            });
1195
1196                    Ok(LoadedLanguage {
1197                        config,
1198                        queries,
1199                        context_provider,
1200                        toolchain_provider: None,
1201                    })
1202                }),
1203            );
1204        }
1205
1206        let fs = self.fs.clone();
1207        let wasm_host = self.wasm_host.clone();
1208        let root_dir = self.installed_dir.clone();
1209        let proxy = self.proxy.clone();
1210        let extension_entries = extensions_to_load
1211            .iter()
1212            .filter_map(|name| new_index.extensions.get(name).cloned())
1213            .collect::<Vec<_>>();
1214
1215        self.extension_index = new_index;
1216        cx.notify();
1217        cx.emit(Event::ExtensionsUpdated);
1218
1219        cx.spawn(|this, mut cx| async move {
1220            cx.background_spawn({
1221                let fs = fs.clone();
1222                async move {
1223                    for theme_path in themes_to_add.into_iter() {
1224                        proxy
1225                            .load_user_theme(theme_path, fs.clone())
1226                            .await
1227                            .log_err();
1228                    }
1229
1230                    for (icon_theme_path, icons_root_path) in icon_themes_to_add.into_iter() {
1231                        proxy
1232                            .load_icon_theme(icon_theme_path, icons_root_path, fs.clone())
1233                            .await
1234                            .log_err();
1235                    }
1236
1237                    for snippets_path in &snippets_to_add {
1238                        if let Some(snippets_contents) = fs.load(snippets_path).await.log_err() {
1239                            proxy
1240                                .register_snippet(snippets_path, &snippets_contents)
1241                                .log_err();
1242                        }
1243                    }
1244                }
1245            })
1246            .await;
1247
1248            let mut wasm_extensions = Vec::new();
1249            for extension in extension_entries {
1250                if extension.manifest.lib.kind.is_none() {
1251                    continue;
1252                };
1253
1254                let extension_path = root_dir.join(extension.manifest.id.as_ref());
1255                let wasm_extension = WasmExtension::load(
1256                    extension_path,
1257                    &extension.manifest,
1258                    wasm_host.clone(),
1259                    &cx,
1260                )
1261                .await;
1262
1263                if let Some(wasm_extension) = wasm_extension.log_err() {
1264                    wasm_extensions.push((extension.manifest.clone(), wasm_extension));
1265                } else {
1266                    this.update(&mut cx, |_, cx| {
1267                        cx.emit(Event::ExtensionFailedToLoad(extension.manifest.id.clone()))
1268                    })
1269                    .ok();
1270                }
1271            }
1272
1273            this.update(&mut cx, |this, cx| {
1274                this.reload_complete_senders.clear();
1275
1276                for (manifest, wasm_extension) in &wasm_extensions {
1277                    let extension = Arc::new(wasm_extension.clone());
1278
1279                    for (language_server_id, language_server_config) in &manifest.language_servers {
1280                        for language in language_server_config.languages() {
1281                            this.proxy.register_language_server(
1282                                extension.clone(),
1283                                language_server_id.clone(),
1284                                language.clone(),
1285                            );
1286                        }
1287                    }
1288
1289                    for (slash_command_name, slash_command) in &manifest.slash_commands {
1290                        this.proxy.register_slash_command(
1291                            extension.clone(),
1292                            extension::SlashCommand {
1293                                name: slash_command_name.to_string(),
1294                                description: slash_command.description.to_string(),
1295                                // We don't currently expose this as a configurable option, as it currently drives
1296                                // the `menu_text` on the `SlashCommand` trait, which is not used for slash commands
1297                                // defined in extensions, as they are not able to be added to the menu.
1298                                tooltip_text: String::new(),
1299                                requires_argument: slash_command.requires_argument,
1300                            },
1301                        );
1302                    }
1303
1304                    for (id, _context_server_entry) in &manifest.context_servers {
1305                        this.proxy
1306                            .register_context_server(extension.clone(), id.clone(), cx);
1307                    }
1308
1309                    for (provider_id, _provider) in &manifest.indexed_docs_providers {
1310                        this.proxy
1311                            .register_indexed_docs_provider(extension.clone(), provider_id.clone());
1312                    }
1313                }
1314
1315                this.wasm_extensions.extend(wasm_extensions);
1316                this.proxy.set_extensions_loaded();
1317                this.proxy.reload_current_theme(cx);
1318                this.proxy.reload_current_icon_theme(cx);
1319
1320                if let Some(events) = ExtensionEvents::try_global(cx) {
1321                    events.update(cx, |this, cx| {
1322                        this.emit(extension::Event::ExtensionsInstalledChanged, cx)
1323                    });
1324                }
1325            })
1326            .ok();
1327        })
1328    }
1329
1330    fn rebuild_extension_index(&self, cx: &mut Context<Self>) -> Task<ExtensionIndex> {
1331        let fs = self.fs.clone();
1332        let work_dir = self.wasm_host.work_dir.clone();
1333        let extensions_dir = self.installed_dir.clone();
1334        let index_path = self.index_path.clone();
1335        let proxy = self.proxy.clone();
1336        cx.background_spawn(async move {
1337            let start_time = Instant::now();
1338            let mut index = ExtensionIndex::default();
1339
1340            fs.create_dir(&work_dir).await.log_err();
1341            fs.create_dir(&extensions_dir).await.log_err();
1342
1343            let extension_paths = fs.read_dir(&extensions_dir).await;
1344            if let Ok(mut extension_paths) = extension_paths {
1345                while let Some(extension_dir) = extension_paths.next().await {
1346                    let Ok(extension_dir) = extension_dir else {
1347                        continue;
1348                    };
1349
1350                    if extension_dir
1351                        .file_name()
1352                        .map_or(false, |file_name| file_name == ".DS_Store")
1353                    {
1354                        continue;
1355                    }
1356
1357                    Self::add_extension_to_index(
1358                        fs.clone(),
1359                        extension_dir,
1360                        &mut index,
1361                        proxy.clone(),
1362                    )
1363                    .await
1364                    .log_err();
1365                }
1366            }
1367
1368            if let Ok(index_json) = serde_json::to_string_pretty(&index) {
1369                fs.save(&index_path, &index_json.as_str().into(), Default::default())
1370                    .await
1371                    .context("failed to save extension index")
1372                    .log_err();
1373            }
1374
1375            log::info!("rebuilt extension index in {:?}", start_time.elapsed());
1376            index
1377        })
1378    }
1379
1380    async fn add_extension_to_index(
1381        fs: Arc<dyn Fs>,
1382        extension_dir: PathBuf,
1383        index: &mut ExtensionIndex,
1384        proxy: Arc<ExtensionHostProxy>,
1385    ) -> Result<()> {
1386        let mut extension_manifest = ExtensionManifest::load(fs.clone(), &extension_dir).await?;
1387        let extension_id = extension_manifest.id.clone();
1388
1389        // TODO: distinguish dev extensions more explicitly, by the absence
1390        // of a checksum file that we'll create when downloading normal extensions.
1391        let is_dev = fs
1392            .metadata(&extension_dir)
1393            .await?
1394            .ok_or_else(|| anyhow!("directory does not exist"))?
1395            .is_symlink;
1396
1397        if let Ok(mut language_paths) = fs.read_dir(&extension_dir.join("languages")).await {
1398            while let Some(language_path) = language_paths.next().await {
1399                let language_path = language_path?;
1400                let Ok(relative_path) = language_path.strip_prefix(&extension_dir) else {
1401                    continue;
1402                };
1403                let Ok(Some(fs_metadata)) = fs.metadata(&language_path).await else {
1404                    continue;
1405                };
1406                if !fs_metadata.is_dir {
1407                    continue;
1408                }
1409                let config = fs.load(&language_path.join("config.toml")).await?;
1410                let config = ::toml::from_str::<LanguageConfig>(&config)?;
1411
1412                let relative_path = relative_path.to_path_buf();
1413                if !extension_manifest.languages.contains(&relative_path) {
1414                    extension_manifest.languages.push(relative_path.clone());
1415                }
1416
1417                index.languages.insert(
1418                    config.name.clone(),
1419                    ExtensionIndexLanguageEntry {
1420                        extension: extension_id.clone(),
1421                        path: relative_path,
1422                        matcher: config.matcher,
1423                        hidden: config.hidden,
1424                        grammar: config.grammar,
1425                    },
1426                );
1427            }
1428        }
1429
1430        if let Ok(mut theme_paths) = fs.read_dir(&extension_dir.join("themes")).await {
1431            while let Some(theme_path) = theme_paths.next().await {
1432                let theme_path = theme_path?;
1433                let Ok(relative_path) = theme_path.strip_prefix(&extension_dir) else {
1434                    continue;
1435                };
1436
1437                let Some(theme_families) = proxy
1438                    .list_theme_names(theme_path.clone(), fs.clone())
1439                    .await
1440                    .log_err()
1441                else {
1442                    continue;
1443                };
1444
1445                let relative_path = relative_path.to_path_buf();
1446                if !extension_manifest.themes.contains(&relative_path) {
1447                    extension_manifest.themes.push(relative_path.clone());
1448                }
1449
1450                for theme_name in theme_families {
1451                    index.themes.insert(
1452                        theme_name.into(),
1453                        ExtensionIndexThemeEntry {
1454                            extension: extension_id.clone(),
1455                            path: relative_path.clone(),
1456                        },
1457                    );
1458                }
1459            }
1460        }
1461
1462        if let Ok(mut icon_theme_paths) = fs.read_dir(&extension_dir.join("icon_themes")).await {
1463            while let Some(icon_theme_path) = icon_theme_paths.next().await {
1464                let icon_theme_path = icon_theme_path?;
1465                let Ok(relative_path) = icon_theme_path.strip_prefix(&extension_dir) else {
1466                    continue;
1467                };
1468
1469                let Some(icon_theme_families) = proxy
1470                    .list_icon_theme_names(icon_theme_path.clone(), fs.clone())
1471                    .await
1472                    .log_err()
1473                else {
1474                    continue;
1475                };
1476
1477                let relative_path = relative_path.to_path_buf();
1478                if !extension_manifest.icon_themes.contains(&relative_path) {
1479                    extension_manifest.icon_themes.push(relative_path.clone());
1480                }
1481
1482                for icon_theme_name in icon_theme_families {
1483                    index.icon_themes.insert(
1484                        icon_theme_name.into(),
1485                        ExtensionIndexIconThemeEntry {
1486                            extension: extension_id.clone(),
1487                            path: relative_path.clone(),
1488                        },
1489                    );
1490                }
1491            }
1492        }
1493
1494        let extension_wasm_path = extension_dir.join("extension.wasm");
1495        if fs.is_file(&extension_wasm_path).await {
1496            extension_manifest
1497                .lib
1498                .kind
1499                .get_or_insert(ExtensionLibraryKind::Rust);
1500        }
1501
1502        index.extensions.insert(
1503            extension_id.clone(),
1504            ExtensionIndexEntry {
1505                dev: is_dev,
1506                manifest: Arc::new(extension_manifest),
1507            },
1508        );
1509
1510        Ok(())
1511    }
1512
1513    fn prepare_remote_extension(
1514        &mut self,
1515        extension_id: Arc<str>,
1516        is_dev: bool,
1517        tmp_dir: PathBuf,
1518        cx: &mut Context<Self>,
1519    ) -> Task<Result<()>> {
1520        let src_dir = self.extensions_dir().join(extension_id.as_ref());
1521        let Some(loaded_extension) = self.extension_index.extensions.get(&extension_id).cloned()
1522        else {
1523            return Task::ready(Err(anyhow!("extension no longer installed")));
1524        };
1525        let fs = self.fs.clone();
1526        cx.background_spawn(async move {
1527            const EXTENSION_TOML: &str = "extension.toml";
1528            const EXTENSION_WASM: &str = "extension.wasm";
1529            const CONFIG_TOML: &str = "config.toml";
1530
1531            if is_dev {
1532                let manifest_toml = toml::to_string(&loaded_extension.manifest)?;
1533                fs.save(
1534                    &tmp_dir.join(EXTENSION_TOML),
1535                    &Rope::from(manifest_toml),
1536                    language::LineEnding::Unix,
1537                )
1538                .await?;
1539            } else {
1540                fs.copy_file(
1541                    &src_dir.join(EXTENSION_TOML),
1542                    &tmp_dir.join(EXTENSION_TOML),
1543                    fs::CopyOptions::default(),
1544                )
1545                .await?
1546            }
1547
1548            if fs.is_file(&src_dir.join(EXTENSION_WASM)).await {
1549                fs.copy_file(
1550                    &src_dir.join(EXTENSION_WASM),
1551                    &tmp_dir.join(EXTENSION_WASM),
1552                    fs::CopyOptions::default(),
1553                )
1554                .await?
1555            }
1556
1557            for language_path in loaded_extension.manifest.languages.iter() {
1558                if fs
1559                    .is_file(&src_dir.join(language_path).join(CONFIG_TOML))
1560                    .await
1561                {
1562                    fs.create_dir(&tmp_dir.join(language_path)).await?;
1563                    fs.copy_file(
1564                        &src_dir.join(language_path).join(CONFIG_TOML),
1565                        &tmp_dir.join(language_path).join(CONFIG_TOML),
1566                        fs::CopyOptions::default(),
1567                    )
1568                    .await?
1569                }
1570            }
1571
1572            Ok(())
1573        })
1574    }
1575
1576    async fn sync_extensions_over_ssh(
1577        this: &WeakEntity<Self>,
1578        client: WeakEntity<SshRemoteClient>,
1579        cx: &mut AsyncApp,
1580    ) -> Result<()> {
1581        let extensions = this.update(cx, |this, _cx| {
1582            this.extension_index
1583                .extensions
1584                .iter()
1585                .filter_map(|(id, entry)| {
1586                    if entry.manifest.language_servers.is_empty() {
1587                        return None;
1588                    }
1589                    Some(proto::Extension {
1590                        id: id.to_string(),
1591                        version: entry.manifest.version.to_string(),
1592                        dev: entry.dev,
1593                    })
1594                })
1595                .collect()
1596        })?;
1597
1598        let response = client
1599            .update(cx, |client, _cx| {
1600                client
1601                    .proto_client()
1602                    .request(proto::SyncExtensions { extensions })
1603            })?
1604            .await?;
1605
1606        for missing_extension in response.missing_extensions.into_iter() {
1607            let tmp_dir = tempfile::tempdir()?;
1608            this.update(cx, |this, cx| {
1609                this.prepare_remote_extension(
1610                    missing_extension.id.clone().into(),
1611                    missing_extension.dev,
1612                    tmp_dir.path().to_owned(),
1613                    cx,
1614                )
1615            })?
1616            .await?;
1617            let dest_dir = PathBuf::from(&response.tmp_dir).join(missing_extension.clone().id);
1618            log::info!("Uploading extension {}", missing_extension.clone().id);
1619
1620            client
1621                .update(cx, |client, cx| {
1622                    client.upload_directory(tmp_dir.path().to_owned(), dest_dir.clone(), cx)
1623                })?
1624                .await?;
1625
1626            log::info!(
1627                "Finished uploading extension {}",
1628                missing_extension.clone().id
1629            );
1630
1631            client
1632                .update(cx, |client, _cx| {
1633                    client.proto_client().request(proto::InstallExtension {
1634                        tmp_dir: dest_dir.to_string_lossy().to_string(),
1635                        extension: Some(missing_extension),
1636                    })
1637                })?
1638                .await?;
1639        }
1640
1641        anyhow::Ok(())
1642    }
1643
1644    pub async fn update_ssh_clients(this: &WeakEntity<Self>, cx: &mut AsyncApp) -> Result<()> {
1645        let clients = this.update(cx, |this, _cx| {
1646            this.ssh_clients.retain(|_k, v| v.upgrade().is_some());
1647            this.ssh_clients.values().cloned().collect::<Vec<_>>()
1648        })?;
1649
1650        for client in clients {
1651            Self::sync_extensions_over_ssh(&this, client, cx)
1652                .await
1653                .log_err();
1654        }
1655
1656        anyhow::Ok(())
1657    }
1658
1659    pub fn register_ssh_client(&mut self, client: Entity<SshRemoteClient>, cx: &mut Context<Self>) {
1660        let connection_options = client.read(cx).connection_options();
1661        if self.ssh_clients.contains_key(&connection_options.ssh_url()) {
1662            return;
1663        }
1664
1665        self.ssh_clients
1666            .insert(connection_options.ssh_url(), client.downgrade());
1667        self.ssh_registered_tx.unbounded_send(()).ok();
1668    }
1669}
1670
1671fn load_plugin_queries(root_path: &Path) -> LanguageQueries {
1672    let mut result = LanguageQueries::default();
1673    if let Some(entries) = std::fs::read_dir(root_path).log_err() {
1674        for entry in entries {
1675            let Some(entry) = entry.log_err() else {
1676                continue;
1677            };
1678            let path = entry.path();
1679            if let Some(remainder) = path.strip_prefix(root_path).ok().and_then(|p| p.to_str()) {
1680                if !remainder.ends_with(".scm") {
1681                    continue;
1682                }
1683                for (name, query) in QUERY_FILENAME_PREFIXES {
1684                    if remainder.starts_with(name) {
1685                        if let Some(contents) = std::fs::read_to_string(&path).log_err() {
1686                            match query(&mut result) {
1687                                None => *query(&mut result) = Some(contents.into()),
1688                                Some(r) => r.to_mut().push_str(contents.as_ref()),
1689                            }
1690                        }
1691                        break;
1692                    }
1693                }
1694            }
1695        }
1696    }
1697    result
1698}