extension_host.rs

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