1pub mod extension_builder;
2mod extension_indexed_docs_provider;
3mod extension_lsp_adapter;
4mod extension_manifest;
5mod extension_settings;
6mod extension_slash_command;
7mod wasm_host;
8
9#[cfg(test)]
10mod extension_store_test;
11
12use crate::extension_indexed_docs_provider::ExtensionIndexedDocsProvider;
13use crate::extension_manifest::SchemaVersion;
14use crate::extension_slash_command::ExtensionSlashCommand;
15use crate::{extension_lsp_adapter::ExtensionLspAdapter, wasm_host::wit};
16use anyhow::{anyhow, bail, Context as _, Result};
17use assistant_slash_command::SlashCommandRegistry;
18use async_compression::futures::bufread::GzipDecoder;
19use async_tar::Archive;
20use client::{telemetry::Telemetry, Client, ExtensionMetadata, GetExtensionsResponse};
21use collections::{btree_map, BTreeMap, HashSet};
22use extension_builder::{CompileExtensionOptions, ExtensionBuilder};
23use fs::{Fs, RemoveOptions};
24use futures::{
25 channel::{
26 mpsc::{unbounded, UnboundedSender},
27 oneshot,
28 },
29 io::BufReader,
30 select_biased, AsyncReadExt as _, Future, FutureExt as _, StreamExt as _,
31};
32use gpui::{
33 actions, AppContext, AsyncAppContext, Context, EventEmitter, Global, Model, ModelContext, Task,
34 WeakModel,
35};
36use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
37use indexed_docs::{IndexedDocsRegistry, ProviderId};
38use language::{
39 LanguageConfig, LanguageMatcher, LanguageQueries, LanguageRegistry, QUERY_FILENAME_PREFIXES,
40};
41use node_runtime::NodeRuntime;
42use project::ContextProviderWithTasks;
43use release_channel::ReleaseChannel;
44use semantic_version::SemanticVersion;
45use serde::{Deserialize, Serialize};
46use settings::Settings;
47use snippet_provider::SnippetRegistry;
48use std::ops::RangeInclusive;
49use std::str::FromStr;
50use std::{
51 cmp::Ordering,
52 path::{self, Path, PathBuf},
53 sync::Arc,
54 time::{Duration, Instant},
55};
56use theme::{ThemeRegistry, ThemeSettings};
57use url::Url;
58use util::{maybe, ResultExt};
59use wasm_host::{
60 wit::{is_supported_wasm_api_version, wasm_api_version_range},
61 WasmExtension, WasmHost,
62};
63
64pub use extension_manifest::{
65 ExtensionLibraryKind, ExtensionManifest, GrammarManifestEntry, OldExtensionManifest,
66};
67pub use extension_settings::ExtensionSettings;
68
69const RELOAD_DEBOUNCE_DURATION: Duration = Duration::from_millis(200);
70const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
71
72/// The current extension [`SchemaVersion`] supported by Zed.
73const CURRENT_SCHEMA_VERSION: SchemaVersion = SchemaVersion(1);
74
75/// Returns the [`SchemaVersion`] range that is compatible with this version of Zed.
76pub fn schema_version_range() -> RangeInclusive<SchemaVersion> {
77 SchemaVersion::ZERO..=CURRENT_SCHEMA_VERSION
78}
79
80/// Returns whether the given extension version is compatible with this version of Zed.
81pub fn is_version_compatible(
82 release_channel: ReleaseChannel,
83 extension_version: &ExtensionMetadata,
84) -> bool {
85 let schema_version = extension_version.manifest.schema_version.unwrap_or(0);
86 if CURRENT_SCHEMA_VERSION.0 < schema_version {
87 return false;
88 }
89
90 if let Some(wasm_api_version) = extension_version
91 .manifest
92 .wasm_api_version
93 .as_ref()
94 .and_then(|wasm_api_version| SemanticVersion::from_str(wasm_api_version).ok())
95 {
96 if !is_supported_wasm_api_version(release_channel, wasm_api_version) {
97 return false;
98 }
99 }
100
101 true
102}
103
104pub struct ExtensionStore {
105 builder: Arc<ExtensionBuilder>,
106 extension_index: ExtensionIndex,
107 fs: Arc<dyn Fs>,
108 http_client: Arc<HttpClientWithUrl>,
109 telemetry: Option<Arc<Telemetry>>,
110 reload_tx: UnboundedSender<Option<Arc<str>>>,
111 reload_complete_senders: Vec<oneshot::Sender<()>>,
112 installed_dir: PathBuf,
113 outstanding_operations: BTreeMap<Arc<str>, ExtensionOperation>,
114 index_path: PathBuf,
115 language_registry: Arc<LanguageRegistry>,
116 theme_registry: Arc<ThemeRegistry>,
117 slash_command_registry: Arc<SlashCommandRegistry>,
118 indexed_docs_registry: Arc<IndexedDocsRegistry>,
119 snippet_registry: Arc<SnippetRegistry>,
120 modified_extensions: HashSet<Arc<str>>,
121 wasm_host: Arc<WasmHost>,
122 wasm_extensions: Vec<(Arc<ExtensionManifest>, WasmExtension)>,
123 tasks: Vec<Task<()>>,
124}
125
126#[derive(Clone, Copy)]
127pub enum ExtensionOperation {
128 Upgrade,
129 Install,
130 Remove,
131}
132
133#[derive(Clone)]
134pub enum Event {
135 ExtensionsUpdated,
136 StartedReloading,
137 ExtensionInstalled(Arc<str>),
138 ExtensionFailedToLoad(Arc<str>),
139}
140
141impl EventEmitter<Event> for ExtensionStore {}
142
143struct GlobalExtensionStore(Model<ExtensionStore>);
144
145impl Global for GlobalExtensionStore {}
146
147#[derive(Debug, Deserialize, Serialize, Default, PartialEq, Eq)]
148pub struct ExtensionIndex {
149 pub extensions: BTreeMap<Arc<str>, ExtensionIndexEntry>,
150 pub themes: BTreeMap<Arc<str>, ExtensionIndexThemeEntry>,
151 pub languages: BTreeMap<Arc<str>, ExtensionIndexLanguageEntry>,
152}
153
154#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
155pub struct ExtensionIndexEntry {
156 pub manifest: Arc<ExtensionManifest>,
157 pub dev: bool,
158}
159
160#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
161pub struct ExtensionIndexThemeEntry {
162 extension: Arc<str>,
163 path: PathBuf,
164}
165
166#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
167pub struct ExtensionIndexLanguageEntry {
168 extension: Arc<str>,
169 path: PathBuf,
170 matcher: LanguageMatcher,
171 grammar: Option<Arc<str>>,
172}
173
174actions!(zed, [ReloadExtensions]);
175
176pub fn init(
177 fs: Arc<dyn Fs>,
178 client: Arc<Client>,
179 node_runtime: Arc<dyn NodeRuntime>,
180 language_registry: Arc<LanguageRegistry>,
181 theme_registry: Arc<ThemeRegistry>,
182 cx: &mut AppContext,
183) {
184 ExtensionSettings::register(cx);
185
186 let store = cx.new_model(move |cx| {
187 ExtensionStore::new(
188 paths::extensions_dir().clone(),
189 None,
190 fs,
191 client.http_client().clone(),
192 Some(client.telemetry().clone()),
193 node_runtime,
194 language_registry,
195 theme_registry,
196 SlashCommandRegistry::global(cx),
197 IndexedDocsRegistry::global(cx),
198 SnippetRegistry::global(cx),
199 cx,
200 )
201 });
202
203 cx.on_action(|_: &ReloadExtensions, cx| {
204 let store = cx.global::<GlobalExtensionStore>().0.clone();
205 store.update(cx, |store, cx| drop(store.reload(None, cx)));
206 });
207
208 cx.set_global(GlobalExtensionStore(store));
209}
210
211impl ExtensionStore {
212 pub fn try_global(cx: &AppContext) -> Option<Model<Self>> {
213 cx.try_global::<GlobalExtensionStore>()
214 .map(|store| store.0.clone())
215 }
216
217 pub fn global(cx: &AppContext) -> Model<Self> {
218 cx.global::<GlobalExtensionStore>().0.clone()
219 }
220
221 #[allow(clippy::too_many_arguments)]
222 pub fn new(
223 extensions_dir: PathBuf,
224 build_dir: Option<PathBuf>,
225 fs: Arc<dyn Fs>,
226 http_client: Arc<HttpClientWithUrl>,
227 telemetry: Option<Arc<Telemetry>>,
228 node_runtime: Arc<dyn NodeRuntime>,
229 language_registry: Arc<LanguageRegistry>,
230 theme_registry: Arc<ThemeRegistry>,
231 slash_command_registry: Arc<SlashCommandRegistry>,
232 indexed_docs_registry: Arc<IndexedDocsRegistry>,
233 snippet_registry: Arc<SnippetRegistry>,
234 cx: &mut ModelContext<Self>,
235 ) -> Self {
236 let work_dir = extensions_dir.join("work");
237 let build_dir = build_dir.unwrap_or_else(|| extensions_dir.join("build"));
238 let installed_dir = extensions_dir.join("installed");
239 let index_path = extensions_dir.join("index.json");
240
241 let (reload_tx, mut reload_rx) = unbounded();
242 let mut this = Self {
243 extension_index: Default::default(),
244 installed_dir,
245 index_path,
246 builder: Arc::new(ExtensionBuilder::new(
247 // Construct a real HTTP client for the extension builder, as we
248 // don't want to use a fake one in the tests.
249 ::http_client::client(None, http_client.proxy().cloned()),
250 build_dir,
251 )),
252 outstanding_operations: Default::default(),
253 modified_extensions: Default::default(),
254 reload_complete_senders: Vec::new(),
255 wasm_host: WasmHost::new(
256 fs.clone(),
257 http_client.clone(),
258 node_runtime,
259 language_registry.clone(),
260 work_dir,
261 cx,
262 ),
263 wasm_extensions: Vec::new(),
264 fs,
265 http_client,
266 telemetry,
267 language_registry,
268 theme_registry,
269 slash_command_registry,
270 indexed_docs_registry,
271 snippet_registry,
272 reload_tx,
273 tasks: Vec::new(),
274 };
275
276 // The extensions store maintains an index file, which contains a complete
277 // list of the installed extensions and the resources that they provide.
278 // This index is loaded synchronously on startup.
279 let (index_content, index_metadata, extensions_metadata) =
280 cx.background_executor().block(async {
281 futures::join!(
282 this.fs.load(&this.index_path),
283 this.fs.metadata(&this.index_path),
284 this.fs.metadata(&this.installed_dir),
285 )
286 });
287
288 // Normally, there is no need to rebuild the index. But if the index file
289 // is invalid or is out-of-date according to the filesystem mtimes, then
290 // it must be asynchronously rebuilt.
291 let mut extension_index = ExtensionIndex::default();
292 let mut extension_index_needs_rebuild = true;
293 if let Some(index_content) = index_content.ok() {
294 if let Some(index) = serde_json::from_str(&index_content).log_err() {
295 extension_index = index;
296 if let (Ok(Some(index_metadata)), Ok(Some(extensions_metadata))) =
297 (index_metadata, extensions_metadata)
298 {
299 if index_metadata.mtime > extensions_metadata.mtime {
300 extension_index_needs_rebuild = false;
301 }
302 }
303 }
304 }
305
306 // Immediately load all of the extensions in the initial manifest. If the
307 // index needs to be rebuild, then enqueue
308 let load_initial_extensions = this.extensions_updated(extension_index, cx);
309 let mut reload_future = None;
310 if extension_index_needs_rebuild {
311 reload_future = Some(this.reload(None, cx));
312 }
313
314 cx.spawn(|this, mut cx| async move {
315 if let Some(future) = reload_future {
316 future.await;
317 }
318 this.update(&mut cx, |this, cx| this.auto_install_extensions(cx))
319 .ok();
320 this.update(&mut cx, |this, cx| this.check_for_updates(cx))
321 .ok();
322 })
323 .detach();
324
325 // Perform all extension loading in a single task to ensure that we
326 // never attempt to simultaneously load/unload extensions from multiple
327 // parallel tasks.
328 this.tasks.push(cx.spawn(|this, mut cx| {
329 async move {
330 load_initial_extensions.await;
331
332 let mut debounce_timer = cx
333 .background_executor()
334 .spawn(futures::future::pending())
335 .fuse();
336 loop {
337 select_biased! {
338 _ = debounce_timer => {
339 let index = this
340 .update(&mut cx, |this, cx| this.rebuild_extension_index(cx))?
341 .await;
342 this.update(&mut cx, |this, cx| this.extensions_updated(index, cx))?
343 .await;
344 }
345 extension_id = reload_rx.next() => {
346 let Some(extension_id) = extension_id else { break; };
347 this.update(&mut cx, |this, _| {
348 this.modified_extensions.extend(extension_id);
349 })?;
350 debounce_timer = cx
351 .background_executor()
352 .timer(RELOAD_DEBOUNCE_DURATION)
353 .fuse();
354 }
355 }
356 }
357
358 anyhow::Ok(())
359 }
360 .map(drop)
361 }));
362
363 // Watch the installed extensions directory for changes. Whenever changes are
364 // detected, rebuild the extension index, and load/unload any extensions that
365 // have been added, removed, or modified.
366 this.tasks.push(cx.background_executor().spawn({
367 let fs = this.fs.clone();
368 let reload_tx = this.reload_tx.clone();
369 let installed_dir = this.installed_dir.clone();
370 async move {
371 let (mut paths, _) = fs.watch(&installed_dir, FS_WATCH_LATENCY).await;
372 while let Some(paths) = paths.next().await {
373 for path in paths {
374 let Ok(event_path) = path.strip_prefix(&installed_dir) else {
375 continue;
376 };
377
378 if let Some(path::Component::Normal(extension_dir_name)) =
379 event_path.components().next()
380 {
381 if let Some(extension_id) = extension_dir_name.to_str() {
382 reload_tx.unbounded_send(Some(extension_id.into())).ok();
383 }
384 }
385 }
386 }
387 }
388 }));
389
390 this
391 }
392
393 fn reload(
394 &mut self,
395 modified_extension: Option<Arc<str>>,
396 cx: &mut ModelContext<Self>,
397 ) -> impl Future<Output = ()> {
398 let (tx, rx) = oneshot::channel();
399 self.reload_complete_senders.push(tx);
400 self.reload_tx
401 .unbounded_send(modified_extension)
402 .expect("reload task exited");
403 cx.emit(Event::StartedReloading);
404
405 async move {
406 rx.await.ok();
407 }
408 }
409
410 fn extensions_dir(&self) -> PathBuf {
411 self.installed_dir.clone()
412 }
413
414 pub fn outstanding_operations(&self) -> &BTreeMap<Arc<str>, ExtensionOperation> {
415 &self.outstanding_operations
416 }
417
418 pub fn installed_extensions(&self) -> &BTreeMap<Arc<str>, ExtensionIndexEntry> {
419 &self.extension_index.extensions
420 }
421
422 pub fn dev_extensions(&self) -> impl Iterator<Item = &Arc<ExtensionManifest>> {
423 self.extension_index
424 .extensions
425 .values()
426 .filter_map(|extension| extension.dev.then_some(&extension.manifest))
427 }
428
429 /// Returns the names of themes provided by extensions.
430 pub fn extension_themes<'a>(
431 &'a self,
432 extension_id: &'a str,
433 ) -> impl Iterator<Item = &'a Arc<str>> {
434 self.extension_index
435 .themes
436 .iter()
437 .filter_map(|(name, theme)| theme.extension.as_ref().eq(extension_id).then_some(name))
438 }
439
440 pub fn fetch_extensions(
441 &self,
442 search: Option<&str>,
443 cx: &mut ModelContext<Self>,
444 ) -> Task<Result<Vec<ExtensionMetadata>>> {
445 let version = CURRENT_SCHEMA_VERSION.to_string();
446 let mut query = vec![("max_schema_version", version.as_str())];
447 if let Some(search) = search {
448 query.push(("filter", search));
449 }
450
451 self.fetch_extensions_from_api("/extensions", &query, cx)
452 }
453
454 pub fn fetch_extensions_with_update_available(
455 &mut self,
456 cx: &mut ModelContext<Self>,
457 ) -> Task<Result<Vec<ExtensionMetadata>>> {
458 let schema_versions = schema_version_range();
459 let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
460 let extension_settings = ExtensionSettings::get_global(cx);
461 let extension_ids = self
462 .extension_index
463 .extensions
464 .iter()
465 .filter(|(id, entry)| !entry.dev && extension_settings.should_auto_update(id))
466 .map(|(id, _)| id.as_ref())
467 .collect::<Vec<_>>()
468 .join(",");
469 let task = self.fetch_extensions_from_api(
470 "/extensions/updates",
471 &[
472 ("min_schema_version", &schema_versions.start().to_string()),
473 ("max_schema_version", &schema_versions.end().to_string()),
474 (
475 "min_wasm_api_version",
476 &wasm_api_versions.start().to_string(),
477 ),
478 ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
479 ("ids", &extension_ids),
480 ],
481 cx,
482 );
483 cx.spawn(move |this, mut cx| async move {
484 let extensions = task.await?;
485 this.update(&mut cx, |this, _cx| {
486 extensions
487 .into_iter()
488 .filter(|extension| {
489 this.extension_index.extensions.get(&extension.id).map_or(
490 true,
491 |installed_extension| {
492 installed_extension.manifest.version != extension.manifest.version
493 },
494 )
495 })
496 .collect()
497 })
498 })
499 }
500
501 pub fn fetch_extension_versions(
502 &self,
503 extension_id: &str,
504 cx: &mut ModelContext<Self>,
505 ) -> Task<Result<Vec<ExtensionMetadata>>> {
506 self.fetch_extensions_from_api(&format!("/extensions/{extension_id}"), &[], cx)
507 }
508
509 /// Installs any extensions that should be included with Zed by default.
510 ///
511 /// This can be used to make certain functionality provided by extensions
512 /// available out-of-the-box.
513 pub fn auto_install_extensions(&mut self, cx: &mut ModelContext<Self>) {
514 let extension_settings = ExtensionSettings::get_global(cx);
515
516 let extensions_to_install = extension_settings
517 .auto_install_extensions
518 .keys()
519 .filter(|extension_id| extension_settings.should_auto_install(extension_id))
520 .filter(|extension_id| {
521 let is_already_installed = self
522 .extension_index
523 .extensions
524 .contains_key(extension_id.as_ref());
525 !is_already_installed
526 })
527 .cloned()
528 .collect::<Vec<_>>();
529
530 cx.spawn(move |this, mut cx| async move {
531 for extension_id in extensions_to_install {
532 this.update(&mut cx, |this, cx| {
533 this.install_latest_extension(extension_id.clone(), cx);
534 })
535 .ok();
536 }
537 })
538 .detach();
539 }
540
541 pub fn check_for_updates(&mut self, cx: &mut ModelContext<Self>) {
542 let task = self.fetch_extensions_with_update_available(cx);
543 cx.spawn(move |this, mut cx| async move {
544 Self::upgrade_extensions(this, task.await?, &mut cx).await
545 })
546 .detach();
547 }
548
549 async fn upgrade_extensions(
550 this: WeakModel<Self>,
551 extensions: Vec<ExtensionMetadata>,
552 cx: &mut AsyncAppContext,
553 ) -> Result<()> {
554 for extension in extensions {
555 let task = this.update(cx, |this, cx| {
556 if let Some(installed_extension) =
557 this.extension_index.extensions.get(&extension.id)
558 {
559 let installed_version =
560 SemanticVersion::from_str(&installed_extension.manifest.version).ok()?;
561 let latest_version =
562 SemanticVersion::from_str(&extension.manifest.version).ok()?;
563
564 if installed_version >= latest_version {
565 return None;
566 }
567 }
568
569 Some(this.upgrade_extension(extension.id, extension.manifest.version, cx))
570 })?;
571
572 if let Some(task) = task {
573 task.await.log_err();
574 }
575 }
576 anyhow::Ok(())
577 }
578
579 fn fetch_extensions_from_api(
580 &self,
581 path: &str,
582 query: &[(&str, &str)],
583 cx: &mut ModelContext<'_, ExtensionStore>,
584 ) -> Task<Result<Vec<ExtensionMetadata>>> {
585 let url = self.http_client.build_zed_api_url(path, &query);
586 let http_client = self.http_client.clone();
587 cx.spawn(move |_, _| async move {
588 let mut response = http_client
589 .get(&url?.as_ref(), AsyncBody::empty(), true)
590 .await?;
591
592 let mut body = Vec::new();
593 response
594 .body_mut()
595 .read_to_end(&mut body)
596 .await
597 .context("error reading extensions")?;
598
599 if response.status().is_client_error() {
600 let text = String::from_utf8_lossy(body.as_slice());
601 bail!(
602 "status error {}, response: {text:?}",
603 response.status().as_u16()
604 );
605 }
606
607 let response: GetExtensionsResponse = serde_json::from_slice(&body)?;
608 Ok(response.data)
609 })
610 }
611
612 pub fn install_extension(
613 &mut self,
614 extension_id: Arc<str>,
615 version: Arc<str>,
616 cx: &mut ModelContext<Self>,
617 ) {
618 self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Install, cx)
619 .detach_and_log_err(cx);
620 }
621
622 fn install_or_upgrade_extension_at_endpoint(
623 &mut self,
624 extension_id: Arc<str>,
625 url: Url,
626 operation: ExtensionOperation,
627 cx: &mut ModelContext<Self>,
628 ) -> Task<Result<()>> {
629 let extension_dir = self.installed_dir.join(extension_id.as_ref());
630 let http_client = self.http_client.clone();
631 let fs = self.fs.clone();
632
633 match self.outstanding_operations.entry(extension_id.clone()) {
634 btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
635 btree_map::Entry::Vacant(e) => e.insert(operation),
636 };
637 cx.notify();
638
639 cx.spawn(move |this, mut cx| async move {
640 let _finish = util::defer({
641 let this = this.clone();
642 let mut cx = cx.clone();
643 let extension_id = extension_id.clone();
644 move || {
645 this.update(&mut cx, |this, cx| {
646 this.outstanding_operations.remove(extension_id.as_ref());
647 cx.notify();
648 })
649 .ok();
650 }
651 });
652
653 let mut response = http_client
654 .get(&url.as_ref(), Default::default(), true)
655 .await
656 .map_err(|err| anyhow!("error downloading extension: {}", err))?;
657
658 fs.remove_dir(
659 &extension_dir,
660 RemoveOptions {
661 recursive: true,
662 ignore_if_not_exists: true,
663 },
664 )
665 .await?;
666
667 let content_length = response
668 .headers()
669 .get(isahc::http::header::CONTENT_LENGTH)
670 .and_then(|value| value.to_str().ok()?.parse::<usize>().ok());
671
672 let mut body = BufReader::new(response.body_mut());
673 let mut tar_gz_bytes = Vec::new();
674 body.read_to_end(&mut tar_gz_bytes).await?;
675
676 if let Some(content_length) = content_length {
677 let actual_len = tar_gz_bytes.len();
678 if content_length != actual_len {
679 bail!("downloaded extension size {actual_len} does not match content length {content_length}");
680 }
681 }
682 let decompressed_bytes = GzipDecoder::new(BufReader::new(tar_gz_bytes.as_slice()));
683 let archive = Archive::new(decompressed_bytes);
684 archive.unpack(extension_dir).await?;
685 this.update(&mut cx, |this, cx| {
686 this.reload(Some(extension_id.clone()), cx)
687 })?
688 .await;
689
690 match operation {
691 ExtensionOperation::Install => {
692 this.update(&mut cx, |_, cx| {
693 cx.emit(Event::ExtensionInstalled(extension_id));
694 })
695 .ok();
696 }
697 _ => {}
698 }
699
700 anyhow::Ok(())
701 })
702 }
703
704 pub fn install_latest_extension(
705 &mut self,
706 extension_id: Arc<str>,
707 cx: &mut ModelContext<Self>,
708 ) {
709 log::info!("installing extension {extension_id} latest version");
710
711 let schema_versions = schema_version_range();
712 let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
713
714 let Some(url) = self
715 .http_client
716 .build_zed_api_url(
717 &format!("/extensions/{extension_id}/download"),
718 &[
719 ("min_schema_version", &schema_versions.start().to_string()),
720 ("max_schema_version", &schema_versions.end().to_string()),
721 (
722 "min_wasm_api_version",
723 &wasm_api_versions.start().to_string(),
724 ),
725 ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
726 ],
727 )
728 .log_err()
729 else {
730 return;
731 };
732
733 self.install_or_upgrade_extension_at_endpoint(
734 extension_id,
735 url,
736 ExtensionOperation::Install,
737 cx,
738 )
739 .detach_and_log_err(cx);
740 }
741
742 pub fn upgrade_extension(
743 &mut self,
744 extension_id: Arc<str>,
745 version: Arc<str>,
746 cx: &mut ModelContext<Self>,
747 ) -> Task<Result<()>> {
748 self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Upgrade, cx)
749 }
750
751 fn install_or_upgrade_extension(
752 &mut self,
753 extension_id: Arc<str>,
754 version: Arc<str>,
755 operation: ExtensionOperation,
756 cx: &mut ModelContext<Self>,
757 ) -> Task<Result<()>> {
758 log::info!("installing extension {extension_id} {version}");
759 let Some(url) = self
760 .http_client
761 .build_zed_api_url(
762 &format!("/extensions/{extension_id}/{version}/download"),
763 &[],
764 )
765 .log_err()
766 else {
767 return Task::ready(Ok(()));
768 };
769
770 self.install_or_upgrade_extension_at_endpoint(extension_id, url, operation, cx)
771 }
772
773 pub fn uninstall_extension(&mut self, extension_id: Arc<str>, cx: &mut ModelContext<Self>) {
774 let extension_dir = self.installed_dir.join(extension_id.as_ref());
775 let work_dir = self.wasm_host.work_dir.join(extension_id.as_ref());
776 let fs = self.fs.clone();
777
778 match self.outstanding_operations.entry(extension_id.clone()) {
779 btree_map::Entry::Occupied(_) => return,
780 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
781 };
782
783 cx.spawn(move |this, mut cx| async move {
784 let _finish = util::defer({
785 let this = this.clone();
786 let mut cx = cx.clone();
787 let extension_id = extension_id.clone();
788 move || {
789 this.update(&mut cx, |this, cx| {
790 this.outstanding_operations.remove(extension_id.as_ref());
791 cx.notify();
792 })
793 .ok();
794 }
795 });
796
797 fs.remove_dir(
798 &work_dir,
799 RemoveOptions {
800 recursive: true,
801 ignore_if_not_exists: true,
802 },
803 )
804 .await?;
805
806 fs.remove_dir(
807 &extension_dir,
808 RemoveOptions {
809 recursive: true,
810 ignore_if_not_exists: true,
811 },
812 )
813 .await?;
814
815 this.update(&mut cx, |this, cx| this.reload(None, cx))?
816 .await;
817 anyhow::Ok(())
818 })
819 .detach_and_log_err(cx)
820 }
821
822 pub fn install_dev_extension(
823 &mut self,
824 extension_source_path: PathBuf,
825 cx: &mut ModelContext<Self>,
826 ) -> Task<Result<()>> {
827 let extensions_dir = self.extensions_dir();
828 let fs = self.fs.clone();
829 let builder = self.builder.clone();
830
831 cx.spawn(move |this, mut cx| async move {
832 let mut extension_manifest =
833 ExtensionManifest::load(fs.clone(), &extension_source_path).await?;
834 let extension_id = extension_manifest.id.clone();
835
836 if !this.update(&mut cx, |this, cx| {
837 match this.outstanding_operations.entry(extension_id.clone()) {
838 btree_map::Entry::Occupied(_) => return false,
839 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
840 };
841 cx.notify();
842 true
843 })? {
844 return Ok(());
845 }
846
847 let _finish = util::defer({
848 let this = this.clone();
849 let mut cx = cx.clone();
850 let extension_id = extension_id.clone();
851 move || {
852 this.update(&mut cx, |this, cx| {
853 this.outstanding_operations.remove(extension_id.as_ref());
854 cx.notify();
855 })
856 .ok();
857 }
858 });
859
860 cx.background_executor()
861 .spawn({
862 let extension_source_path = extension_source_path.clone();
863 async move {
864 builder
865 .compile_extension(
866 &extension_source_path,
867 &mut extension_manifest,
868 CompileExtensionOptions { release: false },
869 )
870 .await
871 }
872 })
873 .await?;
874
875 let output_path = &extensions_dir.join(extension_id.as_ref());
876 if let Some(metadata) = fs.metadata(&output_path).await? {
877 if metadata.is_symlink {
878 fs.remove_file(
879 &output_path,
880 RemoveOptions {
881 recursive: false,
882 ignore_if_not_exists: true,
883 },
884 )
885 .await?;
886 } else {
887 bail!("extension {extension_id} is already installed");
888 }
889 }
890
891 fs.create_symlink(output_path, extension_source_path)
892 .await?;
893
894 this.update(&mut cx, |this, cx| this.reload(None, cx))?
895 .await;
896 Ok(())
897 })
898 }
899
900 pub fn rebuild_dev_extension(&mut self, extension_id: Arc<str>, cx: &mut ModelContext<Self>) {
901 let path = self.installed_dir.join(extension_id.as_ref());
902 let builder = self.builder.clone();
903 let fs = self.fs.clone();
904
905 match self.outstanding_operations.entry(extension_id.clone()) {
906 btree_map::Entry::Occupied(_) => return,
907 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Upgrade),
908 };
909
910 cx.notify();
911 let compile = cx.background_executor().spawn(async move {
912 let mut manifest = ExtensionManifest::load(fs, &path).await?;
913 builder
914 .compile_extension(
915 &path,
916 &mut manifest,
917 CompileExtensionOptions { release: true },
918 )
919 .await
920 });
921
922 cx.spawn(|this, mut cx| async move {
923 let result = compile.await;
924
925 this.update(&mut cx, |this, cx| {
926 this.outstanding_operations.remove(&extension_id);
927 cx.notify();
928 })?;
929
930 if result.is_ok() {
931 this.update(&mut cx, |this, cx| this.reload(Some(extension_id), cx))?
932 .await;
933 }
934
935 result
936 })
937 .detach_and_log_err(cx)
938 }
939
940 /// Updates the set of installed extensions.
941 ///
942 /// First, this unloads any themes, languages, or grammars that are
943 /// no longer in the manifest, or whose files have changed on disk.
944 /// Then it loads any themes, languages, or grammars that are newly
945 /// added to the manifest, or whose files have changed on disk.
946 fn extensions_updated(
947 &mut self,
948 new_index: ExtensionIndex,
949 cx: &mut ModelContext<Self>,
950 ) -> Task<()> {
951 let old_index = &self.extension_index;
952
953 // Determine which extensions need to be loaded and unloaded, based
954 // on the changes to the manifest and the extensions that we know have been
955 // modified.
956 let mut extensions_to_unload = Vec::default();
957 let mut extensions_to_load = Vec::default();
958 {
959 let mut old_keys = old_index.extensions.iter().peekable();
960 let mut new_keys = new_index.extensions.iter().peekable();
961 loop {
962 match (old_keys.peek(), new_keys.peek()) {
963 (None, None) => break,
964 (None, Some(_)) => {
965 extensions_to_load.push(new_keys.next().unwrap().0.clone());
966 }
967 (Some(_), None) => {
968 extensions_to_unload.push(old_keys.next().unwrap().0.clone());
969 }
970 (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(&new_key) {
971 Ordering::Equal => {
972 let (old_key, old_value) = old_keys.next().unwrap();
973 let (new_key, new_value) = new_keys.next().unwrap();
974 if old_value != new_value || self.modified_extensions.contains(old_key)
975 {
976 extensions_to_unload.push(old_key.clone());
977 extensions_to_load.push(new_key.clone());
978 }
979 }
980 Ordering::Less => {
981 extensions_to_unload.push(old_keys.next().unwrap().0.clone());
982 }
983 Ordering::Greater => {
984 extensions_to_load.push(new_keys.next().unwrap().0.clone());
985 }
986 },
987 }
988 }
989 self.modified_extensions.clear();
990 }
991
992 if extensions_to_load.is_empty() && extensions_to_unload.is_empty() {
993 return Task::ready(());
994 }
995
996 let reload_count = extensions_to_unload
997 .iter()
998 .filter(|id| extensions_to_load.contains(id))
999 .count();
1000
1001 log::info!(
1002 "extensions updated. loading {}, reloading {}, unloading {}",
1003 extensions_to_load.len() - reload_count,
1004 reload_count,
1005 extensions_to_unload.len() - reload_count
1006 );
1007
1008 if let Some(telemetry) = &self.telemetry {
1009 for extension_id in &extensions_to_load {
1010 if let Some(extension) = new_index.extensions.get(extension_id) {
1011 telemetry.report_extension_event(
1012 extension_id.clone(),
1013 extension.manifest.version.clone(),
1014 );
1015 }
1016 }
1017 }
1018
1019 let themes_to_remove = old_index
1020 .themes
1021 .iter()
1022 .filter_map(|(name, entry)| {
1023 if extensions_to_unload.contains(&entry.extension) {
1024 Some(name.clone().into())
1025 } else {
1026 None
1027 }
1028 })
1029 .collect::<Vec<_>>();
1030 let languages_to_remove = old_index
1031 .languages
1032 .iter()
1033 .filter_map(|(name, entry)| {
1034 if extensions_to_unload.contains(&entry.extension) {
1035 Some(name.clone())
1036 } else {
1037 None
1038 }
1039 })
1040 .collect::<Vec<_>>();
1041 let mut grammars_to_remove = Vec::new();
1042 for extension_id in &extensions_to_unload {
1043 let Some(extension) = old_index.extensions.get(extension_id) else {
1044 continue;
1045 };
1046 grammars_to_remove.extend(extension.manifest.grammars.keys().cloned());
1047 for (language_server_name, config) in extension.manifest.language_servers.iter() {
1048 for language in config.languages() {
1049 self.language_registry
1050 .remove_lsp_adapter(&language, language_server_name);
1051 }
1052 }
1053 }
1054
1055 self.wasm_extensions
1056 .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
1057 self.theme_registry.remove_user_themes(&themes_to_remove);
1058 self.language_registry
1059 .remove_languages(&languages_to_remove, &grammars_to_remove);
1060
1061 let languages_to_add = new_index
1062 .languages
1063 .iter()
1064 .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
1065 .collect::<Vec<_>>();
1066 let mut grammars_to_add = Vec::new();
1067 let mut themes_to_add = Vec::new();
1068 let mut snippets_to_add = Vec::new();
1069 for extension_id in &extensions_to_load {
1070 let Some(extension) = new_index.extensions.get(extension_id) else {
1071 continue;
1072 };
1073
1074 grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
1075 let mut grammar_path = self.installed_dir.clone();
1076 grammar_path.extend([extension_id.as_ref(), "grammars"]);
1077 grammar_path.push(grammar_name.as_ref());
1078 grammar_path.set_extension("wasm");
1079 (grammar_name.clone(), grammar_path)
1080 }));
1081 themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
1082 let mut path = self.installed_dir.clone();
1083 path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1084 path
1085 }));
1086 snippets_to_add.extend(extension.manifest.snippets.iter().map(|snippets_path| {
1087 let mut path = self.installed_dir.clone();
1088 path.extend([Path::new(extension_id.as_ref()), snippets_path.as_path()]);
1089 path
1090 }));
1091 }
1092
1093 self.language_registry
1094 .register_wasm_grammars(grammars_to_add);
1095
1096 for (language_name, language) in languages_to_add {
1097 let mut language_path = self.installed_dir.clone();
1098 language_path.extend([
1099 Path::new(language.extension.as_ref()),
1100 language.path.as_path(),
1101 ]);
1102 self.language_registry.register_language(
1103 language_name.clone(),
1104 language.grammar.clone(),
1105 language.matcher.clone(),
1106 move || {
1107 let config = std::fs::read_to_string(language_path.join("config.toml"))?;
1108 let config: LanguageConfig = ::toml::from_str(&config)?;
1109 let queries = load_plugin_queries(&language_path);
1110 let tasks = std::fs::read_to_string(language_path.join("tasks.json"))
1111 .ok()
1112 .and_then(|contents| {
1113 let definitions = serde_json_lenient::from_str(&contents).log_err()?;
1114 Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1115 });
1116
1117 Ok((config, queries, tasks))
1118 },
1119 );
1120 }
1121
1122 let fs = self.fs.clone();
1123 let wasm_host = self.wasm_host.clone();
1124 let root_dir = self.installed_dir.clone();
1125 let theme_registry = self.theme_registry.clone();
1126 let snippet_registry = self.snippet_registry.clone();
1127 let extension_entries = extensions_to_load
1128 .iter()
1129 .filter_map(|name| new_index.extensions.get(name).cloned())
1130 .collect::<Vec<_>>();
1131
1132 self.extension_index = new_index;
1133 cx.notify();
1134 cx.emit(Event::ExtensionsUpdated);
1135
1136 cx.spawn(|this, mut cx| async move {
1137 cx.background_executor()
1138 .spawn({
1139 let fs = fs.clone();
1140 async move {
1141 for theme_path in &themes_to_add {
1142 theme_registry
1143 .load_user_theme(&theme_path, fs.clone())
1144 .await
1145 .log_err();
1146 }
1147
1148 for snippets_path in &snippets_to_add {
1149 if let Some(snippets_contents) = fs.load(snippets_path).await.log_err()
1150 {
1151 snippet_registry
1152 .register_snippets(snippets_path, &snippets_contents)
1153 .log_err();
1154 }
1155 }
1156 }
1157 })
1158 .await;
1159
1160 let mut wasm_extensions = Vec::new();
1161 for extension in extension_entries {
1162 if extension.manifest.lib.kind.is_none() {
1163 continue;
1164 };
1165
1166 let wasm_extension = maybe!(async {
1167 let mut path = root_dir.clone();
1168 path.extend([extension.manifest.clone().id.as_ref(), "extension.wasm"]);
1169 let mut wasm_file = fs
1170 .open_sync(&path)
1171 .await
1172 .context("failed to open wasm file")?;
1173
1174 let mut wasm_bytes = Vec::new();
1175 wasm_file
1176 .read_to_end(&mut wasm_bytes)
1177 .context("failed to read wasm")?;
1178
1179 wasm_host
1180 .load_extension(
1181 wasm_bytes,
1182 extension.manifest.clone().clone(),
1183 cx.background_executor().clone(),
1184 )
1185 .await
1186 .with_context(|| {
1187 format!("failed to load wasm extension {}", extension.manifest.id)
1188 })
1189 })
1190 .await;
1191
1192 if let Some(wasm_extension) = wasm_extension.log_err() {
1193 wasm_extensions.push((extension.manifest.clone(), wasm_extension));
1194 } else {
1195 this.update(&mut cx, |_, cx| {
1196 cx.emit(Event::ExtensionFailedToLoad(extension.manifest.id.clone()))
1197 })
1198 .ok();
1199 }
1200 }
1201
1202 this.update(&mut cx, |this, cx| {
1203 this.reload_complete_senders.clear();
1204
1205 for (manifest, wasm_extension) in &wasm_extensions {
1206 for (language_server_id, language_server_config) in &manifest.language_servers {
1207 for language in language_server_config.languages() {
1208 this.language_registry.register_lsp_adapter(
1209 language.clone(),
1210 Arc::new(ExtensionLspAdapter {
1211 extension: wasm_extension.clone(),
1212 host: this.wasm_host.clone(),
1213 language_server_id: language_server_id.clone(),
1214 config: wit::LanguageServerConfig {
1215 name: language_server_id.0.to_string(),
1216 language_name: language.to_string(),
1217 },
1218 }),
1219 );
1220 }
1221 }
1222
1223 for (slash_command_name, slash_command) in &manifest.slash_commands {
1224 this.slash_command_registry.register_command(
1225 ExtensionSlashCommand {
1226 command: crate::wit::SlashCommand {
1227 name: slash_command_name.to_string(),
1228 description: slash_command.description.to_string(),
1229 // We don't currently expose this as a configurable option, as it currently drives
1230 // the `menu_text` on the `SlashCommand` trait, which is not used for slash commands
1231 // defined in extensions, as they are not able to be added to the menu.
1232 tooltip_text: String::new(),
1233 requires_argument: slash_command.requires_argument,
1234 },
1235 extension: wasm_extension.clone(),
1236 host: this.wasm_host.clone(),
1237 },
1238 false,
1239 );
1240 }
1241
1242 for (provider_id, _provider) in &manifest.indexed_docs_providers {
1243 this.indexed_docs_registry.register_provider(Box::new(
1244 ExtensionIndexedDocsProvider {
1245 extension: wasm_extension.clone(),
1246 host: this.wasm_host.clone(),
1247 id: ProviderId(provider_id.clone()),
1248 },
1249 ));
1250 }
1251 }
1252
1253 this.wasm_extensions.extend(wasm_extensions);
1254 ThemeSettings::reload_current_theme(cx)
1255 })
1256 .ok();
1257 })
1258 }
1259
1260 fn rebuild_extension_index(&self, cx: &mut ModelContext<Self>) -> Task<ExtensionIndex> {
1261 let fs = self.fs.clone();
1262 let work_dir = self.wasm_host.work_dir.clone();
1263 let extensions_dir = self.installed_dir.clone();
1264 let index_path = self.index_path.clone();
1265 cx.background_executor().spawn(async move {
1266 let start_time = Instant::now();
1267 let mut index = ExtensionIndex::default();
1268
1269 fs.create_dir(&work_dir).await.log_err();
1270 fs.create_dir(&extensions_dir).await.log_err();
1271
1272 let extension_paths = fs.read_dir(&extensions_dir).await;
1273 if let Ok(mut extension_paths) = extension_paths {
1274 while let Some(extension_dir) = extension_paths.next().await {
1275 let Ok(extension_dir) = extension_dir else {
1276 continue;
1277 };
1278
1279 if extension_dir
1280 .file_name()
1281 .map_or(false, |file_name| file_name == ".DS_Store")
1282 {
1283 continue;
1284 }
1285
1286 Self::add_extension_to_index(fs.clone(), extension_dir, &mut index)
1287 .await
1288 .log_err();
1289 }
1290 }
1291
1292 if let Ok(index_json) = serde_json::to_string_pretty(&index) {
1293 fs.save(&index_path, &index_json.as_str().into(), Default::default())
1294 .await
1295 .context("failed to save extension index")
1296 .log_err();
1297 }
1298
1299 log::info!("rebuilt extension index in {:?}", start_time.elapsed());
1300 index
1301 })
1302 }
1303
1304 async fn add_extension_to_index(
1305 fs: Arc<dyn Fs>,
1306 extension_dir: PathBuf,
1307 index: &mut ExtensionIndex,
1308 ) -> Result<()> {
1309 let mut extension_manifest = ExtensionManifest::load(fs.clone(), &extension_dir).await?;
1310 let extension_id = extension_manifest.id.clone();
1311
1312 // TODO: distinguish dev extensions more explicitly, by the absence
1313 // of a checksum file that we'll create when downloading normal extensions.
1314 let is_dev = fs
1315 .metadata(&extension_dir)
1316 .await?
1317 .ok_or_else(|| anyhow!("directory does not exist"))?
1318 .is_symlink;
1319
1320 if let Ok(mut language_paths) = fs.read_dir(&extension_dir.join("languages")).await {
1321 while let Some(language_path) = language_paths.next().await {
1322 let language_path = language_path?;
1323 let Ok(relative_path) = language_path.strip_prefix(&extension_dir) else {
1324 continue;
1325 };
1326 let Ok(Some(fs_metadata)) = fs.metadata(&language_path).await else {
1327 continue;
1328 };
1329 if !fs_metadata.is_dir {
1330 continue;
1331 }
1332 let config = fs.load(&language_path.join("config.toml")).await?;
1333 let config = ::toml::from_str::<LanguageConfig>(&config)?;
1334
1335 let relative_path = relative_path.to_path_buf();
1336 if !extension_manifest.languages.contains(&relative_path) {
1337 extension_manifest.languages.push(relative_path.clone());
1338 }
1339
1340 index.languages.insert(
1341 config.name.clone(),
1342 ExtensionIndexLanguageEntry {
1343 extension: extension_id.clone(),
1344 path: relative_path,
1345 matcher: config.matcher,
1346 grammar: config.grammar,
1347 },
1348 );
1349 }
1350 }
1351
1352 if let Ok(mut theme_paths) = fs.read_dir(&extension_dir.join("themes")).await {
1353 while let Some(theme_path) = theme_paths.next().await {
1354 let theme_path = theme_path?;
1355 let Ok(relative_path) = theme_path.strip_prefix(&extension_dir) else {
1356 continue;
1357 };
1358
1359 let Some(theme_family) = ThemeRegistry::read_user_theme(&theme_path, fs.clone())
1360 .await
1361 .log_err()
1362 else {
1363 continue;
1364 };
1365
1366 let relative_path = relative_path.to_path_buf();
1367 if !extension_manifest.themes.contains(&relative_path) {
1368 extension_manifest.themes.push(relative_path.clone());
1369 }
1370
1371 for theme in theme_family.themes {
1372 index.themes.insert(
1373 theme.name.into(),
1374 ExtensionIndexThemeEntry {
1375 extension: extension_id.clone(),
1376 path: relative_path.clone(),
1377 },
1378 );
1379 }
1380 }
1381 }
1382
1383 let extension_wasm_path = extension_dir.join("extension.wasm");
1384 if fs.is_file(&extension_wasm_path).await {
1385 extension_manifest
1386 .lib
1387 .kind
1388 .get_or_insert(ExtensionLibraryKind::Rust);
1389 }
1390
1391 index.extensions.insert(
1392 extension_id.clone(),
1393 ExtensionIndexEntry {
1394 dev: is_dev,
1395 manifest: Arc::new(extension_manifest),
1396 },
1397 );
1398
1399 Ok(())
1400 }
1401}
1402
1403fn load_plugin_queries(root_path: &Path) -> LanguageQueries {
1404 let mut result = LanguageQueries::default();
1405 if let Some(entries) = std::fs::read_dir(root_path).log_err() {
1406 for entry in entries {
1407 let Some(entry) = entry.log_err() else {
1408 continue;
1409 };
1410 let path = entry.path();
1411 if let Some(remainder) = path.strip_prefix(root_path).ok().and_then(|p| p.to_str()) {
1412 if !remainder.ends_with(".scm") {
1413 continue;
1414 }
1415 for (name, query) in QUERY_FILENAME_PREFIXES {
1416 if remainder.starts_with(name) {
1417 if let Some(contents) = std::fs::read_to_string(&path).log_err() {
1418 match query(&mut result) {
1419 None => *query(&mut result) = Some(contents.into()),
1420 Some(r) => r.to_mut().push_str(contents.as_ref()),
1421 }
1422 }
1423 break;
1424 }
1425 }
1426 }
1427 }
1428 }
1429 result
1430}