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