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