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