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 decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
 610            let archive = Archive::new(decompressed_bytes);
 611            archive.unpack(extension_dir).await?;
 612            this.update(&mut cx, |this, cx| {
 613                this.reload(Some(extension_id.clone()), cx)
 614            })?
 615            .await;
 616
 617            match operation {
 618                ExtensionOperation::Install => {
 619                    this.update(&mut cx, |_, cx| {
 620                        cx.emit(Event::ExtensionInstalled(extension_id));
 621                    })
 622                    .ok();
 623                }
 624                _ => {}
 625            }
 626
 627            anyhow::Ok(())
 628        })
 629    }
 630
 631    pub fn install_latest_extension(
 632        &mut self,
 633        extension_id: Arc<str>,
 634        cx: &mut ModelContext<Self>,
 635    ) {
 636        log::info!("installing extension {extension_id} latest version");
 637
 638        let schema_versions = schema_version_range();
 639        let wasm_api_versions = wasm_api_version_range();
 640
 641        let Some(url) = self
 642            .http_client
 643            .build_zed_api_url(
 644                &format!("/extensions/{extension_id}/download"),
 645                &[
 646                    ("min_schema_version", &schema_versions.start().to_string()),
 647                    ("max_schema_version", &schema_versions.end().to_string()),
 648                    (
 649                        "min_wasm_api_version",
 650                        &wasm_api_versions.start().to_string(),
 651                    ),
 652                    ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
 653                ],
 654            )
 655            .log_err()
 656        else {
 657            return;
 658        };
 659
 660        self.install_or_upgrade_extension_at_endpoint(
 661            extension_id,
 662            url,
 663            ExtensionOperation::Install,
 664            cx,
 665        )
 666        .detach_and_log_err(cx);
 667    }
 668
 669    pub fn upgrade_extension(
 670        &mut self,
 671        extension_id: Arc<str>,
 672        version: Arc<str>,
 673        cx: &mut ModelContext<Self>,
 674    ) -> Task<Result<()>> {
 675        self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Upgrade, cx)
 676    }
 677
 678    fn install_or_upgrade_extension(
 679        &mut self,
 680        extension_id: Arc<str>,
 681        version: Arc<str>,
 682        operation: ExtensionOperation,
 683        cx: &mut ModelContext<Self>,
 684    ) -> Task<Result<()>> {
 685        log::info!("installing extension {extension_id} {version}");
 686        let Some(url) = self
 687            .http_client
 688            .build_zed_api_url(
 689                &format!("/extensions/{extension_id}/{version}/download"),
 690                &[],
 691            )
 692            .log_err()
 693        else {
 694            return Task::ready(Ok(()));
 695        };
 696
 697        self.install_or_upgrade_extension_at_endpoint(extension_id, url, operation, cx)
 698    }
 699
 700    pub fn uninstall_extension(&mut self, extension_id: Arc<str>, cx: &mut ModelContext<Self>) {
 701        let extension_dir = self.installed_dir.join(extension_id.as_ref());
 702        let fs = self.fs.clone();
 703
 704        match self.outstanding_operations.entry(extension_id.clone()) {
 705            btree_map::Entry::Occupied(_) => return,
 706            btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
 707        };
 708
 709        cx.spawn(move |this, mut cx| async move {
 710            let _finish = util::defer({
 711                let this = this.clone();
 712                let mut cx = cx.clone();
 713                let extension_id = extension_id.clone();
 714                move || {
 715                    this.update(&mut cx, |this, cx| {
 716                        this.outstanding_operations.remove(extension_id.as_ref());
 717                        cx.notify();
 718                    })
 719                    .ok();
 720                }
 721            });
 722
 723            fs.remove_dir(
 724                &extension_dir,
 725                RemoveOptions {
 726                    recursive: true,
 727                    ignore_if_not_exists: true,
 728                },
 729            )
 730            .await?;
 731
 732            this.update(&mut cx, |this, cx| this.reload(None, cx))?
 733                .await;
 734            anyhow::Ok(())
 735        })
 736        .detach_and_log_err(cx)
 737    }
 738
 739    pub fn install_dev_extension(
 740        &mut self,
 741        extension_source_path: PathBuf,
 742        cx: &mut ModelContext<Self>,
 743    ) -> Task<Result<()>> {
 744        let extensions_dir = self.extensions_dir();
 745        let fs = self.fs.clone();
 746        let builder = self.builder.clone();
 747
 748        cx.spawn(move |this, mut cx| async move {
 749            let mut extension_manifest =
 750                ExtensionManifest::load(fs.clone(), &extension_source_path).await?;
 751            let extension_id = extension_manifest.id.clone();
 752
 753            if !this.update(&mut cx, |this, cx| {
 754                match this.outstanding_operations.entry(extension_id.clone()) {
 755                    btree_map::Entry::Occupied(_) => return false,
 756                    btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
 757                };
 758                cx.notify();
 759                true
 760            })? {
 761                return Ok(());
 762            }
 763
 764            let _finish = util::defer({
 765                let this = this.clone();
 766                let mut cx = cx.clone();
 767                let extension_id = extension_id.clone();
 768                move || {
 769                    this.update(&mut cx, |this, cx| {
 770                        this.outstanding_operations.remove(extension_id.as_ref());
 771                        cx.notify();
 772                    })
 773                    .ok();
 774                }
 775            });
 776
 777            cx.background_executor()
 778                .spawn({
 779                    let extension_source_path = extension_source_path.clone();
 780                    async move {
 781                        builder
 782                            .compile_extension(
 783                                &extension_source_path,
 784                                &mut extension_manifest,
 785                                CompileExtensionOptions { release: false },
 786                            )
 787                            .await
 788                    }
 789                })
 790                .await?;
 791
 792            let output_path = &extensions_dir.join(extension_id.as_ref());
 793            if let Some(metadata) = fs.metadata(&output_path).await? {
 794                if metadata.is_symlink {
 795                    fs.remove_file(
 796                        &output_path,
 797                        RemoveOptions {
 798                            recursive: false,
 799                            ignore_if_not_exists: true,
 800                        },
 801                    )
 802                    .await?;
 803                } else {
 804                    bail!("extension {extension_id} is already installed");
 805                }
 806            }
 807
 808            fs.create_symlink(output_path, extension_source_path)
 809                .await?;
 810
 811            this.update(&mut cx, |this, cx| this.reload(None, cx))?
 812                .await;
 813            Ok(())
 814        })
 815    }
 816
 817    pub fn rebuild_dev_extension(&mut self, extension_id: Arc<str>, cx: &mut ModelContext<Self>) {
 818        let path = self.installed_dir.join(extension_id.as_ref());
 819        let builder = self.builder.clone();
 820        let fs = self.fs.clone();
 821
 822        match self.outstanding_operations.entry(extension_id.clone()) {
 823            btree_map::Entry::Occupied(_) => return,
 824            btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Upgrade),
 825        };
 826
 827        cx.notify();
 828        let compile = cx.background_executor().spawn(async move {
 829            let mut manifest = ExtensionManifest::load(fs, &path).await?;
 830            builder
 831                .compile_extension(
 832                    &path,
 833                    &mut manifest,
 834                    CompileExtensionOptions { release: true },
 835                )
 836                .await
 837        });
 838
 839        cx.spawn(|this, mut cx| async move {
 840            let result = compile.await;
 841
 842            this.update(&mut cx, |this, cx| {
 843                this.outstanding_operations.remove(&extension_id);
 844                cx.notify();
 845            })?;
 846
 847            if result.is_ok() {
 848                this.update(&mut cx, |this, cx| this.reload(Some(extension_id), cx))?
 849                    .await;
 850            }
 851
 852            result
 853        })
 854        .detach_and_log_err(cx)
 855    }
 856
 857    /// Updates the set of installed extensions.
 858    ///
 859    /// First, this unloads any themes, languages, or grammars that are
 860    /// no longer in the manifest, or whose files have changed on disk.
 861    /// Then it loads any themes, languages, or grammars that are newly
 862    /// added to the manifest, or whose files have changed on disk.
 863    fn extensions_updated(
 864        &mut self,
 865        new_index: ExtensionIndex,
 866        cx: &mut ModelContext<Self>,
 867    ) -> Task<()> {
 868        let old_index = &self.extension_index;
 869
 870        // Determine which extensions need to be loaded and unloaded, based
 871        // on the changes to the manifest and the extensions that we know have been
 872        // modified.
 873        let mut extensions_to_unload = Vec::default();
 874        let mut extensions_to_load = Vec::default();
 875        {
 876            let mut old_keys = old_index.extensions.iter().peekable();
 877            let mut new_keys = new_index.extensions.iter().peekable();
 878            loop {
 879                match (old_keys.peek(), new_keys.peek()) {
 880                    (None, None) => break,
 881                    (None, Some(_)) => {
 882                        extensions_to_load.push(new_keys.next().unwrap().0.clone());
 883                    }
 884                    (Some(_), None) => {
 885                        extensions_to_unload.push(old_keys.next().unwrap().0.clone());
 886                    }
 887                    (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(&new_key) {
 888                        Ordering::Equal => {
 889                            let (old_key, old_value) = old_keys.next().unwrap();
 890                            let (new_key, new_value) = new_keys.next().unwrap();
 891                            if old_value != new_value || self.modified_extensions.contains(old_key)
 892                            {
 893                                extensions_to_unload.push(old_key.clone());
 894                                extensions_to_load.push(new_key.clone());
 895                            }
 896                        }
 897                        Ordering::Less => {
 898                            extensions_to_unload.push(old_keys.next().unwrap().0.clone());
 899                        }
 900                        Ordering::Greater => {
 901                            extensions_to_load.push(new_keys.next().unwrap().0.clone());
 902                        }
 903                    },
 904                }
 905            }
 906            self.modified_extensions.clear();
 907        }
 908
 909        if extensions_to_load.is_empty() && extensions_to_unload.is_empty() {
 910            return Task::ready(());
 911        }
 912
 913        let reload_count = extensions_to_unload
 914            .iter()
 915            .filter(|id| extensions_to_load.contains(id))
 916            .count();
 917
 918        log::info!(
 919            "extensions updated. loading {}, reloading {}, unloading {}",
 920            extensions_to_load.len() - reload_count,
 921            reload_count,
 922            extensions_to_unload.len() - reload_count
 923        );
 924
 925        if let Some(telemetry) = &self.telemetry {
 926            for extension_id in &extensions_to_load {
 927                if let Some(extension) = new_index.extensions.get(extension_id) {
 928                    telemetry.report_extension_event(
 929                        extension_id.clone(),
 930                        extension.manifest.version.clone(),
 931                    );
 932                }
 933            }
 934        }
 935
 936        let themes_to_remove = old_index
 937            .themes
 938            .iter()
 939            .filter_map(|(name, entry)| {
 940                if extensions_to_unload.contains(&entry.extension) {
 941                    Some(name.clone().into())
 942                } else {
 943                    None
 944                }
 945            })
 946            .collect::<Vec<_>>();
 947        let languages_to_remove = old_index
 948            .languages
 949            .iter()
 950            .filter_map(|(name, entry)| {
 951                if extensions_to_unload.contains(&entry.extension) {
 952                    Some(name.clone())
 953                } else {
 954                    None
 955                }
 956            })
 957            .collect::<Vec<_>>();
 958        let mut grammars_to_remove = Vec::new();
 959        for extension_id in &extensions_to_unload {
 960            let Some(extension) = old_index.extensions.get(extension_id) else {
 961                continue;
 962            };
 963            grammars_to_remove.extend(extension.manifest.grammars.keys().cloned());
 964            for (language_server_name, config) in extension.manifest.language_servers.iter() {
 965                for language in config.languages() {
 966                    self.language_registry
 967                        .remove_lsp_adapter(&language, language_server_name);
 968                }
 969            }
 970        }
 971
 972        self.wasm_extensions
 973            .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
 974        self.theme_registry.remove_user_themes(&themes_to_remove);
 975        self.language_registry
 976            .remove_languages(&languages_to_remove, &grammars_to_remove);
 977
 978        let languages_to_add = new_index
 979            .languages
 980            .iter()
 981            .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
 982            .collect::<Vec<_>>();
 983        let mut grammars_to_add = Vec::new();
 984        let mut themes_to_add = Vec::new();
 985        for extension_id in &extensions_to_load {
 986            let Some(extension) = new_index.extensions.get(extension_id) else {
 987                continue;
 988            };
 989
 990            grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
 991                let mut grammar_path = self.installed_dir.clone();
 992                grammar_path.extend([extension_id.as_ref(), "grammars"]);
 993                grammar_path.push(grammar_name.as_ref());
 994                grammar_path.set_extension("wasm");
 995                (grammar_name.clone(), grammar_path)
 996            }));
 997            themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
 998                let mut path = self.installed_dir.clone();
 999                path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1000                path
1001            }));
1002        }
1003
1004        self.language_registry
1005            .register_wasm_grammars(grammars_to_add);
1006
1007        for (language_name, language) in languages_to_add {
1008            let mut language_path = self.installed_dir.clone();
1009            language_path.extend([
1010                Path::new(language.extension.as_ref()),
1011                language.path.as_path(),
1012            ]);
1013            self.language_registry.register_language(
1014                language_name.clone(),
1015                language.grammar.clone(),
1016                language.matcher.clone(),
1017                move || {
1018                    let config = std::fs::read_to_string(language_path.join("config.toml"))?;
1019                    let config: LanguageConfig = ::toml::from_str(&config)?;
1020                    let queries = load_plugin_queries(&language_path);
1021                    let tasks = std::fs::read_to_string(language_path.join("tasks.json"))
1022                        .ok()
1023                        .and_then(|contents| {
1024                            let definitions = serde_json_lenient::from_str(&contents).log_err()?;
1025                            Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1026                        });
1027
1028                    Ok((config, queries, tasks))
1029                },
1030            );
1031        }
1032
1033        let fs = self.fs.clone();
1034        let wasm_host = self.wasm_host.clone();
1035        let root_dir = self.installed_dir.clone();
1036        let theme_registry = self.theme_registry.clone();
1037        let extension_entries = extensions_to_load
1038            .iter()
1039            .filter_map(|name| new_index.extensions.get(name).cloned())
1040            .collect::<Vec<_>>();
1041
1042        self.extension_index = new_index;
1043        cx.notify();
1044        cx.emit(Event::ExtensionsUpdated);
1045
1046        cx.spawn(|this, mut cx| async move {
1047            cx.background_executor()
1048                .spawn({
1049                    let fs = fs.clone();
1050                    async move {
1051                        for theme_path in &themes_to_add {
1052                            theme_registry
1053                                .load_user_theme(&theme_path, fs.clone())
1054                                .await
1055                                .log_err();
1056                        }
1057                    }
1058                })
1059                .await;
1060
1061            let mut wasm_extensions = Vec::new();
1062            for extension in extension_entries {
1063                if extension.manifest.lib.kind.is_none() {
1064                    continue;
1065                };
1066
1067                let wasm_extension = maybe!(async {
1068                    let mut path = root_dir.clone();
1069                    path.extend([extension.manifest.clone().id.as_ref(), "extension.wasm"]);
1070                    let mut wasm_file = fs
1071                        .open_sync(&path)
1072                        .await
1073                        .context("failed to open wasm file")?;
1074
1075                    let mut wasm_bytes = Vec::new();
1076                    wasm_file
1077                        .read_to_end(&mut wasm_bytes)
1078                        .context("failed to read wasm")?;
1079
1080                    wasm_host
1081                        .load_extension(
1082                            wasm_bytes,
1083                            extension.manifest.clone().clone(),
1084                            cx.background_executor().clone(),
1085                        )
1086                        .await
1087                        .with_context(|| {
1088                            format!("failed to load wasm extension {}", extension.manifest.id)
1089                        })
1090                })
1091                .await;
1092
1093                if let Some(wasm_extension) = wasm_extension.log_err() {
1094                    wasm_extensions.push((extension.manifest.clone(), wasm_extension));
1095                } else {
1096                    this.update(&mut cx, |_, cx| {
1097                        cx.emit(Event::ExtensionFailedToLoad(extension.manifest.id.clone()))
1098                    })
1099                    .ok();
1100                }
1101            }
1102
1103            this.update(&mut cx, |this, cx| {
1104                this.reload_complete_senders.clear();
1105
1106                for (manifest, wasm_extension) in &wasm_extensions {
1107                    for (language_server_id, language_server_config) in &manifest.language_servers {
1108                        for language in language_server_config.languages() {
1109                            this.language_registry.register_lsp_adapter(
1110                                language.clone(),
1111                                Arc::new(ExtensionLspAdapter {
1112                                    extension: wasm_extension.clone(),
1113                                    host: this.wasm_host.clone(),
1114                                    language_server_id: language_server_id.clone(),
1115                                    config: wit::LanguageServerConfig {
1116                                        name: language_server_id.0.to_string(),
1117                                        language_name: language.to_string(),
1118                                    },
1119                                }),
1120                            );
1121                        }
1122                    }
1123                }
1124                this.wasm_extensions.extend(wasm_extensions);
1125                ThemeSettings::reload_current_theme(cx)
1126            })
1127            .ok();
1128        })
1129    }
1130
1131    fn rebuild_extension_index(&self, cx: &mut ModelContext<Self>) -> Task<ExtensionIndex> {
1132        let fs = self.fs.clone();
1133        let work_dir = self.wasm_host.work_dir.clone();
1134        let extensions_dir = self.installed_dir.clone();
1135        let index_path = self.index_path.clone();
1136        cx.background_executor().spawn(async move {
1137            let start_time = Instant::now();
1138            let mut index = ExtensionIndex::default();
1139
1140            fs.create_dir(&work_dir).await.log_err();
1141            fs.create_dir(&extensions_dir).await.log_err();
1142
1143            let extension_paths = fs.read_dir(&extensions_dir).await;
1144            if let Ok(mut extension_paths) = extension_paths {
1145                while let Some(extension_dir) = extension_paths.next().await {
1146                    let Ok(extension_dir) = extension_dir else {
1147                        continue;
1148                    };
1149
1150                    if extension_dir
1151                        .file_name()
1152                        .map_or(false, |file_name| file_name == ".DS_Store")
1153                    {
1154                        continue;
1155                    }
1156
1157                    Self::add_extension_to_index(fs.clone(), extension_dir, &mut index)
1158                        .await
1159                        .log_err();
1160                }
1161            }
1162
1163            if let Ok(index_json) = serde_json::to_string_pretty(&index) {
1164                fs.save(&index_path, &index_json.as_str().into(), Default::default())
1165                    .await
1166                    .context("failed to save extension index")
1167                    .log_err();
1168            }
1169
1170            log::info!("rebuilt extension index in {:?}", start_time.elapsed());
1171            index
1172        })
1173    }
1174
1175    async fn add_extension_to_index(
1176        fs: Arc<dyn Fs>,
1177        extension_dir: PathBuf,
1178        index: &mut ExtensionIndex,
1179    ) -> Result<()> {
1180        let mut extension_manifest = ExtensionManifest::load(fs.clone(), &extension_dir).await?;
1181        let extension_id = extension_manifest.id.clone();
1182
1183        // TODO: distinguish dev extensions more explicitly, by the absence
1184        // of a checksum file that we'll create when downloading normal extensions.
1185        let is_dev = fs
1186            .metadata(&extension_dir)
1187            .await?
1188            .ok_or_else(|| anyhow!("directory does not exist"))?
1189            .is_symlink;
1190
1191        if let Ok(mut language_paths) = fs.read_dir(&extension_dir.join("languages")).await {
1192            while let Some(language_path) = language_paths.next().await {
1193                let language_path = language_path?;
1194                let Ok(relative_path) = language_path.strip_prefix(&extension_dir) else {
1195                    continue;
1196                };
1197                let Ok(Some(fs_metadata)) = fs.metadata(&language_path).await else {
1198                    continue;
1199                };
1200                if !fs_metadata.is_dir {
1201                    continue;
1202                }
1203                let config = fs.load(&language_path.join("config.toml")).await?;
1204                let config = ::toml::from_str::<LanguageConfig>(&config)?;
1205
1206                let relative_path = relative_path.to_path_buf();
1207                if !extension_manifest.languages.contains(&relative_path) {
1208                    extension_manifest.languages.push(relative_path.clone());
1209                }
1210
1211                index.languages.insert(
1212                    config.name.clone(),
1213                    ExtensionIndexLanguageEntry {
1214                        extension: extension_id.clone(),
1215                        path: relative_path,
1216                        matcher: config.matcher,
1217                        grammar: config.grammar,
1218                    },
1219                );
1220            }
1221        }
1222
1223        if let Ok(mut theme_paths) = fs.read_dir(&extension_dir.join("themes")).await {
1224            while let Some(theme_path) = theme_paths.next().await {
1225                let theme_path = theme_path?;
1226                let Ok(relative_path) = theme_path.strip_prefix(&extension_dir) else {
1227                    continue;
1228                };
1229
1230                let Some(theme_family) = ThemeRegistry::read_user_theme(&theme_path, fs.clone())
1231                    .await
1232                    .log_err()
1233                else {
1234                    continue;
1235                };
1236
1237                let relative_path = relative_path.to_path_buf();
1238                if !extension_manifest.themes.contains(&relative_path) {
1239                    extension_manifest.themes.push(relative_path.clone());
1240                }
1241
1242                for theme in theme_family.themes {
1243                    index.themes.insert(
1244                        theme.name.into(),
1245                        ExtensionIndexThemeEntry {
1246                            extension: extension_id.clone(),
1247                            path: relative_path.clone(),
1248                        },
1249                    );
1250                }
1251            }
1252        }
1253
1254        let extension_wasm_path = extension_dir.join("extension.wasm");
1255        if fs.is_file(&extension_wasm_path).await {
1256            extension_manifest
1257                .lib
1258                .kind
1259                .get_or_insert(ExtensionLibraryKind::Rust);
1260        }
1261
1262        index.extensions.insert(
1263            extension_id.clone(),
1264            ExtensionIndexEntry {
1265                dev: is_dev,
1266                manifest: Arc::new(extension_manifest),
1267            },
1268        );
1269
1270        Ok(())
1271    }
1272}
1273
1274fn load_plugin_queries(root_path: &Path) -> LanguageQueries {
1275    let mut result = LanguageQueries::default();
1276    if let Some(entries) = std::fs::read_dir(root_path).log_err() {
1277        for entry in entries {
1278            let Some(entry) = entry.log_err() else {
1279                continue;
1280            };
1281            let path = entry.path();
1282            if let Some(remainder) = path.strip_prefix(root_path).ok().and_then(|p| p.to_str()) {
1283                if !remainder.ends_with(".scm") {
1284                    continue;
1285                }
1286                for (name, query) in QUERY_FILENAME_PREFIXES {
1287                    if remainder.starts_with(name) {
1288                        if let Some(contents) = std::fs::read_to_string(&path).log_err() {
1289                            match query(&mut result) {
1290                                None => *query(&mut result) = Some(contents.into()),
1291                                Some(r) => r.to_mut().push_str(contents.as_ref()),
1292                            }
1293                        }
1294                        break;
1295                    }
1296                }
1297            }
1298        }
1299    }
1300    result
1301}