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 content_length = response
 609                .headers()
 610                .get(isahc::http::header::CONTENT_LENGTH)
 611                .and_then(|value| value.to_str().ok()?.parse::<usize>().ok());
 612
 613            let mut body = BufReader::new(response.body_mut());
 614            let mut tgz_bytes = Vec::new();
 615            body.read_to_end(&mut tgz_bytes).await?;
 616
 617            if let Some(content_length) = content_length {
 618                let actual_len = tgz_bytes.len();
 619                if content_length != actual_len {
 620                    bail!("downloaded extension size {actual_len} does not match content length {content_length}");
 621                }
 622            }
 623            let decompressed_bytes = GzipDecoder::new(BufReader::new(tgz_bytes.as_slice()));
 624            // let decompressed_bytes = GzipDecoder::new(BufReader::new(tgz_bytes));
 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                self.language_registry
 981                    .remove_lsp_adapter(config.language.as_ref(), language_server_name);
 982            }
 983        }
 984
 985        self.wasm_extensions
 986            .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
 987        self.theme_registry.remove_user_themes(&themes_to_remove);
 988        self.language_registry
 989            .remove_languages(&languages_to_remove, &grammars_to_remove);
 990
 991        let languages_to_add = new_index
 992            .languages
 993            .iter()
 994            .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
 995            .collect::<Vec<_>>();
 996        let mut grammars_to_add = Vec::new();
 997        let mut themes_to_add = Vec::new();
 998        for extension_id in &extensions_to_load {
 999            let Some(extension) = new_index.extensions.get(extension_id) else {
1000                continue;
1001            };
1002
1003            grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
1004                let mut grammar_path = self.installed_dir.clone();
1005                grammar_path.extend([extension_id.as_ref(), "grammars"]);
1006                grammar_path.push(grammar_name.as_ref());
1007                grammar_path.set_extension("wasm");
1008                (grammar_name.clone(), grammar_path)
1009            }));
1010            themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
1011                let mut path = self.installed_dir.clone();
1012                path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1013                path
1014            }));
1015        }
1016
1017        self.language_registry
1018            .register_wasm_grammars(grammars_to_add);
1019
1020        for (language_name, language) in languages_to_add {
1021            let mut language_path = self.installed_dir.clone();
1022            language_path.extend([
1023                Path::new(language.extension.as_ref()),
1024                language.path.as_path(),
1025            ]);
1026            self.language_registry.register_language(
1027                language_name.clone(),
1028                language.grammar.clone(),
1029                language.matcher.clone(),
1030                move || {
1031                    let config = std::fs::read_to_string(language_path.join("config.toml"))?;
1032                    let config: LanguageConfig = ::toml::from_str(&config)?;
1033                    let queries = load_plugin_queries(&language_path);
1034                    let tasks = std::fs::read_to_string(language_path.join("tasks.json"))
1035                        .ok()
1036                        .and_then(|contents| {
1037                            let definitions = serde_json_lenient::from_str(&contents).log_err()?;
1038                            Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1039                        });
1040
1041                    Ok((config, queries, tasks))
1042                },
1043            );
1044        }
1045
1046        let fs = self.fs.clone();
1047        let wasm_host = self.wasm_host.clone();
1048        let root_dir = self.installed_dir.clone();
1049        let theme_registry = self.theme_registry.clone();
1050        let extension_entries = extensions_to_load
1051            .iter()
1052            .filter_map(|name| new_index.extensions.get(name).cloned())
1053            .collect::<Vec<_>>();
1054
1055        self.extension_index = new_index;
1056        cx.notify();
1057        cx.emit(Event::ExtensionsUpdated);
1058
1059        cx.spawn(|this, mut cx| async move {
1060            cx.background_executor()
1061                .spawn({
1062                    let fs = fs.clone();
1063                    async move {
1064                        for theme_path in &themes_to_add {
1065                            theme_registry
1066                                .load_user_theme(&theme_path, fs.clone())
1067                                .await
1068                                .log_err();
1069                        }
1070                    }
1071                })
1072                .await;
1073
1074            let mut wasm_extensions = Vec::new();
1075            for extension in extension_entries {
1076                if extension.manifest.lib.kind.is_none() {
1077                    continue;
1078                };
1079
1080                let wasm_extension = maybe!(async {
1081                    let mut path = root_dir.clone();
1082                    path.extend([extension.manifest.clone().id.as_ref(), "extension.wasm"]);
1083                    let mut wasm_file = fs
1084                        .open_sync(&path)
1085                        .await
1086                        .context("failed to open wasm file")?;
1087
1088                    let mut wasm_bytes = Vec::new();
1089                    wasm_file
1090                        .read_to_end(&mut wasm_bytes)
1091                        .context("failed to read wasm")?;
1092
1093                    wasm_host
1094                        .load_extension(
1095                            wasm_bytes,
1096                            extension.manifest.clone().clone(),
1097                            cx.background_executor().clone(),
1098                        )
1099                        .await
1100                        .with_context(|| {
1101                            format!("failed to load wasm extension {}", extension.manifest.id)
1102                        })
1103                })
1104                .await;
1105
1106                if let Some(wasm_extension) = wasm_extension.log_err() {
1107                    wasm_extensions.push((extension.manifest.clone(), wasm_extension));
1108                } else {
1109                    this.update(&mut cx, |_, cx| {
1110                        cx.emit(Event::ExtensionFailedToLoad(extension.manifest.id.clone()))
1111                    })
1112                    .ok();
1113                }
1114            }
1115
1116            this.update(&mut cx, |this, cx| {
1117                this.reload_complete_senders.clear();
1118
1119                for (manifest, wasm_extension) in &wasm_extensions {
1120                    for (language_server_name, language_server_config) in &manifest.language_servers
1121                    {
1122                        this.language_registry.register_lsp_adapter(
1123                            language_server_config.language.clone(),
1124                            Arc::new(ExtensionLspAdapter {
1125                                extension: wasm_extension.clone(),
1126                                host: this.wasm_host.clone(),
1127                                config: wit::LanguageServerConfig {
1128                                    name: language_server_name.0.to_string(),
1129                                    language_name: language_server_config.language.to_string(),
1130                                },
1131                            }),
1132                        );
1133                    }
1134                }
1135                this.wasm_extensions.extend(wasm_extensions);
1136                ThemeSettings::reload_current_theme(cx)
1137            })
1138            .ok();
1139        })
1140    }
1141
1142    fn rebuild_extension_index(&self, cx: &mut ModelContext<Self>) -> Task<ExtensionIndex> {
1143        let fs = self.fs.clone();
1144        let work_dir = self.wasm_host.work_dir.clone();
1145        let extensions_dir = self.installed_dir.clone();
1146        let index_path = self.index_path.clone();
1147        cx.background_executor().spawn(async move {
1148            let start_time = Instant::now();
1149            let mut index = ExtensionIndex::default();
1150
1151            fs.create_dir(&work_dir).await.log_err();
1152            fs.create_dir(&extensions_dir).await.log_err();
1153
1154            let extension_paths = fs.read_dir(&extensions_dir).await;
1155            if let Ok(mut extension_paths) = extension_paths {
1156                while let Some(extension_dir) = extension_paths.next().await {
1157                    let Ok(extension_dir) = extension_dir else {
1158                        continue;
1159                    };
1160
1161                    if extension_dir
1162                        .file_name()
1163                        .map_or(false, |file_name| file_name == ".DS_Store")
1164                    {
1165                        continue;
1166                    }
1167
1168                    Self::add_extension_to_index(fs.clone(), extension_dir, &mut index)
1169                        .await
1170                        .log_err();
1171                }
1172            }
1173
1174            if let Ok(index_json) = serde_json::to_string_pretty(&index) {
1175                fs.save(&index_path, &index_json.as_str().into(), Default::default())
1176                    .await
1177                    .context("failed to save extension index")
1178                    .log_err();
1179            }
1180
1181            log::info!("rebuilt extension index in {:?}", start_time.elapsed());
1182            index
1183        })
1184    }
1185
1186    async fn add_extension_to_index(
1187        fs: Arc<dyn Fs>,
1188        extension_dir: PathBuf,
1189        index: &mut ExtensionIndex,
1190    ) -> Result<()> {
1191        let mut extension_manifest = ExtensionManifest::load(fs.clone(), &extension_dir).await?;
1192        let extension_id = extension_manifest.id.clone();
1193
1194        // TODO: distinguish dev extensions more explicitly, by the absence
1195        // of a checksum file that we'll create when downloading normal extensions.
1196        let is_dev = fs
1197            .metadata(&extension_dir)
1198            .await?
1199            .ok_or_else(|| anyhow!("directory does not exist"))?
1200            .is_symlink;
1201
1202        if let Ok(mut language_paths) = fs.read_dir(&extension_dir.join("languages")).await {
1203            while let Some(language_path) = language_paths.next().await {
1204                let language_path = language_path?;
1205                let Ok(relative_path) = language_path.strip_prefix(&extension_dir) else {
1206                    continue;
1207                };
1208                let Ok(Some(fs_metadata)) = fs.metadata(&language_path).await else {
1209                    continue;
1210                };
1211                if !fs_metadata.is_dir {
1212                    continue;
1213                }
1214                let config = fs.load(&language_path.join("config.toml")).await?;
1215                let config = ::toml::from_str::<LanguageConfig>(&config)?;
1216
1217                let relative_path = relative_path.to_path_buf();
1218                if !extension_manifest.languages.contains(&relative_path) {
1219                    extension_manifest.languages.push(relative_path.clone());
1220                }
1221
1222                index.languages.insert(
1223                    config.name.clone(),
1224                    ExtensionIndexLanguageEntry {
1225                        extension: extension_id.clone(),
1226                        path: relative_path,
1227                        matcher: config.matcher,
1228                        grammar: config.grammar,
1229                    },
1230                );
1231            }
1232        }
1233
1234        if let Ok(mut theme_paths) = fs.read_dir(&extension_dir.join("themes")).await {
1235            while let Some(theme_path) = theme_paths.next().await {
1236                let theme_path = theme_path?;
1237                let Ok(relative_path) = theme_path.strip_prefix(&extension_dir) else {
1238                    continue;
1239                };
1240
1241                let Some(theme_family) = ThemeRegistry::read_user_theme(&theme_path, fs.clone())
1242                    .await
1243                    .log_err()
1244                else {
1245                    continue;
1246                };
1247
1248                let relative_path = relative_path.to_path_buf();
1249                if !extension_manifest.themes.contains(&relative_path) {
1250                    extension_manifest.themes.push(relative_path.clone());
1251                }
1252
1253                for theme in theme_family.themes {
1254                    index.themes.insert(
1255                        theme.name.into(),
1256                        ExtensionIndexThemeEntry {
1257                            extension: extension_id.clone(),
1258                            path: relative_path.clone(),
1259                        },
1260                    );
1261                }
1262            }
1263        }
1264
1265        let extension_wasm_path = extension_dir.join("extension.wasm");
1266        if fs.is_file(&extension_wasm_path).await {
1267            extension_manifest
1268                .lib
1269                .kind
1270                .get_or_insert(ExtensionLibraryKind::Rust);
1271        }
1272
1273        index.extensions.insert(
1274            extension_id.clone(),
1275            ExtensionIndexEntry {
1276                dev: is_dev,
1277                manifest: Arc::new(extension_manifest),
1278            },
1279        );
1280
1281        Ok(())
1282    }
1283}
1284
1285fn load_plugin_queries(root_path: &Path) -> LanguageQueries {
1286    let mut result = LanguageQueries::default();
1287    if let Some(entries) = std::fs::read_dir(root_path).log_err() {
1288        for entry in entries {
1289            let Some(entry) = entry.log_err() else {
1290                continue;
1291            };
1292            let path = entry.path();
1293            if let Some(remainder) = path.strip_prefix(root_path).ok().and_then(|p| p.to_str()) {
1294                if !remainder.ends_with(".scm") {
1295                    continue;
1296                }
1297                for (name, query) in QUERY_FILENAME_PREFIXES {
1298                    if remainder.starts_with(name) {
1299                        if let Some(contents) = std::fs::read_to_string(&path).log_err() {
1300                            match query(&mut result) {
1301                                None => *query(&mut result) = Some(contents.into()),
1302                                Some(r) => r.to_mut().push_str(contents.as_ref()),
1303                            }
1304                        }
1305                        break;
1306                    }
1307                }
1308            }
1309        }
1310    }
1311    result
1312}