extension_store.rs

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