extension_host.rs

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