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