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