extension_host.rs

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