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