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