extension_host.rs

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