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