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.check_for_updates(cx))
 295                .ok();
 296        })
 297        .detach();
 298
 299        // Perform all extension loading in a single task to ensure that we
 300        // never attempt to simultaneously load/unload extensions from multiple
 301        // parallel tasks.
 302        this.tasks.push(cx.spawn(|this, mut cx| {
 303            async move {
 304                load_initial_extensions.await;
 305
 306                let mut debounce_timer = cx
 307                    .background_executor()
 308                    .spawn(futures::future::pending())
 309                    .fuse();
 310                loop {
 311                    select_biased! {
 312                        _ = debounce_timer => {
 313                            let index = this
 314                                .update(&mut cx, |this, cx| this.rebuild_extension_index(cx))?
 315                                .await;
 316                            this.update(&mut cx, |this, cx| this.extensions_updated(index, cx))?
 317                                .await;
 318                        }
 319                        extension_id = reload_rx.next() => {
 320                            let Some(extension_id) = extension_id else { break; };
 321                            this.update(&mut cx, |this, _| {
 322                                this.modified_extensions.extend(extension_id);
 323                            })?;
 324                            debounce_timer = cx
 325                                .background_executor()
 326                                .timer(RELOAD_DEBOUNCE_DURATION)
 327                                .fuse();
 328                        }
 329                    }
 330                }
 331
 332                anyhow::Ok(())
 333            }
 334            .map(drop)
 335        }));
 336
 337        // Watch the installed extensions directory for changes. Whenever changes are
 338        // detected, rebuild the extension index, and load/unload any extensions that
 339        // have been added, removed, or modified.
 340        this.tasks.push(cx.background_executor().spawn({
 341            let fs = this.fs.clone();
 342            let reload_tx = this.reload_tx.clone();
 343            let installed_dir = this.installed_dir.clone();
 344            async move {
 345                let mut paths = fs.watch(&installed_dir, FS_WATCH_LATENCY).await;
 346                while let Some(paths) = paths.next().await {
 347                    for path in paths {
 348                        let Ok(event_path) = path.strip_prefix(&installed_dir) else {
 349                            continue;
 350                        };
 351
 352                        if let Some(path::Component::Normal(extension_dir_name)) =
 353                            event_path.components().next()
 354                        {
 355                            if let Some(extension_id) = extension_dir_name.to_str() {
 356                                reload_tx.unbounded_send(Some(extension_id.into())).ok();
 357                            }
 358                        }
 359                    }
 360                }
 361            }
 362        }));
 363
 364        this
 365    }
 366
 367    fn reload(
 368        &mut self,
 369        modified_extension: Option<Arc<str>>,
 370        cx: &mut ModelContext<Self>,
 371    ) -> impl Future<Output = ()> {
 372        let (tx, rx) = oneshot::channel();
 373        self.reload_complete_senders.push(tx);
 374        self.reload_tx
 375            .unbounded_send(modified_extension)
 376            .expect("reload task exited");
 377        cx.emit(Event::StartedReloading);
 378
 379        async move {
 380            rx.await.ok();
 381        }
 382    }
 383
 384    fn extensions_dir(&self) -> PathBuf {
 385        self.installed_dir.clone()
 386    }
 387
 388    pub fn outstanding_operations(&self) -> &BTreeMap<Arc<str>, ExtensionOperation> {
 389        &self.outstanding_operations
 390    }
 391
 392    pub fn installed_extensions(&self) -> &BTreeMap<Arc<str>, ExtensionIndexEntry> {
 393        &self.extension_index.extensions
 394    }
 395
 396    pub fn dev_extensions(&self) -> impl Iterator<Item = &Arc<ExtensionManifest>> {
 397        self.extension_index
 398            .extensions
 399            .values()
 400            .filter_map(|extension| extension.dev.then_some(&extension.manifest))
 401    }
 402
 403    /// Returns the names of themes provided by extensions.
 404    pub fn extension_themes<'a>(
 405        &'a self,
 406        extension_id: &'a str,
 407    ) -> impl Iterator<Item = &'a Arc<str>> {
 408        self.extension_index
 409            .themes
 410            .iter()
 411            .filter_map(|(name, theme)| theme.extension.as_ref().eq(extension_id).then_some(name))
 412    }
 413
 414    pub fn fetch_extensions(
 415        &self,
 416        search: Option<&str>,
 417        cx: &mut ModelContext<Self>,
 418    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 419        let version = CURRENT_SCHEMA_VERSION.to_string();
 420        let mut query = vec![("max_schema_version", version.as_str())];
 421        if let Some(search) = search {
 422            query.push(("filter", search));
 423        }
 424
 425        self.fetch_extensions_from_api("/extensions", &query, cx)
 426    }
 427
 428    pub fn fetch_extensions_with_update_available(
 429        &mut self,
 430        cx: &mut ModelContext<Self>,
 431    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 432        let schema_versions = schema_version_range();
 433        let wasm_api_versions = wasm_api_version_range();
 434        let extension_settings = ExtensionSettings::get_global(cx);
 435        let extension_ids = self
 436            .extension_index
 437            .extensions
 438            .keys()
 439            .map(|id| id.as_ref())
 440            .filter(|id| extension_settings.should_auto_update(id))
 441            .collect::<Vec<_>>()
 442            .join(",");
 443        let task = self.fetch_extensions_from_api(
 444            "/extensions/updates",
 445            &[
 446                ("min_schema_version", &schema_versions.start().to_string()),
 447                ("max_schema_version", &schema_versions.end().to_string()),
 448                (
 449                    "min_wasm_api_version",
 450                    &wasm_api_versions.start().to_string(),
 451                ),
 452                ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
 453                ("ids", &extension_ids),
 454            ],
 455            cx,
 456        );
 457        cx.spawn(move |this, mut cx| async move {
 458            let extensions = task.await?;
 459            this.update(&mut cx, |this, _cx| {
 460                extensions
 461                    .into_iter()
 462                    .filter(|extension| {
 463                        this.extension_index.extensions.get(&extension.id).map_or(
 464                            true,
 465                            |installed_extension| {
 466                                installed_extension.manifest.version != extension.manifest.version
 467                            },
 468                        )
 469                    })
 470                    .collect()
 471            })
 472        })
 473    }
 474
 475    pub fn fetch_extension_versions(
 476        &self,
 477        extension_id: &str,
 478        cx: &mut ModelContext<Self>,
 479    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 480        self.fetch_extensions_from_api(&format!("/extensions/{extension_id}"), &[], cx)
 481    }
 482
 483    pub fn check_for_updates(&mut self, cx: &mut ModelContext<Self>) {
 484        let task = self.fetch_extensions_with_update_available(cx);
 485        cx.spawn(move |this, mut cx| async move {
 486            Self::upgrade_extensions(this, task.await?, &mut cx).await
 487        })
 488        .detach();
 489    }
 490
 491    async fn upgrade_extensions(
 492        this: WeakModel<Self>,
 493        extensions: Vec<ExtensionMetadata>,
 494        cx: &mut AsyncAppContext,
 495    ) -> Result<()> {
 496        for extension in extensions {
 497            let task = this.update(cx, |this, cx| {
 498                if let Some(installed_extension) =
 499                    this.extension_index.extensions.get(&extension.id)
 500                {
 501                    let installed_version =
 502                        SemanticVersion::from_str(&installed_extension.manifest.version).ok()?;
 503                    let latest_version =
 504                        SemanticVersion::from_str(&extension.manifest.version).ok()?;
 505
 506                    if installed_version >= latest_version {
 507                        return None;
 508                    }
 509                }
 510
 511                Some(this.upgrade_extension(extension.id, extension.manifest.version, cx))
 512            })?;
 513
 514            if let Some(task) = task {
 515                task.await.log_err();
 516            }
 517        }
 518        anyhow::Ok(())
 519    }
 520
 521    fn fetch_extensions_from_api(
 522        &self,
 523        path: &str,
 524        query: &[(&str, &str)],
 525        cx: &mut ModelContext<'_, ExtensionStore>,
 526    ) -> Task<Result<Vec<ExtensionMetadata>>> {
 527        let url = self.http_client.build_zed_api_url(path, &query);
 528        let http_client = self.http_client.clone();
 529        cx.spawn(move |_, _| async move {
 530            let mut response = http_client
 531                .get(&url?.as_ref(), AsyncBody::empty(), true)
 532                .await?;
 533
 534            let mut body = Vec::new();
 535            response
 536                .body_mut()
 537                .read_to_end(&mut body)
 538                .await
 539                .context("error reading extensions")?;
 540
 541            if response.status().is_client_error() {
 542                let text = String::from_utf8_lossy(body.as_slice());
 543                bail!(
 544                    "status error {}, response: {text:?}",
 545                    response.status().as_u16()
 546                );
 547            }
 548
 549            let response: GetExtensionsResponse = serde_json::from_slice(&body)?;
 550            Ok(response.data)
 551        })
 552    }
 553
 554    pub fn install_extension(
 555        &mut self,
 556        extension_id: Arc<str>,
 557        version: Arc<str>,
 558        cx: &mut ModelContext<Self>,
 559    ) {
 560        self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Install, cx)
 561            .detach_and_log_err(cx);
 562    }
 563
 564    fn install_or_upgrade_extension_at_endpoint(
 565        &mut self,
 566        extension_id: Arc<str>,
 567        url: Url,
 568        operation: ExtensionOperation,
 569        cx: &mut ModelContext<Self>,
 570    ) -> Task<Result<()>> {
 571        let extension_dir = self.installed_dir.join(extension_id.as_ref());
 572        let http_client = self.http_client.clone();
 573        let fs = self.fs.clone();
 574
 575        match self.outstanding_operations.entry(extension_id.clone()) {
 576            btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
 577            btree_map::Entry::Vacant(e) => e.insert(operation),
 578        };
 579        cx.notify();
 580
 581        cx.spawn(move |this, mut cx| async move {
 582            let _finish = util::defer({
 583                let this = this.clone();
 584                let mut cx = cx.clone();
 585                let extension_id = extension_id.clone();
 586                move || {
 587                    this.update(&mut cx, |this, cx| {
 588                        this.outstanding_operations.remove(extension_id.as_ref());
 589                        cx.notify();
 590                    })
 591                    .ok();
 592                }
 593            });
 594
 595            let mut response = http_client
 596                .get(&url.as_ref(), Default::default(), true)
 597                .await
 598                .map_err(|err| anyhow!("error downloading extension: {}", err))?;
 599
 600            fs.remove_dir(
 601                &extension_dir,
 602                RemoveOptions {
 603                    recursive: true,
 604                    ignore_if_not_exists: true,
 605                },
 606            )
 607            .await?;
 608
 609            let content_length = response
 610                .headers()
 611                .get(isahc::http::header::CONTENT_LENGTH)
 612                .and_then(|value| value.to_str().ok()?.parse::<usize>().ok());
 613
 614            let mut body = BufReader::new(response.body_mut());
 615            let mut tgz_bytes = Vec::new();
 616            body.read_to_end(&mut tgz_bytes).await?;
 617
 618            if let Some(content_length) = content_length {
 619                let actual_len = tgz_bytes.len();
 620                if content_length != actual_len {
 621                    bail!("downloaded extension size {actual_len} does not match content length {content_length}");
 622                }
 623            }
 624            let decompressed_bytes = GzipDecoder::new(BufReader::new(tgz_bytes.as_slice()));
 625            // let decompressed_bytes = GzipDecoder::new(BufReader::new(tgz_bytes));
 626            let archive = Archive::new(decompressed_bytes);
 627            archive.unpack(extension_dir).await?;
 628            this.update(&mut cx, |this, cx| {
 629                this.reload(Some(extension_id.clone()), cx)
 630            })?
 631            .await;
 632
 633            match operation {
 634                ExtensionOperation::Install => {
 635                    this.update(&mut cx, |_, cx| {
 636                        cx.emit(Event::ExtensionInstalled(extension_id));
 637                    })
 638                    .ok();
 639                }
 640                _ => {}
 641            }
 642
 643            anyhow::Ok(())
 644        })
 645    }
 646
 647    pub fn install_latest_extension(
 648        &mut self,
 649        extension_id: Arc<str>,
 650        cx: &mut ModelContext<Self>,
 651    ) {
 652        log::info!("installing extension {extension_id} latest version");
 653
 654        let schema_versions = schema_version_range();
 655        let wasm_api_versions = wasm_api_version_range();
 656
 657        let Some(url) = self
 658            .http_client
 659            .build_zed_api_url(
 660                &format!("/extensions/{extension_id}/download"),
 661                &[
 662                    ("min_schema_version", &schema_versions.start().to_string()),
 663                    ("max_schema_version", &schema_versions.end().to_string()),
 664                    (
 665                        "min_wasm_api_version",
 666                        &wasm_api_versions.start().to_string(),
 667                    ),
 668                    ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
 669                ],
 670            )
 671            .log_err()
 672        else {
 673            return;
 674        };
 675
 676        self.install_or_upgrade_extension_at_endpoint(
 677            extension_id,
 678            url,
 679            ExtensionOperation::Install,
 680            cx,
 681        )
 682        .detach_and_log_err(cx);
 683    }
 684
 685    pub fn upgrade_extension(
 686        &mut self,
 687        extension_id: Arc<str>,
 688        version: Arc<str>,
 689        cx: &mut ModelContext<Self>,
 690    ) -> Task<Result<()>> {
 691        self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Upgrade, cx)
 692    }
 693
 694    fn install_or_upgrade_extension(
 695        &mut self,
 696        extension_id: Arc<str>,
 697        version: Arc<str>,
 698        operation: ExtensionOperation,
 699        cx: &mut ModelContext<Self>,
 700    ) -> Task<Result<()>> {
 701        log::info!("installing extension {extension_id} {version}");
 702        let Some(url) = self
 703            .http_client
 704            .build_zed_api_url(
 705                &format!("/extensions/{extension_id}/{version}/download"),
 706                &[],
 707            )
 708            .log_err()
 709        else {
 710            return Task::ready(Ok(()));
 711        };
 712
 713        self.install_or_upgrade_extension_at_endpoint(extension_id, url, operation, cx)
 714    }
 715
 716    pub fn uninstall_extension(&mut self, extension_id: Arc<str>, cx: &mut ModelContext<Self>) {
 717        let extension_dir = self.installed_dir.join(extension_id.as_ref());
 718        let fs = self.fs.clone();
 719
 720        match self.outstanding_operations.entry(extension_id.clone()) {
 721            btree_map::Entry::Occupied(_) => return,
 722            btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
 723        };
 724
 725        cx.spawn(move |this, mut cx| async move {
 726            let _finish = util::defer({
 727                let this = this.clone();
 728                let mut cx = cx.clone();
 729                let extension_id = extension_id.clone();
 730                move || {
 731                    this.update(&mut cx, |this, cx| {
 732                        this.outstanding_operations.remove(extension_id.as_ref());
 733                        cx.notify();
 734                    })
 735                    .ok();
 736                }
 737            });
 738
 739            fs.remove_dir(
 740                &extension_dir,
 741                RemoveOptions {
 742                    recursive: true,
 743                    ignore_if_not_exists: true,
 744                },
 745            )
 746            .await?;
 747
 748            this.update(&mut cx, |this, cx| this.reload(None, cx))?
 749                .await;
 750            anyhow::Ok(())
 751        })
 752        .detach_and_log_err(cx)
 753    }
 754
 755    pub fn install_dev_extension(
 756        &mut self,
 757        extension_source_path: PathBuf,
 758        cx: &mut ModelContext<Self>,
 759    ) -> Task<Result<()>> {
 760        let extensions_dir = self.extensions_dir();
 761        let fs = self.fs.clone();
 762        let builder = self.builder.clone();
 763
 764        cx.spawn(move |this, mut cx| async move {
 765            let mut extension_manifest =
 766                ExtensionManifest::load(fs.clone(), &extension_source_path).await?;
 767            let extension_id = extension_manifest.id.clone();
 768
 769            if !this.update(&mut cx, |this, cx| {
 770                match this.outstanding_operations.entry(extension_id.clone()) {
 771                    btree_map::Entry::Occupied(_) => return false,
 772                    btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
 773                };
 774                cx.notify();
 775                true
 776            })? {
 777                return Ok(());
 778            }
 779
 780            let _finish = util::defer({
 781                let this = this.clone();
 782                let mut cx = cx.clone();
 783                let extension_id = extension_id.clone();
 784                move || {
 785                    this.update(&mut cx, |this, cx| {
 786                        this.outstanding_operations.remove(extension_id.as_ref());
 787                        cx.notify();
 788                    })
 789                    .ok();
 790                }
 791            });
 792
 793            cx.background_executor()
 794                .spawn({
 795                    let extension_source_path = extension_source_path.clone();
 796                    async move {
 797                        builder
 798                            .compile_extension(
 799                                &extension_source_path,
 800                                &mut extension_manifest,
 801                                CompileExtensionOptions { release: false },
 802                            )
 803                            .await
 804                    }
 805                })
 806                .await?;
 807
 808            let output_path = &extensions_dir.join(extension_id.as_ref());
 809            if let Some(metadata) = fs.metadata(&output_path).await? {
 810                if metadata.is_symlink {
 811                    fs.remove_file(
 812                        &output_path,
 813                        RemoveOptions {
 814                            recursive: false,
 815                            ignore_if_not_exists: true,
 816                        },
 817                    )
 818                    .await?;
 819                } else {
 820                    bail!("extension {extension_id} is already installed");
 821                }
 822            }
 823
 824            fs.create_symlink(output_path, extension_source_path)
 825                .await?;
 826
 827            this.update(&mut cx, |this, cx| this.reload(None, cx))?
 828                .await;
 829            Ok(())
 830        })
 831    }
 832
 833    pub fn rebuild_dev_extension(&mut self, extension_id: Arc<str>, cx: &mut ModelContext<Self>) {
 834        let path = self.installed_dir.join(extension_id.as_ref());
 835        let builder = self.builder.clone();
 836        let fs = self.fs.clone();
 837
 838        match self.outstanding_operations.entry(extension_id.clone()) {
 839            btree_map::Entry::Occupied(_) => return,
 840            btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Upgrade),
 841        };
 842
 843        cx.notify();
 844        let compile = cx.background_executor().spawn(async move {
 845            let mut manifest = ExtensionManifest::load(fs, &path).await?;
 846            builder
 847                .compile_extension(
 848                    &path,
 849                    &mut manifest,
 850                    CompileExtensionOptions { release: true },
 851                )
 852                .await
 853        });
 854
 855        cx.spawn(|this, mut cx| async move {
 856            let result = compile.await;
 857
 858            this.update(&mut cx, |this, cx| {
 859                this.outstanding_operations.remove(&extension_id);
 860                cx.notify();
 861            })?;
 862
 863            if result.is_ok() {
 864                this.update(&mut cx, |this, cx| this.reload(Some(extension_id), cx))?
 865                    .await;
 866            }
 867
 868            result
 869        })
 870        .detach_and_log_err(cx)
 871    }
 872
 873    /// Updates the set of installed extensions.
 874    ///
 875    /// First, this unloads any themes, languages, or grammars that are
 876    /// no longer in the manifest, or whose files have changed on disk.
 877    /// Then it loads any themes, languages, or grammars that are newly
 878    /// added to the manifest, or whose files have changed on disk.
 879    fn extensions_updated(
 880        &mut self,
 881        new_index: ExtensionIndex,
 882        cx: &mut ModelContext<Self>,
 883    ) -> Task<()> {
 884        let old_index = &self.extension_index;
 885
 886        // Determine which extensions need to be loaded and unloaded, based
 887        // on the changes to the manifest and the extensions that we know have been
 888        // modified.
 889        let mut extensions_to_unload = Vec::default();
 890        let mut extensions_to_load = Vec::default();
 891        {
 892            let mut old_keys = old_index.extensions.iter().peekable();
 893            let mut new_keys = new_index.extensions.iter().peekable();
 894            loop {
 895                match (old_keys.peek(), new_keys.peek()) {
 896                    (None, None) => break,
 897                    (None, Some(_)) => {
 898                        extensions_to_load.push(new_keys.next().unwrap().0.clone());
 899                    }
 900                    (Some(_), None) => {
 901                        extensions_to_unload.push(old_keys.next().unwrap().0.clone());
 902                    }
 903                    (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(&new_key) {
 904                        Ordering::Equal => {
 905                            let (old_key, old_value) = old_keys.next().unwrap();
 906                            let (new_key, new_value) = new_keys.next().unwrap();
 907                            if old_value != new_value || self.modified_extensions.contains(old_key)
 908                            {
 909                                extensions_to_unload.push(old_key.clone());
 910                                extensions_to_load.push(new_key.clone());
 911                            }
 912                        }
 913                        Ordering::Less => {
 914                            extensions_to_unload.push(old_keys.next().unwrap().0.clone());
 915                        }
 916                        Ordering::Greater => {
 917                            extensions_to_load.push(new_keys.next().unwrap().0.clone());
 918                        }
 919                    },
 920                }
 921            }
 922            self.modified_extensions.clear();
 923        }
 924
 925        if extensions_to_load.is_empty() && extensions_to_unload.is_empty() {
 926            return Task::ready(());
 927        }
 928
 929        let reload_count = extensions_to_unload
 930            .iter()
 931            .filter(|id| extensions_to_load.contains(id))
 932            .count();
 933
 934        log::info!(
 935            "extensions updated. loading {}, reloading {}, unloading {}",
 936            extensions_to_load.len() - reload_count,
 937            reload_count,
 938            extensions_to_unload.len() - reload_count
 939        );
 940
 941        if let Some(telemetry) = &self.telemetry {
 942            for extension_id in &extensions_to_load {
 943                if let Some(extension) = new_index.extensions.get(extension_id) {
 944                    telemetry.report_extension_event(
 945                        extension_id.clone(),
 946                        extension.manifest.version.clone(),
 947                    );
 948                }
 949            }
 950        }
 951
 952        let themes_to_remove = old_index
 953            .themes
 954            .iter()
 955            .filter_map(|(name, entry)| {
 956                if extensions_to_unload.contains(&entry.extension) {
 957                    Some(name.clone().into())
 958                } else {
 959                    None
 960                }
 961            })
 962            .collect::<Vec<_>>();
 963        let languages_to_remove = old_index
 964            .languages
 965            .iter()
 966            .filter_map(|(name, entry)| {
 967                if extensions_to_unload.contains(&entry.extension) {
 968                    Some(name.clone())
 969                } else {
 970                    None
 971                }
 972            })
 973            .collect::<Vec<_>>();
 974        let mut grammars_to_remove = Vec::new();
 975        for extension_id in &extensions_to_unload {
 976            let Some(extension) = old_index.extensions.get(extension_id) else {
 977                continue;
 978            };
 979            grammars_to_remove.extend(extension.manifest.grammars.keys().cloned());
 980            for (language_server_name, config) in extension.manifest.language_servers.iter() {
 981                for language in config.languages() {
 982                    self.language_registry
 983                        .remove_lsp_adapter(&language, language_server_name);
 984                }
 985            }
 986        }
 987
 988        self.wasm_extensions
 989            .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
 990        self.theme_registry.remove_user_themes(&themes_to_remove);
 991        self.language_registry
 992            .remove_languages(&languages_to_remove, &grammars_to_remove);
 993
 994        let languages_to_add = new_index
 995            .languages
 996            .iter()
 997            .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
 998            .collect::<Vec<_>>();
 999        let mut grammars_to_add = Vec::new();
1000        let mut themes_to_add = Vec::new();
1001        for extension_id in &extensions_to_load {
1002            let Some(extension) = new_index.extensions.get(extension_id) else {
1003                continue;
1004            };
1005
1006            grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
1007                let mut grammar_path = self.installed_dir.clone();
1008                grammar_path.extend([extension_id.as_ref(), "grammars"]);
1009                grammar_path.push(grammar_name.as_ref());
1010                grammar_path.set_extension("wasm");
1011                (grammar_name.clone(), grammar_path)
1012            }));
1013            themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
1014                let mut path = self.installed_dir.clone();
1015                path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1016                path
1017            }));
1018        }
1019
1020        self.language_registry
1021            .register_wasm_grammars(grammars_to_add);
1022
1023        for (language_name, language) in languages_to_add {
1024            let mut language_path = self.installed_dir.clone();
1025            language_path.extend([
1026                Path::new(language.extension.as_ref()),
1027                language.path.as_path(),
1028            ]);
1029            self.language_registry.register_language(
1030                language_name.clone(),
1031                language.grammar.clone(),
1032                language.matcher.clone(),
1033                move || {
1034                    let config = std::fs::read_to_string(language_path.join("config.toml"))?;
1035                    let config: LanguageConfig = ::toml::from_str(&config)?;
1036                    let queries = load_plugin_queries(&language_path);
1037                    let tasks = std::fs::read_to_string(language_path.join("tasks.json"))
1038                        .ok()
1039                        .and_then(|contents| {
1040                            let definitions = serde_json_lenient::from_str(&contents).log_err()?;
1041                            Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1042                        });
1043
1044                    Ok((config, queries, tasks))
1045                },
1046            );
1047        }
1048
1049        let fs = self.fs.clone();
1050        let wasm_host = self.wasm_host.clone();
1051        let root_dir = self.installed_dir.clone();
1052        let theme_registry = self.theme_registry.clone();
1053        let extension_entries = extensions_to_load
1054            .iter()
1055            .filter_map(|name| new_index.extensions.get(name).cloned())
1056            .collect::<Vec<_>>();
1057
1058        self.extension_index = new_index;
1059        cx.notify();
1060        cx.emit(Event::ExtensionsUpdated);
1061
1062        cx.spawn(|this, mut cx| async move {
1063            cx.background_executor()
1064                .spawn({
1065                    let fs = fs.clone();
1066                    async move {
1067                        for theme_path in &themes_to_add {
1068                            theme_registry
1069                                .load_user_theme(&theme_path, fs.clone())
1070                                .await
1071                                .log_err();
1072                        }
1073                    }
1074                })
1075                .await;
1076
1077            let mut wasm_extensions = Vec::new();
1078            for extension in extension_entries {
1079                if extension.manifest.lib.kind.is_none() {
1080                    continue;
1081                };
1082
1083                let wasm_extension = maybe!(async {
1084                    let mut path = root_dir.clone();
1085                    path.extend([extension.manifest.clone().id.as_ref(), "extension.wasm"]);
1086                    let mut wasm_file = fs
1087                        .open_sync(&path)
1088                        .await
1089                        .context("failed to open wasm file")?;
1090
1091                    let mut wasm_bytes = Vec::new();
1092                    wasm_file
1093                        .read_to_end(&mut wasm_bytes)
1094                        .context("failed to read wasm")?;
1095
1096                    wasm_host
1097                        .load_extension(
1098                            wasm_bytes,
1099                            extension.manifest.clone().clone(),
1100                            cx.background_executor().clone(),
1101                        )
1102                        .await
1103                        .with_context(|| {
1104                            format!("failed to load wasm extension {}", extension.manifest.id)
1105                        })
1106                })
1107                .await;
1108
1109                if let Some(wasm_extension) = wasm_extension.log_err() {
1110                    wasm_extensions.push((extension.manifest.clone(), wasm_extension));
1111                } else {
1112                    this.update(&mut cx, |_, cx| {
1113                        cx.emit(Event::ExtensionFailedToLoad(extension.manifest.id.clone()))
1114                    })
1115                    .ok();
1116                }
1117            }
1118
1119            this.update(&mut cx, |this, cx| {
1120                this.reload_complete_senders.clear();
1121
1122                for (manifest, wasm_extension) in &wasm_extensions {
1123                    for (language_server_id, language_server_config) in &manifest.language_servers {
1124                        for language in language_server_config.languages() {
1125                            this.language_registry.register_lsp_adapter(
1126                                language.clone(),
1127                                Arc::new(ExtensionLspAdapter {
1128                                    extension: wasm_extension.clone(),
1129                                    host: this.wasm_host.clone(),
1130                                    language_server_id: language_server_id.clone(),
1131                                    config: wit::LanguageServerConfig {
1132                                        name: language_server_id.0.to_string(),
1133                                        language_name: language.to_string(),
1134                                    },
1135                                }),
1136                            );
1137                        }
1138                    }
1139                }
1140                this.wasm_extensions.extend(wasm_extensions);
1141                ThemeSettings::reload_current_theme(cx)
1142            })
1143            .ok();
1144        })
1145    }
1146
1147    fn rebuild_extension_index(&self, cx: &mut ModelContext<Self>) -> Task<ExtensionIndex> {
1148        let fs = self.fs.clone();
1149        let work_dir = self.wasm_host.work_dir.clone();
1150        let extensions_dir = self.installed_dir.clone();
1151        let index_path = self.index_path.clone();
1152        cx.background_executor().spawn(async move {
1153            let start_time = Instant::now();
1154            let mut index = ExtensionIndex::default();
1155
1156            fs.create_dir(&work_dir).await.log_err();
1157            fs.create_dir(&extensions_dir).await.log_err();
1158
1159            let extension_paths = fs.read_dir(&extensions_dir).await;
1160            if let Ok(mut extension_paths) = extension_paths {
1161                while let Some(extension_dir) = extension_paths.next().await {
1162                    let Ok(extension_dir) = extension_dir else {
1163                        continue;
1164                    };
1165
1166                    if extension_dir
1167                        .file_name()
1168                        .map_or(false, |file_name| file_name == ".DS_Store")
1169                    {
1170                        continue;
1171                    }
1172
1173                    Self::add_extension_to_index(fs.clone(), extension_dir, &mut index)
1174                        .await
1175                        .log_err();
1176                }
1177            }
1178
1179            if let Ok(index_json) = serde_json::to_string_pretty(&index) {
1180                fs.save(&index_path, &index_json.as_str().into(), Default::default())
1181                    .await
1182                    .context("failed to save extension index")
1183                    .log_err();
1184            }
1185
1186            log::info!("rebuilt extension index in {:?}", start_time.elapsed());
1187            index
1188        })
1189    }
1190
1191    async fn add_extension_to_index(
1192        fs: Arc<dyn Fs>,
1193        extension_dir: PathBuf,
1194        index: &mut ExtensionIndex,
1195    ) -> Result<()> {
1196        let mut extension_manifest = ExtensionManifest::load(fs.clone(), &extension_dir).await?;
1197        let extension_id = extension_manifest.id.clone();
1198
1199        // TODO: distinguish dev extensions more explicitly, by the absence
1200        // of a checksum file that we'll create when downloading normal extensions.
1201        let is_dev = fs
1202            .metadata(&extension_dir)
1203            .await?
1204            .ok_or_else(|| anyhow!("directory does not exist"))?
1205            .is_symlink;
1206
1207        if let Ok(mut language_paths) = fs.read_dir(&extension_dir.join("languages")).await {
1208            while let Some(language_path) = language_paths.next().await {
1209                let language_path = language_path?;
1210                let Ok(relative_path) = language_path.strip_prefix(&extension_dir) else {
1211                    continue;
1212                };
1213                let Ok(Some(fs_metadata)) = fs.metadata(&language_path).await else {
1214                    continue;
1215                };
1216                if !fs_metadata.is_dir {
1217                    continue;
1218                }
1219                let config = fs.load(&language_path.join("config.toml")).await?;
1220                let config = ::toml::from_str::<LanguageConfig>(&config)?;
1221
1222                let relative_path = relative_path.to_path_buf();
1223                if !extension_manifest.languages.contains(&relative_path) {
1224                    extension_manifest.languages.push(relative_path.clone());
1225                }
1226
1227                index.languages.insert(
1228                    config.name.clone(),
1229                    ExtensionIndexLanguageEntry {
1230                        extension: extension_id.clone(),
1231                        path: relative_path,
1232                        matcher: config.matcher,
1233                        grammar: config.grammar,
1234                    },
1235                );
1236            }
1237        }
1238
1239        if let Ok(mut theme_paths) = fs.read_dir(&extension_dir.join("themes")).await {
1240            while let Some(theme_path) = theme_paths.next().await {
1241                let theme_path = theme_path?;
1242                let Ok(relative_path) = theme_path.strip_prefix(&extension_dir) else {
1243                    continue;
1244                };
1245
1246                let Some(theme_family) = ThemeRegistry::read_user_theme(&theme_path, fs.clone())
1247                    .await
1248                    .log_err()
1249                else {
1250                    continue;
1251                };
1252
1253                let relative_path = relative_path.to_path_buf();
1254                if !extension_manifest.themes.contains(&relative_path) {
1255                    extension_manifest.themes.push(relative_path.clone());
1256                }
1257
1258                for theme in theme_family.themes {
1259                    index.themes.insert(
1260                        theme.name.into(),
1261                        ExtensionIndexThemeEntry {
1262                            extension: extension_id.clone(),
1263                            path: relative_path.clone(),
1264                        },
1265                    );
1266                }
1267            }
1268        }
1269
1270        let extension_wasm_path = extension_dir.join("extension.wasm");
1271        if fs.is_file(&extension_wasm_path).await {
1272            extension_manifest
1273                .lib
1274                .kind
1275                .get_or_insert(ExtensionLibraryKind::Rust);
1276        }
1277
1278        index.extensions.insert(
1279            extension_id.clone(),
1280            ExtensionIndexEntry {
1281                dev: is_dev,
1282                manifest: Arc::new(extension_manifest),
1283            },
1284        );
1285
1286        Ok(())
1287    }
1288}
1289
1290fn load_plugin_queries(root_path: &Path) -> LanguageQueries {
1291    let mut result = LanguageQueries::default();
1292    if let Some(entries) = std::fs::read_dir(root_path).log_err() {
1293        for entry in entries {
1294            let Some(entry) = entry.log_err() else {
1295                continue;
1296            };
1297            let path = entry.path();
1298            if let Some(remainder) = path.strip_prefix(root_path).ok().and_then(|p| p.to_str()) {
1299                if !remainder.ends_with(".scm") {
1300                    continue;
1301                }
1302                for (name, query) in QUERY_FILENAME_PREFIXES {
1303                    if remainder.starts_with(name) {
1304                        if let Some(contents) = std::fs::read_to_string(&path).log_err() {
1305                            match query(&mut result) {
1306                                None => *query(&mut result) = Some(contents.into()),
1307                                Some(r) => r.to_mut().push_str(contents.as_ref()),
1308                            }
1309                        }
1310                        break;
1311                    }
1312                }
1313            }
1314        }
1315    }
1316    result
1317}