extension_host.rs

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