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