extension_host.rs

   1pub mod extension_settings;
   2pub mod headless_host;
   3pub mod wasm_host;
   4
   5#[cfg(test)]
   6mod extension_store_test;
   7
   8use anyhow::{anyhow, bail, Context as _, Result};
   9use async_compression::futures::bufread::GzipDecoder;
  10use async_tar::Archive;
  11use client::ExtensionProvides;
  12use client::{proto, telemetry::Telemetry, Client, ExtensionMetadata, GetExtensionsResponse};
  13use collections::{btree_map, BTreeMap, BTreeSet, HashMap, HashSet};
  14use extension::extension_builder::{CompileExtensionOptions, ExtensionBuilder};
  15pub use extension::ExtensionManifest;
  16use extension::{
  17    ExtensionContextServerProxy, ExtensionEvents, ExtensionGrammarProxy, ExtensionHostProxy,
  18    ExtensionIndexedDocsProviderProxy, ExtensionLanguageProxy, ExtensionLanguageServerProxy,
  19    ExtensionSlashCommandProxy, ExtensionSnippetProxy, ExtensionThemeProxy,
  20};
  21use fs::{Fs, RemoveOptions};
  22use futures::{
  23    channel::{
  24        mpsc::{unbounded, UnboundedSender},
  25        oneshot,
  26    },
  27    io::BufReader,
  28    select_biased, AsyncReadExt as _, Future, FutureExt as _, StreamExt as _,
  29};
  30use gpui::{
  31    actions, App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Global, Task,
  32    WeakEntity,
  33};
  34use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
  35use language::{
  36    LanguageConfig, LanguageMatcher, LanguageName, LanguageQueries, LoadedLanguage, Rope,
  37    QUERY_FILENAME_PREFIXES,
  38};
  39use node_runtime::NodeRuntime;
  40use project::ContextProviderWithTasks;
  41use release_channel::ReleaseChannel;
  42use remote::SshRemoteClient;
  43use semantic_version::SemanticVersion;
  44use serde::{Deserialize, Serialize};
  45use settings::Settings;
  46use std::ops::RangeInclusive;
  47use std::str::FromStr;
  48use std::{
  49    cmp::Ordering,
  50    path::{self, Path, PathBuf},
  51    sync::Arc,
  52    time::{Duration, Instant},
  53};
  54use url::Url;
  55use util::ResultExt;
  56use wasm_host::{
  57    wit::{is_supported_wasm_api_version, wasm_api_version_range},
  58    WasmExtension, WasmHost,
  59};
  60
  61pub use extension::{
  62    ExtensionLibraryKind, GrammarManifestEntry, OldExtensionManifest, SchemaVersion,
  63};
  64pub use extension_settings::ExtensionSettings;
  65
  66pub const RELOAD_DEBOUNCE_DURATION: Duration = Duration::from_millis(200);
  67const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
  68
  69/// The current extension [`SchemaVersion`] supported by Zed.
  70const CURRENT_SCHEMA_VERSION: SchemaVersion = SchemaVersion(1);
  71
  72/// Returns the [`SchemaVersion`] range that is compatible with this version of Zed.
  73pub fn schema_version_range() -> RangeInclusive<SchemaVersion> {
  74    SchemaVersion::ZERO..=CURRENT_SCHEMA_VERSION
  75}
  76
  77/// Returns whether the given extension version is compatible with this version of Zed.
  78pub fn is_version_compatible(
  79    release_channel: ReleaseChannel,
  80    extension_version: &ExtensionMetadata,
  81) -> bool {
  82    let schema_version = extension_version.manifest.schema_version.unwrap_or(0);
  83    if CURRENT_SCHEMA_VERSION.0 < schema_version {
  84        return false;
  85    }
  86
  87    if let Some(wasm_api_version) = extension_version
  88        .manifest
  89        .wasm_api_version
  90        .as_ref()
  91        .and_then(|wasm_api_version| SemanticVersion::from_str(wasm_api_version).ok())
  92    {
  93        if !is_supported_wasm_api_version(release_channel, wasm_api_version) {
  94            return false;
  95        }
  96    }
  97
  98    true
  99}
 100
 101pub struct ExtensionStore {
 102    pub proxy: Arc<ExtensionHostProxy>,
 103    pub builder: Arc<ExtensionBuilder>,
 104    pub extension_index: ExtensionIndex,
 105    pub fs: Arc<dyn Fs>,
 106    pub http_client: Arc<HttpClientWithUrl>,
 107    pub telemetry: Option<Arc<Telemetry>>,
 108    pub reload_tx: UnboundedSender<Option<Arc<str>>>,
 109    pub reload_complete_senders: Vec<oneshot::Sender<()>>,
 110    pub installed_dir: PathBuf,
 111    pub outstanding_operations: BTreeMap<Arc<str>, ExtensionOperation>,
 112    pub index_path: PathBuf,
 113    pub modified_extensions: HashSet<Arc<str>>,
 114    pub wasm_host: Arc<WasmHost>,
 115    pub wasm_extensions: Vec<(Arc<ExtensionManifest>, WasmExtension)>,
 116    pub tasks: Vec<Task<()>>,
 117    pub ssh_clients: HashMap<String, WeakEntity<SshRemoteClient>>,
 118    pub ssh_registered_tx: UnboundedSender<()>,
 119}
 120
 121#[derive(Clone, Copy)]
 122pub enum ExtensionOperation {
 123    Upgrade,
 124    Install,
 125    Remove,
 126}
 127
 128#[derive(Clone)]
 129pub enum Event {
 130    StartedReloading,
 131    ExtensionInstalled(Arc<str>),
 132    ExtensionFailedToLoad(Arc<str>),
 133}
 134
 135impl EventEmitter<Event> for ExtensionStore {}
 136
 137struct GlobalExtensionStore(Entity<ExtensionStore>);
 138
 139impl Global for GlobalExtensionStore {}
 140
 141#[derive(Debug, Deserialize, Serialize, Default, PartialEq, Eq)]
 142pub struct ExtensionIndex {
 143    pub extensions: BTreeMap<Arc<str>, ExtensionIndexEntry>,
 144    pub themes: BTreeMap<Arc<str>, ExtensionIndexThemeEntry>,
 145    #[serde(default)]
 146    pub icon_themes: BTreeMap<Arc<str>, ExtensionIndexIconThemeEntry>,
 147    pub languages: BTreeMap<LanguageName, ExtensionIndexLanguageEntry>,
 148}
 149
 150#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
 151pub struct ExtensionIndexEntry {
 152    pub manifest: Arc<ExtensionManifest>,
 153    pub dev: bool,
 154}
 155
 156#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
 157pub struct ExtensionIndexThemeEntry {
 158    pub extension: Arc<str>,
 159    pub path: PathBuf,
 160}
 161
 162#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
 163pub struct ExtensionIndexIconThemeEntry {
 164    pub extension: Arc<str>,
 165    pub path: PathBuf,
 166}
 167
 168#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
 169pub struct ExtensionIndexLanguageEntry {
 170    pub extension: Arc<str>,
 171    pub path: PathBuf,
 172    pub matcher: LanguageMatcher,
 173    pub hidden: bool,
 174    pub grammar: Option<Arc<str>>,
 175}
 176
 177actions!(zed, [ReloadExtensions]);
 178
 179pub fn init(
 180    extension_host_proxy: Arc<ExtensionHostProxy>,
 181    fs: Arc<dyn Fs>,
 182    client: Arc<Client>,
 183    node_runtime: NodeRuntime,
 184    cx: &mut App,
 185) {
 186    ExtensionSettings::register(cx);
 187
 188    let store = cx.new(move |cx| {
 189        ExtensionStore::new(
 190            paths::extensions_dir().clone(),
 191            None,
 192            extension_host_proxy,
 193            fs,
 194            client.http_client().clone(),
 195            client.http_client().clone(),
 196            Some(client.telemetry().clone()),
 197            node_runtime,
 198            cx,
 199        )
 200    });
 201
 202    cx.on_action(|_: &ReloadExtensions, cx| {
 203        let store = cx.global::<GlobalExtensionStore>().0.clone();
 204        store.update(cx, |store, cx| drop(store.reload(None, cx)));
 205    });
 206
 207    cx.set_global(GlobalExtensionStore(store));
 208}
 209
 210impl ExtensionStore {
 211    pub fn try_global(cx: &App) -> Option<Entity<Self>> {
 212        cx.try_global::<GlobalExtensionStore>()
 213            .map(|store| store.0.clone())
 214    }
 215
 216    pub fn global(cx: &App) -> Entity<Self> {
 217        cx.global::<GlobalExtensionStore>().0.clone()
 218    }
 219
 220    pub fn new(
 221        extensions_dir: PathBuf,
 222        build_dir: Option<PathBuf>,
 223        extension_host_proxy: Arc<ExtensionHostProxy>,
 224        fs: Arc<dyn Fs>,
 225        http_client: Arc<HttpClientWithUrl>,
 226        builder_client: Arc<dyn HttpClient>,
 227        telemetry: Option<Arc<Telemetry>>,
 228        node_runtime: NodeRuntime,
 229        cx: &mut Context<Self>,
 230    ) -> Self {
 231        let work_dir = extensions_dir.join("work");
 232        let build_dir = build_dir.unwrap_or_else(|| extensions_dir.join("build"));
 233        let installed_dir = extensions_dir.join("installed");
 234        let index_path = extensions_dir.join("index.json");
 235
 236        let (reload_tx, mut reload_rx) = unbounded();
 237        let (connection_registered_tx, mut connection_registered_rx) = unbounded();
 238        let mut this = Self {
 239            proxy: extension_host_proxy.clone(),
 240            extension_index: Default::default(),
 241            installed_dir,
 242            index_path,
 243            builder: Arc::new(ExtensionBuilder::new(builder_client, build_dir)),
 244            outstanding_operations: Default::default(),
 245            modified_extensions: Default::default(),
 246            reload_complete_senders: Vec::new(),
 247            wasm_host: WasmHost::new(
 248                fs.clone(),
 249                http_client.clone(),
 250                node_runtime,
 251                extension_host_proxy,
 252                work_dir,
 253                cx,
 254            ),
 255            wasm_extensions: Vec::new(),
 256            fs,
 257            http_client,
 258            telemetry,
 259            reload_tx,
 260            tasks: Vec::new(),
 261
 262            ssh_clients: HashMap::default(),
 263            ssh_registered_tx: connection_registered_tx,
 264        };
 265
 266        // The extensions store maintains an index file, which contains a complete
 267        // list of the installed extensions and the resources that they provide.
 268        // This index is loaded synchronously on startup.
 269        let (index_content, index_metadata, extensions_metadata) =
 270            cx.background_executor().block(async {
 271                futures::join!(
 272                    this.fs.load(&this.index_path),
 273                    this.fs.metadata(&this.index_path),
 274                    this.fs.metadata(&this.installed_dir),
 275                )
 276            });
 277
 278        // Normally, there is no need to rebuild the index. But if the index file
 279        // is invalid or is out-of-date according to the filesystem mtimes, then
 280        // it must be asynchronously rebuilt.
 281        let mut extension_index = ExtensionIndex::default();
 282        let mut extension_index_needs_rebuild = true;
 283        if let Ok(index_content) = index_content {
 284            if let Some(index) = serde_json::from_str(&index_content).log_err() {
 285                extension_index = index;
 286                if let (Ok(Some(index_metadata)), Ok(Some(extensions_metadata))) =
 287                    (index_metadata, extensions_metadata)
 288                {
 289                    if index_metadata
 290                        .mtime
 291                        .bad_is_greater_than(extensions_metadata.mtime)
 292                    {
 293                        extension_index_needs_rebuild = false;
 294                    }
 295                }
 296            }
 297        }
 298
 299        // Immediately load all of the extensions in the initial manifest. If the
 300        // index needs to be rebuild, then enqueue
 301        let load_initial_extensions = this.extensions_updated(extension_index, cx);
 302        let mut reload_future = None;
 303        if extension_index_needs_rebuild {
 304            reload_future = Some(this.reload(None, cx));
 305        }
 306
 307        cx.spawn(|this, mut cx| async move {
 308            if let Some(future) = reload_future {
 309                future.await;
 310            }
 311            this.update(&mut cx, |this, cx| this.auto_install_extensions(cx))
 312                .ok();
 313            this.update(&mut cx, |this, cx| this.check_for_updates(cx))
 314                .ok();
 315        })
 316        .detach();
 317
 318        // Perform all extension loading in a single task to ensure that we
 319        // never attempt to simultaneously load/unload extensions from multiple
 320        // parallel tasks.
 321        this.tasks.push(cx.spawn(|this, mut cx| {
 322            async move {
 323                load_initial_extensions.await;
 324
 325                let mut index_changed = false;
 326                let mut debounce_timer = cx.background_spawn(futures::future::pending()).fuse();
 327                loop {
 328                    select_biased! {
 329                        _ = debounce_timer => {
 330                            if index_changed {
 331                                let index = this
 332                                    .update(&mut cx, |this, cx| this.rebuild_extension_index(cx))?
 333                                    .await;
 334                                this.update(&mut cx, |this, cx| this.extensions_updated(index, cx))?
 335                                    .await;
 336                                index_changed = false;
 337                            }
 338
 339                            Self::update_ssh_clients(&this, &mut cx).await?;
 340                        }
 341                        _ = connection_registered_rx.next() => {
 342                            debounce_timer = cx
 343                                .background_executor()
 344                                .timer(RELOAD_DEBOUNCE_DURATION)
 345                                .fuse();
 346                        }
 347                        extension_id = reload_rx.next() => {
 348                            let Some(extension_id) = extension_id else { break; };
 349                            this.update(&mut cx, |this, _| {
 350                                this.modified_extensions.extend(extension_id);
 351                            })?;
 352                            index_changed = true;
 353                            debounce_timer = cx
 354                                .background_executor()
 355                                .timer(RELOAD_DEBOUNCE_DURATION)
 356                                .fuse();
 357                        }
 358                    }
 359                }
 360
 361                anyhow::Ok(())
 362            }
 363            .map(drop)
 364        }));
 365
 366        // Watch the installed extensions directory for changes. Whenever changes are
 367        // detected, rebuild the extension index, and load/unload any extensions that
 368        // have been added, removed, or modified.
 369        this.tasks.push(cx.background_spawn({
 370            let fs = this.fs.clone();
 371            let reload_tx = this.reload_tx.clone();
 372            let installed_dir = this.installed_dir.clone();
 373            async move {
 374                let (mut paths, _) = fs.watch(&installed_dir, FS_WATCH_LATENCY).await;
 375                while let Some(events) = paths.next().await {
 376                    for event in events {
 377                        let Ok(event_path) = event.path.strip_prefix(&installed_dir) else {
 378                            continue;
 379                        };
 380
 381                        if let Some(path::Component::Normal(extension_dir_name)) =
 382                            event_path.components().next()
 383                        {
 384                            if let Some(extension_id) = extension_dir_name.to_str() {
 385                                reload_tx.unbounded_send(Some(extension_id.into())).ok();
 386                            }
 387                        }
 388                    }
 389                }
 390            }
 391        }));
 392
 393        this
 394    }
 395
 396    pub fn reload(
 397        &mut self,
 398        modified_extension: Option<Arc<str>>,
 399        cx: &mut Context<Self>,
 400    ) -> impl Future<Output = ()> {
 401        let (tx, rx) = oneshot::channel();
 402        self.reload_complete_senders.push(tx);
 403        self.reload_tx
 404            .unbounded_send(modified_extension)
 405            .expect("reload task exited");
 406        cx.emit(Event::StartedReloading);
 407
 408        async move {
 409            rx.await.ok();
 410        }
 411    }
 412
 413    fn extensions_dir(&self) -> PathBuf {
 414        self.installed_dir.clone()
 415    }
 416
 417    pub fn outstanding_operations(&self) -> &BTreeMap<Arc<str>, ExtensionOperation> {
 418        &self.outstanding_operations
 419    }
 420
 421    pub fn installed_extensions(&self) -> &BTreeMap<Arc<str>, ExtensionIndexEntry> {
 422        &self.extension_index.extensions
 423    }
 424
 425    pub fn dev_extensions(&self) -> impl Iterator<Item = &Arc<ExtensionManifest>> {
 426        self.extension_index
 427            .extensions
 428            .values()
 429            .filter_map(|extension| extension.dev.then_some(&extension.manifest))
 430    }
 431
 432    /// Returns the names of themes provided by extensions.
 433    pub fn extension_themes<'a>(
 434        &'a self,
 435        extension_id: &'a str,
 436    ) -> impl Iterator<Item = &'a Arc<str>> {
 437        self.extension_index
 438            .themes
 439            .iter()
 440            .filter_map(|(name, theme)| theme.extension.as_ref().eq(extension_id).then_some(name))
 441    }
 442
 443    /// Returns the path to the theme file within an extension, if there is an
 444    /// extension that provides the theme.
 445    pub fn path_to_extension_theme(&self, theme_name: &str) -> Option<PathBuf> {
 446        let entry = self.extension_index.themes.get(theme_name)?;
 447
 448        Some(
 449            self.extensions_dir()
 450                .join(entry.extension.as_ref())
 451                .join(&entry.path),
 452        )
 453    }
 454
 455    /// Returns the names of icon themes provided by extensions.
 456    pub fn extension_icon_themes<'a>(
 457        &'a self,
 458        extension_id: &'a str,
 459    ) -> impl Iterator<Item = &'a Arc<str>> {
 460        self.extension_index
 461            .icon_themes
 462            .iter()
 463            .filter_map(|(name, icon_theme)| {
 464                icon_theme
 465                    .extension
 466                    .as_ref()
 467                    .eq(extension_id)
 468                    .then_some(name)
 469            })
 470    }
 471
 472    /// Returns the path to the icon theme file within an extension, if there is
 473    /// an extension that provides the icon theme.
 474    pub fn path_to_extension_icon_theme(
 475        &self,
 476        icon_theme_name: &str,
 477    ) -> Option<(PathBuf, PathBuf)> {
 478        let entry = self.extension_index.icon_themes.get(icon_theme_name)?;
 479
 480        let icon_theme_path = self
 481            .extensions_dir()
 482            .join(entry.extension.as_ref())
 483            .join(&entry.path);
 484        let icons_root_path = self.extensions_dir().join(entry.extension.as_ref());
 485
 486        Some((icon_theme_path, icons_root_path))
 487    }
 488
 489    pub fn fetch_extensions(
 490        &self,
 491        search: Option<&str>,
 492        provides_filter: Option<&BTreeSet<ExtensionProvides>>,
 493        cx: &mut Context<Self>,
 494    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 495        let version = CURRENT_SCHEMA_VERSION.to_string();
 496        let mut query = vec![("max_schema_version", version.as_str())];
 497        if let Some(search) = search {
 498            query.push(("filter", search));
 499        }
 500
 501        let provides_filter = provides_filter.map(|provides_filter| {
 502            provides_filter
 503                .iter()
 504                .map(|provides| provides.to_string())
 505                .collect::<Vec<_>>()
 506                .join(",")
 507        });
 508        if let Some(provides_filter) = provides_filter.as_deref() {
 509            query.push(("provides", provides_filter));
 510        }
 511
 512        self.fetch_extensions_from_api("/extensions", &query, cx)
 513    }
 514
 515    pub fn fetch_extensions_with_update_available(
 516        &mut self,
 517        cx: &mut Context<Self>,
 518    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 519        let schema_versions = schema_version_range();
 520        let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
 521        let extension_settings = ExtensionSettings::get_global(cx);
 522        let extension_ids = self
 523            .extension_index
 524            .extensions
 525            .iter()
 526            .filter(|(id, entry)| !entry.dev && extension_settings.should_auto_update(id))
 527            .map(|(id, _)| id.as_ref())
 528            .collect::<Vec<_>>()
 529            .join(",");
 530        let task = self.fetch_extensions_from_api(
 531            "/extensions/updates",
 532            &[
 533                ("min_schema_version", &schema_versions.start().to_string()),
 534                ("max_schema_version", &schema_versions.end().to_string()),
 535                (
 536                    "min_wasm_api_version",
 537                    &wasm_api_versions.start().to_string(),
 538                ),
 539                ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
 540                ("ids", &extension_ids),
 541            ],
 542            cx,
 543        );
 544        cx.spawn(move |this, mut cx| async move {
 545            let extensions = task.await?;
 546            this.update(&mut cx, |this, _cx| {
 547                extensions
 548                    .into_iter()
 549                    .filter(|extension| {
 550                        this.extension_index.extensions.get(&extension.id).map_or(
 551                            true,
 552                            |installed_extension| {
 553                                installed_extension.manifest.version != extension.manifest.version
 554                            },
 555                        )
 556                    })
 557                    .collect()
 558            })
 559        })
 560    }
 561
 562    pub fn fetch_extension_versions(
 563        &self,
 564        extension_id: &str,
 565        cx: &mut Context<Self>,
 566    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 567        self.fetch_extensions_from_api(&format!("/extensions/{extension_id}"), &[], cx)
 568    }
 569
 570    /// Installs any extensions that should be included with Zed by default.
 571    ///
 572    /// This can be used to make certain functionality provided by extensions
 573    /// available out-of-the-box.
 574    pub fn auto_install_extensions(&mut self, cx: &mut Context<Self>) {
 575        let extension_settings = ExtensionSettings::get_global(cx);
 576
 577        let extensions_to_install = extension_settings
 578            .auto_install_extensions
 579            .keys()
 580            .filter(|extension_id| extension_settings.should_auto_install(extension_id))
 581            .filter(|extension_id| {
 582                let is_already_installed = self
 583                    .extension_index
 584                    .extensions
 585                    .contains_key(extension_id.as_ref());
 586                !is_already_installed
 587            })
 588            .cloned()
 589            .collect::<Vec<_>>();
 590
 591        cx.spawn(move |this, mut cx| async move {
 592            for extension_id in extensions_to_install {
 593                this.update(&mut cx, |this, cx| {
 594                    this.install_latest_extension(extension_id.clone(), cx);
 595                })
 596                .ok();
 597            }
 598        })
 599        .detach();
 600    }
 601
 602    pub fn check_for_updates(&mut self, cx: &mut Context<Self>) {
 603        let task = self.fetch_extensions_with_update_available(cx);
 604        cx.spawn(move |this, mut cx| async move {
 605            Self::upgrade_extensions(this, task.await?, &mut cx).await
 606        })
 607        .detach();
 608    }
 609
 610    async fn upgrade_extensions(
 611        this: WeakEntity<Self>,
 612        extensions: Vec<ExtensionMetadata>,
 613        cx: &mut AsyncApp,
 614    ) -> Result<()> {
 615        for extension in extensions {
 616            let task = this.update(cx, |this, cx| {
 617                if let Some(installed_extension) =
 618                    this.extension_index.extensions.get(&extension.id)
 619                {
 620                    let installed_version =
 621                        SemanticVersion::from_str(&installed_extension.manifest.version).ok()?;
 622                    let latest_version =
 623                        SemanticVersion::from_str(&extension.manifest.version).ok()?;
 624
 625                    if installed_version >= latest_version {
 626                        return None;
 627                    }
 628                }
 629
 630                Some(this.upgrade_extension(extension.id, extension.manifest.version, cx))
 631            })?;
 632
 633            if let Some(task) = task {
 634                task.await.log_err();
 635            }
 636        }
 637        anyhow::Ok(())
 638    }
 639
 640    fn fetch_extensions_from_api(
 641        &self,
 642        path: &str,
 643        query: &[(&str, &str)],
 644        cx: &mut Context<'_, ExtensionStore>,
 645    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 646        let url = self.http_client.build_zed_api_url(path, query);
 647        let http_client = self.http_client.clone();
 648        cx.spawn(move |_, _| async move {
 649            let mut response = http_client
 650                .get(url?.as_ref(), AsyncBody::empty(), true)
 651                .await?;
 652
 653            let mut body = Vec::new();
 654            response
 655                .body_mut()
 656                .read_to_end(&mut body)
 657                .await
 658                .context("error reading extensions")?;
 659
 660            if response.status().is_client_error() {
 661                let text = String::from_utf8_lossy(body.as_slice());
 662                bail!(
 663                    "status error {}, response: {text:?}",
 664                    response.status().as_u16()
 665                );
 666            }
 667
 668            let response: GetExtensionsResponse = serde_json::from_slice(&body)?;
 669            Ok(response.data)
 670        })
 671    }
 672
 673    pub fn install_extension(
 674        &mut self,
 675        extension_id: Arc<str>,
 676        version: Arc<str>,
 677        cx: &mut Context<Self>,
 678    ) {
 679        self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Install, cx)
 680            .detach_and_log_err(cx);
 681    }
 682
 683    fn install_or_upgrade_extension_at_endpoint(
 684        &mut self,
 685        extension_id: Arc<str>,
 686        url: Url,
 687        operation: ExtensionOperation,
 688        cx: &mut Context<Self>,
 689    ) -> Task<Result<()>> {
 690        let extension_dir = self.installed_dir.join(extension_id.as_ref());
 691        let http_client = self.http_client.clone();
 692        let fs = self.fs.clone();
 693
 694        match self.outstanding_operations.entry(extension_id.clone()) {
 695            btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
 696            btree_map::Entry::Vacant(e) => e.insert(operation),
 697        };
 698        cx.notify();
 699
 700        cx.spawn(move |this, mut cx| async move {
 701            let _finish = util::defer({
 702                let this = this.clone();
 703                let mut cx = cx.clone();
 704                let extension_id = extension_id.clone();
 705                move || {
 706                    this.update(&mut cx, |this, cx| {
 707                        this.outstanding_operations.remove(extension_id.as_ref());
 708                        cx.notify();
 709                    })
 710                    .ok();
 711                }
 712            });
 713
 714            let mut response = http_client
 715                .get(url.as_ref(), Default::default(), true)
 716                .await
 717                .map_err(|err| anyhow!("error downloading extension: {}", err))?;
 718
 719            fs.remove_dir(
 720                &extension_dir,
 721                RemoveOptions {
 722                    recursive: true,
 723                    ignore_if_not_exists: true,
 724                },
 725            )
 726            .await?;
 727
 728            let content_length = response
 729                .headers()
 730                .get(http_client::http::header::CONTENT_LENGTH)
 731                .and_then(|value| value.to_str().ok()?.parse::<usize>().ok());
 732
 733            let mut body = BufReader::new(response.body_mut());
 734            let mut tar_gz_bytes = Vec::new();
 735            body.read_to_end(&mut tar_gz_bytes).await?;
 736
 737            if let Some(content_length) = content_length {
 738                let actual_len = tar_gz_bytes.len();
 739                if content_length != actual_len {
 740                    bail!("downloaded extension size {actual_len} does not match content length {content_length}");
 741                }
 742            }
 743            let decompressed_bytes = GzipDecoder::new(BufReader::new(tar_gz_bytes.as_slice()));
 744            let archive = Archive::new(decompressed_bytes);
 745            archive.unpack(extension_dir).await?;
 746            this.update(&mut cx, |this, cx| {
 747                this.reload(Some(extension_id.clone()), cx)
 748            })?
 749            .await;
 750
 751            if let ExtensionOperation::Install = operation {
 752                this.update(&mut cx, |_, cx| {
 753                    cx.emit(Event::ExtensionInstalled(extension_id));
 754                })
 755                .ok();
 756            }
 757
 758            anyhow::Ok(())
 759        })
 760    }
 761
 762    pub fn install_latest_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
 763        log::info!("installing extension {extension_id} latest version");
 764
 765        let schema_versions = schema_version_range();
 766        let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
 767
 768        let Some(url) = self
 769            .http_client
 770            .build_zed_api_url(
 771                &format!("/extensions/{extension_id}/download"),
 772                &[
 773                    ("min_schema_version", &schema_versions.start().to_string()),
 774                    ("max_schema_version", &schema_versions.end().to_string()),
 775                    (
 776                        "min_wasm_api_version",
 777                        &wasm_api_versions.start().to_string(),
 778                    ),
 779                    ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
 780                ],
 781            )
 782            .log_err()
 783        else {
 784            return;
 785        };
 786
 787        self.install_or_upgrade_extension_at_endpoint(
 788            extension_id,
 789            url,
 790            ExtensionOperation::Install,
 791            cx,
 792        )
 793        .detach_and_log_err(cx);
 794    }
 795
 796    pub fn upgrade_extension(
 797        &mut self,
 798        extension_id: Arc<str>,
 799        version: Arc<str>,
 800        cx: &mut Context<Self>,
 801    ) -> Task<Result<()>> {
 802        self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Upgrade, cx)
 803    }
 804
 805    fn install_or_upgrade_extension(
 806        &mut self,
 807        extension_id: Arc<str>,
 808        version: Arc<str>,
 809        operation: ExtensionOperation,
 810        cx: &mut Context<Self>,
 811    ) -> Task<Result<()>> {
 812        log::info!("installing extension {extension_id} {version}");
 813        let Some(url) = self
 814            .http_client
 815            .build_zed_api_url(
 816                &format!("/extensions/{extension_id}/{version}/download"),
 817                &[],
 818            )
 819            .log_err()
 820        else {
 821            return Task::ready(Ok(()));
 822        };
 823
 824        self.install_or_upgrade_extension_at_endpoint(extension_id, url, operation, cx)
 825    }
 826
 827    pub fn uninstall_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
 828        let extension_dir = self.installed_dir.join(extension_id.as_ref());
 829        let work_dir = self.wasm_host.work_dir.join(extension_id.as_ref());
 830        let fs = self.fs.clone();
 831
 832        match self.outstanding_operations.entry(extension_id.clone()) {
 833            btree_map::Entry::Occupied(_) => return,
 834            btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
 835        };
 836
 837        cx.spawn(move |this, mut cx| async move {
 838            let _finish = util::defer({
 839                let this = this.clone();
 840                let mut cx = cx.clone();
 841                let extension_id = extension_id.clone();
 842                move || {
 843                    this.update(&mut cx, |this, cx| {
 844                        this.outstanding_operations.remove(extension_id.as_ref());
 845                        cx.notify();
 846                    })
 847                    .ok();
 848                }
 849            });
 850
 851            fs.remove_dir(
 852                &work_dir,
 853                RemoveOptions {
 854                    recursive: true,
 855                    ignore_if_not_exists: true,
 856                },
 857            )
 858            .await?;
 859
 860            fs.remove_dir(
 861                &extension_dir,
 862                RemoveOptions {
 863                    recursive: true,
 864                    ignore_if_not_exists: true,
 865                },
 866            )
 867            .await?;
 868
 869            this.update(&mut cx, |this, cx| this.reload(None, cx))?
 870                .await;
 871            anyhow::Ok(())
 872        })
 873        .detach_and_log_err(cx)
 874    }
 875
 876    pub fn install_dev_extension(
 877        &mut self,
 878        extension_source_path: PathBuf,
 879        cx: &mut Context<Self>,
 880    ) -> Task<Result<()>> {
 881        let extensions_dir = self.extensions_dir();
 882        let fs = self.fs.clone();
 883        let builder = self.builder.clone();
 884
 885        cx.spawn(move |this, mut cx| async move {
 886            let mut extension_manifest =
 887                ExtensionManifest::load(fs.clone(), &extension_source_path).await?;
 888            let extension_id = extension_manifest.id.clone();
 889
 890            if !this.update(&mut cx, |this, cx| {
 891                match this.outstanding_operations.entry(extension_id.clone()) {
 892                    btree_map::Entry::Occupied(_) => return false,
 893                    btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
 894                };
 895                cx.notify();
 896                true
 897            })? {
 898                return Ok(());
 899            }
 900
 901            let _finish = util::defer({
 902                let this = this.clone();
 903                let mut cx = cx.clone();
 904                let extension_id = extension_id.clone();
 905                move || {
 906                    this.update(&mut cx, |this, cx| {
 907                        this.outstanding_operations.remove(extension_id.as_ref());
 908                        cx.notify();
 909                    })
 910                    .ok();
 911                }
 912            });
 913
 914            cx.background_spawn({
 915                let extension_source_path = extension_source_path.clone();
 916                async move {
 917                    builder
 918                        .compile_extension(
 919                            &extension_source_path,
 920                            &mut extension_manifest,
 921                            CompileExtensionOptions { release: false },
 922                        )
 923                        .await
 924                }
 925            })
 926            .await?;
 927
 928            let output_path = &extensions_dir.join(extension_id.as_ref());
 929            if let Some(metadata) = fs.metadata(output_path).await? {
 930                if metadata.is_symlink {
 931                    fs.remove_file(
 932                        output_path,
 933                        RemoveOptions {
 934                            recursive: false,
 935                            ignore_if_not_exists: true,
 936                        },
 937                    )
 938                    .await?;
 939                } else {
 940                    bail!("extension {extension_id} is already installed");
 941                }
 942            }
 943
 944            fs.create_symlink(output_path, extension_source_path)
 945                .await?;
 946
 947            this.update(&mut cx, |this, cx| this.reload(None, cx))?
 948                .await;
 949            Ok(())
 950        })
 951    }
 952
 953    pub fn rebuild_dev_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
 954        let path = self.installed_dir.join(extension_id.as_ref());
 955        let builder = self.builder.clone();
 956        let fs = self.fs.clone();
 957
 958        match self.outstanding_operations.entry(extension_id.clone()) {
 959            btree_map::Entry::Occupied(_) => return,
 960            btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Upgrade),
 961        };
 962
 963        cx.notify();
 964        let compile = cx.background_spawn(async move {
 965            let mut manifest = ExtensionManifest::load(fs, &path).await?;
 966            builder
 967                .compile_extension(
 968                    &path,
 969                    &mut manifest,
 970                    CompileExtensionOptions { release: true },
 971                )
 972                .await
 973        });
 974
 975        cx.spawn(|this, mut cx| async move {
 976            let result = compile.await;
 977
 978            this.update(&mut cx, |this, cx| {
 979                this.outstanding_operations.remove(&extension_id);
 980                cx.notify();
 981            })?;
 982
 983            if result.is_ok() {
 984                this.update(&mut cx, |this, cx| this.reload(Some(extension_id), cx))?
 985                    .await;
 986            }
 987
 988            result
 989        })
 990        .detach_and_log_err(cx)
 991    }
 992
 993    /// Updates the set of installed extensions.
 994    ///
 995    /// First, this unloads any themes, languages, or grammars that are
 996    /// no longer in the manifest, or whose files have changed on disk.
 997    /// Then it loads any themes, languages, or grammars that are newly
 998    /// added to the manifest, or whose files have changed on disk.
 999    fn extensions_updated(
1000        &mut self,
1001        new_index: ExtensionIndex,
1002        cx: &mut Context<Self>,
1003    ) -> Task<()> {
1004        let old_index = &self.extension_index;
1005
1006        // Determine which extensions need to be loaded and unloaded, based
1007        // on the changes to the manifest and the extensions that we know have been
1008        // modified.
1009        let mut extensions_to_unload = Vec::default();
1010        let mut extensions_to_load = Vec::default();
1011        {
1012            let mut old_keys = old_index.extensions.iter().peekable();
1013            let mut new_keys = new_index.extensions.iter().peekable();
1014            loop {
1015                match (old_keys.peek(), new_keys.peek()) {
1016                    (None, None) => break,
1017                    (None, Some(_)) => {
1018                        extensions_to_load.push(new_keys.next().unwrap().0.clone());
1019                    }
1020                    (Some(_), None) => {
1021                        extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1022                    }
1023                    (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(new_key) {
1024                        Ordering::Equal => {
1025                            let (old_key, old_value) = old_keys.next().unwrap();
1026                            let (new_key, new_value) = new_keys.next().unwrap();
1027                            if old_value != new_value || self.modified_extensions.contains(old_key)
1028                            {
1029                                extensions_to_unload.push(old_key.clone());
1030                                extensions_to_load.push(new_key.clone());
1031                            }
1032                        }
1033                        Ordering::Less => {
1034                            extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1035                        }
1036                        Ordering::Greater => {
1037                            extensions_to_load.push(new_keys.next().unwrap().0.clone());
1038                        }
1039                    },
1040                }
1041            }
1042            self.modified_extensions.clear();
1043        }
1044
1045        if extensions_to_load.is_empty() && extensions_to_unload.is_empty() {
1046            return Task::ready(());
1047        }
1048
1049        let reload_count = extensions_to_unload
1050            .iter()
1051            .filter(|id| extensions_to_load.contains(id))
1052            .count();
1053
1054        log::info!(
1055            "extensions updated. loading {}, reloading {}, unloading {}",
1056            extensions_to_load.len() - reload_count,
1057            reload_count,
1058            extensions_to_unload.len() - reload_count
1059        );
1060
1061        for extension_id in &extensions_to_load {
1062            if let Some(extension) = new_index.extensions.get(extension_id) {
1063                telemetry::event!(
1064                    "Extension Loaded",
1065                    extension_id,
1066                    version = extension.manifest.version
1067                );
1068            }
1069        }
1070
1071        let themes_to_remove = old_index
1072            .themes
1073            .iter()
1074            .filter_map(|(name, entry)| {
1075                if extensions_to_unload.contains(&entry.extension) {
1076                    Some(name.clone().into())
1077                } else {
1078                    None
1079                }
1080            })
1081            .collect::<Vec<_>>();
1082        let icon_themes_to_remove = old_index
1083            .icon_themes
1084            .iter()
1085            .filter_map(|(name, entry)| {
1086                if extensions_to_unload.contains(&entry.extension) {
1087                    Some(name.clone().into())
1088                } else {
1089                    None
1090                }
1091            })
1092            .collect::<Vec<_>>();
1093        let languages_to_remove = old_index
1094            .languages
1095            .iter()
1096            .filter_map(|(name, entry)| {
1097                if extensions_to_unload.contains(&entry.extension) {
1098                    Some(name.clone())
1099                } else {
1100                    None
1101                }
1102            })
1103            .collect::<Vec<_>>();
1104        let mut grammars_to_remove = Vec::new();
1105        for extension_id in &extensions_to_unload {
1106            let Some(extension) = old_index.extensions.get(extension_id) else {
1107                continue;
1108            };
1109            grammars_to_remove.extend(extension.manifest.grammars.keys().cloned());
1110            for (language_server_name, config) in extension.manifest.language_servers.iter() {
1111                for language in config.languages() {
1112                    self.proxy
1113                        .remove_language_server(&language, language_server_name);
1114                }
1115            }
1116        }
1117
1118        self.wasm_extensions
1119            .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
1120        self.proxy.remove_user_themes(themes_to_remove);
1121        self.proxy.remove_icon_themes(icon_themes_to_remove);
1122        self.proxy
1123            .remove_languages(&languages_to_remove, &grammars_to_remove);
1124
1125        let languages_to_add = new_index
1126            .languages
1127            .iter()
1128            .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
1129            .collect::<Vec<_>>();
1130        let mut grammars_to_add = Vec::new();
1131        let mut themes_to_add = Vec::new();
1132        let mut icon_themes_to_add = Vec::new();
1133        let mut snippets_to_add = Vec::new();
1134        for extension_id in &extensions_to_load {
1135            let Some(extension) = new_index.extensions.get(extension_id) else {
1136                continue;
1137            };
1138
1139            grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
1140                let mut grammar_path = self.installed_dir.clone();
1141                grammar_path.extend([extension_id.as_ref(), "grammars"]);
1142                grammar_path.push(grammar_name.as_ref());
1143                grammar_path.set_extension("wasm");
1144                (grammar_name.clone(), grammar_path)
1145            }));
1146            themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
1147                let mut path = self.installed_dir.clone();
1148                path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1149                path
1150            }));
1151            icon_themes_to_add.extend(extension.manifest.icon_themes.iter().map(
1152                |icon_theme_path| {
1153                    let mut path = self.installed_dir.clone();
1154                    path.extend([Path::new(extension_id.as_ref()), icon_theme_path.as_path()]);
1155
1156                    let mut icons_root_path = self.installed_dir.clone();
1157                    icons_root_path.extend([Path::new(extension_id.as_ref())]);
1158
1159                    (path, icons_root_path)
1160                },
1161            ));
1162            snippets_to_add.extend(extension.manifest.snippets.iter().map(|snippets_path| {
1163                let mut path = self.installed_dir.clone();
1164                path.extend([Path::new(extension_id.as_ref()), snippets_path.as_path()]);
1165                path
1166            }));
1167        }
1168
1169        self.proxy.register_grammars(grammars_to_add);
1170
1171        for (language_name, language) in languages_to_add {
1172            let mut language_path = self.installed_dir.clone();
1173            language_path.extend([
1174                Path::new(language.extension.as_ref()),
1175                language.path.as_path(),
1176            ]);
1177            self.proxy.register_language(
1178                language_name.clone(),
1179                language.grammar.clone(),
1180                language.matcher.clone(),
1181                language.hidden,
1182                Arc::new(move || {
1183                    let config = std::fs::read_to_string(language_path.join("config.toml"))?;
1184                    let config: LanguageConfig = ::toml::from_str(&config)?;
1185                    let queries = load_plugin_queries(&language_path);
1186                    let context_provider =
1187                        std::fs::read_to_string(language_path.join("tasks.json"))
1188                            .ok()
1189                            .and_then(|contents| {
1190                                let definitions =
1191                                    serde_json_lenient::from_str(&contents).log_err()?;
1192                                Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1193                            });
1194
1195                    Ok(LoadedLanguage {
1196                        config,
1197                        queries,
1198                        context_provider,
1199                        toolchain_provider: None,
1200                    })
1201                }),
1202            );
1203        }
1204
1205        let fs = self.fs.clone();
1206        let wasm_host = self.wasm_host.clone();
1207        let root_dir = self.installed_dir.clone();
1208        let proxy = self.proxy.clone();
1209        let extension_entries = extensions_to_load
1210            .iter()
1211            .filter_map(|name| new_index.extensions.get(name).cloned())
1212            .collect::<Vec<_>>();
1213
1214        self.extension_index = new_index;
1215        cx.notify();
1216        ExtensionEvents::global(cx).update(cx, |this, cx| {
1217            this.emit(extension::Event::ExtensionsUpdated, cx)
1218        });
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}