extension_host.rs

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