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