1mod capability_granter;
2pub mod extension_settings;
3pub mod headless_host;
4pub mod wasm_host;
5
6#[cfg(test)]
7mod extension_store_test;
8
9use anyhow::{Context as _, Result, anyhow, bail};
10use async_compression::futures::bufread::GzipDecoder;
11use async_tar::Archive;
12use client::{Client, proto, telemetry::Telemetry};
13use cloud_api_types::{ExtensionMetadata, ExtensionProvides, GetExtensionsResponse};
14use collections::{BTreeMap, BTreeSet, HashSet, btree_map};
15pub use extension::ExtensionManifest;
16use extension::extension_builder::{CompileExtensionOptions, ExtensionBuilder};
17use extension::{
18 ExtensionContextServerProxy, ExtensionDebugAdapterProviderProxy, ExtensionEvents,
19 ExtensionGrammarProxy, ExtensionHostProxy, ExtensionLanguageProxy,
20 ExtensionLanguageServerProxy, ExtensionSlashCommandProxy, ExtensionSnippetProxy,
21 ExtensionThemeProxy,
22};
23use fs::{Fs, RemoveOptions};
24use futures::future::join_all;
25use futures::{
26 AsyncReadExt as _, Future, FutureExt as _, StreamExt as _,
27 channel::{
28 mpsc::{UnboundedSender, unbounded},
29 oneshot,
30 },
31 io::BufReader,
32 select_biased,
33};
34use gpui::{
35 App, AppContext as _, AsyncApp, Context, Entity, EventEmitter, Global, Task, UpdateGlobal as _,
36 WeakEntity, actions,
37};
38use http_client::{AsyncBody, HttpClient, HttpClientWithUrl};
39use language::{
40 LanguageConfig, LanguageMatcher, LanguageName, LanguageQueries, LoadedLanguage,
41 QUERY_FILENAME_PREFIXES, Rope,
42};
43use node_runtime::NodeRuntime;
44use project::ContextProviderWithTasks;
45use release_channel::ReleaseChannel;
46use remote::RemoteClient;
47use semver::Version;
48use serde::{Deserialize, Serialize};
49use settings::{SemanticTokenRules, Settings, SettingsStore};
50use std::ops::RangeInclusive;
51use std::str::FromStr;
52use std::{
53 cmp::Ordering,
54 path::{self, Path, PathBuf},
55 sync::Arc,
56 time::{Duration, Instant},
57};
58use task::TaskTemplates;
59use url::Url;
60use util::{ResultExt, paths::RemotePathBuf};
61use wasm_host::{
62 WasmExtension, WasmHost,
63 wit::{is_supported_wasm_api_version, wasm_api_version_range},
64};
65
66pub use extension::{
67 ExtensionLibraryKind, GrammarManifestEntry, OldExtensionManifest, SchemaVersion,
68};
69pub use extension_settings::ExtensionSettings;
70
71pub const RELOAD_DEBOUNCE_DURATION: Duration = Duration::from_millis(200);
72const FS_WATCH_LATENCY: Duration = Duration::from_millis(100);
73
74/// The current extension [`SchemaVersion`] supported by Zed.
75const CURRENT_SCHEMA_VERSION: SchemaVersion = SchemaVersion(1);
76
77/// Extensions that should no longer be loaded or downloaded.
78///
79/// These snippets should no longer be downloaded or loaded, because their
80/// functionality has been integrated into the core editor.
81const SUPPRESSED_EXTENSIONS: &[&str] = &["snippets", "ruff", "ty", "basedpyright"];
82
83/// Returns the [`SchemaVersion`] range that is compatible with this version of Zed.
84pub fn schema_version_range() -> RangeInclusive<SchemaVersion> {
85 SchemaVersion::ZERO..=CURRENT_SCHEMA_VERSION
86}
87
88/// Returns whether the given extension version is compatible with this version of Zed.
89pub fn is_version_compatible(
90 release_channel: ReleaseChannel,
91 extension_version: &ExtensionMetadata,
92) -> bool {
93 let schema_version = extension_version.manifest.schema_version.unwrap_or(0);
94 if CURRENT_SCHEMA_VERSION.0 < schema_version {
95 return false;
96 }
97
98 if let Some(wasm_api_version) = extension_version
99 .manifest
100 .wasm_api_version
101 .as_ref()
102 .and_then(|wasm_api_version| Version::from_str(wasm_api_version).ok())
103 && !is_supported_wasm_api_version(release_channel, wasm_api_version)
104 {
105 return false;
106 }
107
108 true
109}
110
111pub struct ExtensionStore {
112 pub proxy: Arc<ExtensionHostProxy>,
113 pub builder: Arc<ExtensionBuilder>,
114 pub extension_index: ExtensionIndex,
115 pub fs: Arc<dyn Fs>,
116 pub http_client: Arc<HttpClientWithUrl>,
117 pub telemetry: Option<Arc<Telemetry>>,
118 pub reload_tx: UnboundedSender<Option<Arc<str>>>,
119 pub reload_complete_senders: Vec<oneshot::Sender<()>>,
120 pub installed_dir: PathBuf,
121 pub outstanding_operations: BTreeMap<Arc<str>, ExtensionOperation>,
122 pub index_path: PathBuf,
123 pub modified_extensions: HashSet<Arc<str>>,
124 pub wasm_host: Arc<WasmHost>,
125 pub wasm_extensions: Vec<(Arc<ExtensionManifest>, WasmExtension)>,
126 pub tasks: Vec<Task<()>>,
127 pub remote_clients: Vec<WeakEntity<RemoteClient>>,
128 pub ssh_registered_tx: UnboundedSender<()>,
129}
130
131#[derive(Clone, Copy)]
132pub enum ExtensionOperation {
133 Upgrade,
134 Install,
135 Remove,
136}
137
138#[derive(Clone)]
139pub enum Event {
140 ExtensionsUpdated,
141 StartedReloading,
142 ExtensionInstalled(Arc<str>),
143 ExtensionUninstalled(Arc<str>),
144 ExtensionFailedToLoad(Arc<str>),
145}
146
147impl EventEmitter<Event> for ExtensionStore {}
148
149struct GlobalExtensionStore(Entity<ExtensionStore>);
150
151impl Global for GlobalExtensionStore {}
152
153#[derive(Debug, Deserialize, Serialize, Default, PartialEq, Eq)]
154pub struct ExtensionIndex {
155 pub extensions: BTreeMap<Arc<str>, ExtensionIndexEntry>,
156 pub themes: BTreeMap<Arc<str>, ExtensionIndexThemeEntry>,
157 #[serde(default)]
158 pub icon_themes: BTreeMap<Arc<str>, ExtensionIndexIconThemeEntry>,
159 pub languages: BTreeMap<LanguageName, ExtensionIndexLanguageEntry>,
160}
161
162#[derive(Clone, PartialEq, Eq, Debug, Deserialize, Serialize)]
163pub struct ExtensionIndexEntry {
164 pub manifest: Arc<ExtensionManifest>,
165 pub dev: bool,
166}
167
168#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
169pub struct ExtensionIndexThemeEntry {
170 pub extension: Arc<str>,
171 pub path: PathBuf,
172}
173
174#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
175pub struct ExtensionIndexIconThemeEntry {
176 pub extension: Arc<str>,
177 pub path: PathBuf,
178}
179
180#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Deserialize, Serialize)]
181pub struct ExtensionIndexLanguageEntry {
182 pub extension: Arc<str>,
183 pub path: PathBuf,
184 pub matcher: LanguageMatcher,
185 pub hidden: bool,
186 pub grammar: Option<Arc<str>>,
187}
188
189actions!(
190 zed,
191 [
192 /// Reloads all installed extensions.
193 ReloadExtensions
194 ]
195);
196
197pub fn init(
198 extension_host_proxy: Arc<ExtensionHostProxy>,
199 fs: Arc<dyn Fs>,
200 client: Arc<Client>,
201 node_runtime: NodeRuntime,
202 cx: &mut App,
203) {
204 let store = cx.new(move |cx| {
205 ExtensionStore::new(
206 paths::extensions_dir().clone(),
207 None,
208 extension_host_proxy,
209 fs,
210 client.http_client(),
211 client.http_client(),
212 Some(client.telemetry().clone()),
213 node_runtime,
214 cx,
215 )
216 });
217
218 cx.on_action(|_: &ReloadExtensions, cx| {
219 let store = cx.global::<GlobalExtensionStore>().0.clone();
220 store.update(cx, |store, cx| drop(store.reload(None, cx)));
221 });
222
223 cx.set_global(GlobalExtensionStore(store));
224}
225
226impl ExtensionStore {
227 pub fn try_global(cx: &App) -> Option<Entity<Self>> {
228 cx.try_global::<GlobalExtensionStore>()
229 .map(|store| store.0.clone())
230 }
231
232 pub fn global(cx: &App) -> Entity<Self> {
233 cx.global::<GlobalExtensionStore>().0.clone()
234 }
235
236 pub fn new(
237 extensions_dir: PathBuf,
238 build_dir: Option<PathBuf>,
239 extension_host_proxy: Arc<ExtensionHostProxy>,
240 fs: Arc<dyn Fs>,
241 http_client: Arc<HttpClientWithUrl>,
242 builder_client: Arc<dyn HttpClient>,
243 telemetry: Option<Arc<Telemetry>>,
244 node_runtime: NodeRuntime,
245 cx: &mut Context<Self>,
246 ) -> Self {
247 let work_dir = extensions_dir.join("work");
248 let build_dir = build_dir.unwrap_or_else(|| extensions_dir.join("build"));
249 let installed_dir = extensions_dir.join("installed");
250 let index_path = extensions_dir.join("index.json");
251
252 let (reload_tx, mut reload_rx) = unbounded();
253 let (connection_registered_tx, mut connection_registered_rx) = unbounded();
254 let mut this = Self {
255 proxy: extension_host_proxy.clone(),
256 extension_index: Default::default(),
257 installed_dir,
258 index_path,
259 builder: Arc::new(ExtensionBuilder::new(builder_client, build_dir)),
260 outstanding_operations: Default::default(),
261 modified_extensions: Default::default(),
262 reload_complete_senders: Vec::new(),
263 wasm_host: WasmHost::new(
264 fs.clone(),
265 http_client.clone(),
266 node_runtime,
267 extension_host_proxy,
268 work_dir,
269 cx,
270 ),
271 wasm_extensions: Vec::new(),
272 fs,
273 http_client,
274 telemetry,
275 reload_tx,
276 tasks: Vec::new(),
277
278 remote_clients: Default::default(),
279 ssh_registered_tx: connection_registered_tx,
280 };
281
282 // The extensions store maintains an index file, which contains a complete
283 // list of the installed extensions and the resources that they provide.
284 // This index is loaded synchronously on startup.
285 let (index_content, index_metadata, extensions_metadata) =
286 cx.foreground_executor().block_on(async {
287 futures::join!(
288 this.fs.load(&this.index_path),
289 this.fs.metadata(&this.index_path),
290 this.fs.metadata(&this.installed_dir),
291 )
292 });
293
294 // Normally, there is no need to rebuild the index. But if the index file
295 // is invalid or is out-of-date according to the filesystem mtimes, then
296 // it must be asynchronously rebuilt.
297 let mut extension_index = ExtensionIndex::default();
298 let mut extension_index_needs_rebuild = true;
299 if let Ok(index_content) = index_content
300 && let Some(index) = serde_json::from_str(&index_content).log_err()
301 {
302 extension_index = index;
303 if let (Ok(Some(index_metadata)), Ok(Some(extensions_metadata))) =
304 (index_metadata, extensions_metadata)
305 && index_metadata
306 .mtime
307 .bad_is_greater_than(extensions_metadata.mtime)
308 {
309 extension_index_needs_rebuild = false;
310 }
311 }
312
313 // Immediately load all of the extensions in the initial manifest. If the
314 // index needs to be rebuild, then enqueue
315 let load_initial_extensions = this.extensions_updated(extension_index, cx);
316 let mut reload_future = None;
317 if extension_index_needs_rebuild {
318 reload_future = Some(this.reload(None, cx));
319 }
320
321 cx.spawn(async move |this, cx| {
322 if let Some(future) = reload_future {
323 future.await;
324 }
325 this.update(cx, |this, cx| this.auto_install_extensions(cx))
326 .ok();
327 this.update(cx, |this, cx| this.check_for_updates(cx)).ok();
328 })
329 .detach();
330
331 // Perform all extension loading in a single task to ensure that we
332 // never attempt to simultaneously load/unload extensions from multiple
333 // parallel tasks.
334 this.tasks.push(cx.spawn(async move |this, cx| {
335 async move {
336 load_initial_extensions.await;
337
338 let mut index_changed = false;
339 let mut debounce_timer = cx.background_spawn(futures::future::pending()).fuse();
340
341 loop {
342 select_biased! {
343 _ = debounce_timer => {
344 if index_changed {
345 let index = this
346 .update(cx, |this, cx| this.rebuild_extension_index(cx))?
347 .await;
348 this.update(cx, |this, cx| this.extensions_updated(index, cx))?
349 .await;
350 index_changed = false;
351 }
352
353 Self::update_remote_clients(&this, cx).await?;
354 }
355 _ = connection_registered_rx.next() => {
356 debounce_timer = cx.background_executor().timer(RELOAD_DEBOUNCE_DURATION).fuse()
357 }
358 extension_id = reload_rx.next() => {
359 let Some(extension_id) = extension_id else { break; };
360 this.update(cx, |this, _cx| {
361 this.modified_extensions.extend(extension_id);
362 })?;
363 index_changed = true;
364 debounce_timer = cx.background_executor().timer(RELOAD_DEBOUNCE_DURATION).fuse()
365 }
366 }
367 }
368
369 anyhow::Ok(())
370 }
371 .map(drop)
372 .await;
373 }));
374
375 // Watch the installed extensions directory for changes. Whenever changes are
376 // detected, rebuild the extension index, and load/unload any extensions that
377 // have been added, removed, or modified.
378 this.tasks.push(cx.background_spawn({
379 let fs = this.fs.clone();
380 let reload_tx = this.reload_tx.clone();
381 let installed_dir = this.installed_dir.clone();
382 async move {
383 let (mut paths, _) = fs.watch(&installed_dir, FS_WATCH_LATENCY).await;
384 while let Some(events) = paths.next().await {
385 for event in events {
386 let Ok(event_path) = event.path.strip_prefix(&installed_dir) else {
387 continue;
388 };
389
390 if let Some(path::Component::Normal(extension_dir_name)) =
391 event_path.components().next()
392 && let Some(extension_id) = extension_dir_name.to_str()
393 {
394 reload_tx.unbounded_send(Some(extension_id.into())).ok();
395 }
396 }
397 }
398 }
399 }));
400
401 this
402 }
403
404 pub fn reload(
405 &mut self,
406 modified_extension: Option<Arc<str>>,
407 cx: &mut Context<Self>,
408 ) -> impl Future<Output = ()> + use<> {
409 let (tx, rx) = oneshot::channel();
410 self.reload_complete_senders.push(tx);
411 self.reload_tx
412 .unbounded_send(modified_extension)
413 .expect("reload task exited");
414 cx.emit(Event::StartedReloading);
415
416 async move {
417 rx.await.ok();
418 }
419 }
420
421 fn extensions_dir(&self) -> PathBuf {
422 self.installed_dir.clone()
423 }
424
425 pub fn outstanding_operations(&self) -> &BTreeMap<Arc<str>, ExtensionOperation> {
426 &self.outstanding_operations
427 }
428
429 pub fn installed_extensions(&self) -> &BTreeMap<Arc<str>, ExtensionIndexEntry> {
430 &self.extension_index.extensions
431 }
432
433 pub fn dev_extensions(&self) -> impl Iterator<Item = &Arc<ExtensionManifest>> {
434 self.extension_index
435 .extensions
436 .values()
437 .filter_map(|extension| extension.dev.then_some(&extension.manifest))
438 }
439
440 pub fn extension_manifest_for_id(&self, extension_id: &str) -> Option<&Arc<ExtensionManifest>> {
441 self.extension_index
442 .extensions
443 .get(extension_id)
444 .map(|extension| &extension.manifest)
445 }
446
447 /// Returns the names of themes provided by extensions.
448 pub fn extension_themes<'a>(
449 &'a self,
450 extension_id: &'a str,
451 ) -> impl Iterator<Item = &'a Arc<str>> {
452 self.extension_index
453 .themes
454 .iter()
455 .filter_map(|(name, theme)| theme.extension.as_ref().eq(extension_id).then_some(name))
456 }
457
458 /// Returns the path to the theme file within an extension, if there is an
459 /// extension that provides the theme.
460 pub fn path_to_extension_theme(&self, theme_name: &str) -> Option<PathBuf> {
461 let entry = self.extension_index.themes.get(theme_name)?;
462
463 Some(
464 self.extensions_dir()
465 .join(entry.extension.as_ref())
466 .join(&entry.path),
467 )
468 }
469
470 /// Returns the names of icon themes provided by extensions.
471 pub fn extension_icon_themes<'a>(
472 &'a self,
473 extension_id: &'a str,
474 ) -> impl Iterator<Item = &'a Arc<str>> {
475 self.extension_index
476 .icon_themes
477 .iter()
478 .filter_map(|(name, icon_theme)| {
479 icon_theme
480 .extension
481 .as_ref()
482 .eq(extension_id)
483 .then_some(name)
484 })
485 }
486
487 /// Returns the path to the icon theme file within an extension, if there is
488 /// an extension that provides the icon theme.
489 pub fn path_to_extension_icon_theme(
490 &self,
491 icon_theme_name: &str,
492 ) -> Option<(PathBuf, PathBuf)> {
493 let entry = self.extension_index.icon_themes.get(icon_theme_name)?;
494
495 let icon_theme_path = self
496 .extensions_dir()
497 .join(entry.extension.as_ref())
498 .join(&entry.path);
499 let icons_root_path = self.extensions_dir().join(entry.extension.as_ref());
500
501 Some((icon_theme_path, icons_root_path))
502 }
503
504 pub fn fetch_extensions(
505 &self,
506 search: Option<&str>,
507 provides_filter: Option<&BTreeSet<ExtensionProvides>>,
508 cx: &mut Context<Self>,
509 ) -> Task<Result<Vec<ExtensionMetadata>>> {
510 let version = CURRENT_SCHEMA_VERSION.to_string();
511 let mut query = vec![("max_schema_version", version.as_str())];
512 if let Some(search) = search {
513 query.push(("filter", search));
514 }
515
516 let provides_filter = provides_filter.map(|provides_filter| {
517 provides_filter
518 .iter()
519 .map(|provides| provides.to_string())
520 .collect::<Vec<_>>()
521 .join(",")
522 });
523 if let Some(provides_filter) = provides_filter.as_deref() {
524 query.push(("provides", provides_filter));
525 }
526
527 self.fetch_extensions_from_api("/extensions", &query, cx)
528 }
529
530 pub fn fetch_extensions_with_update_available(
531 &mut self,
532 cx: &mut Context<Self>,
533 ) -> Task<Result<Vec<ExtensionMetadata>>> {
534 let schema_versions = schema_version_range();
535 let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
536 let extension_settings = ExtensionSettings::get_global(cx);
537 let extension_ids = self
538 .extension_index
539 .extensions
540 .iter()
541 .filter(|(id, entry)| !entry.dev && extension_settings.should_auto_update(id))
542 .map(|(id, _)| id.as_ref())
543 .collect::<Vec<_>>()
544 .join(",");
545 let task = self.fetch_extensions_from_api(
546 "/extensions/updates",
547 &[
548 ("min_schema_version", &schema_versions.start().to_string()),
549 ("max_schema_version", &schema_versions.end().to_string()),
550 (
551 "min_wasm_api_version",
552 &wasm_api_versions.start().to_string(),
553 ),
554 ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
555 ("ids", &extension_ids),
556 ],
557 cx,
558 );
559 cx.spawn(async move |this, cx| {
560 let extensions = task.await?;
561 this.update(cx, |this, _cx| {
562 extensions
563 .into_iter()
564 .filter(|extension| {
565 this.extension_index
566 .extensions
567 .get(&extension.id)
568 .is_none_or(|installed_extension| {
569 installed_extension.manifest.version != extension.manifest.version
570 })
571 })
572 .collect()
573 })
574 })
575 }
576
577 pub fn fetch_extension_versions(
578 &self,
579 extension_id: &str,
580 cx: &mut Context<Self>,
581 ) -> Task<Result<Vec<ExtensionMetadata>>> {
582 self.fetch_extensions_from_api(&format!("/extensions/{extension_id}"), &[], cx)
583 }
584
585 /// Installs any extensions that should be included with Zed by default.
586 ///
587 /// This can be used to make certain functionality provided by extensions
588 /// available out-of-the-box.
589 pub fn auto_install_extensions(&mut self, cx: &mut Context<Self>) {
590 if cfg!(test) {
591 return;
592 }
593
594 let extension_settings = ExtensionSettings::get_global(cx);
595
596 let extensions_to_install = extension_settings
597 .auto_install_extensions
598 .keys()
599 .filter(|extension_id| extension_settings.should_auto_install(extension_id))
600 .filter(|extension_id| {
601 let is_already_installed = self
602 .extension_index
603 .extensions
604 .contains_key(extension_id.as_ref());
605 !is_already_installed && !SUPPRESSED_EXTENSIONS.contains(&extension_id.as_ref())
606 })
607 .cloned()
608 .collect::<Vec<_>>();
609
610 cx.spawn(async move |this, cx| {
611 for extension_id in extensions_to_install {
612 this.update(cx, |this, cx| {
613 this.install_latest_extension(extension_id.clone(), cx);
614 })
615 .ok();
616 }
617 })
618 .detach();
619 }
620
621 pub fn check_for_updates(&mut self, cx: &mut Context<Self>) {
622 let task = self.fetch_extensions_with_update_available(cx);
623 cx.spawn(async move |this, cx| Self::upgrade_extensions(this, task.await?, cx).await)
624 .detach();
625 }
626
627 async fn upgrade_extensions(
628 this: WeakEntity<Self>,
629 extensions: Vec<ExtensionMetadata>,
630 cx: &mut AsyncApp,
631 ) -> Result<()> {
632 for extension in extensions {
633 let task = this.update(cx, |this, cx| {
634 if let Some(installed_extension) =
635 this.extension_index.extensions.get(&extension.id)
636 {
637 let installed_version =
638 Version::from_str(&installed_extension.manifest.version).ok()?;
639 let latest_version = Version::from_str(&extension.manifest.version).ok()?;
640
641 if installed_version >= latest_version {
642 return None;
643 }
644 }
645
646 Some(this.upgrade_extension(extension.id, extension.manifest.version, cx))
647 })?;
648
649 if let Some(task) = task {
650 task.await.log_err();
651 }
652 }
653 anyhow::Ok(())
654 }
655
656 fn fetch_extensions_from_api(
657 &self,
658 path: &str,
659 query: &[(&str, &str)],
660 cx: &mut Context<ExtensionStore>,
661 ) -> Task<Result<Vec<ExtensionMetadata>>> {
662 let url = self.http_client.build_zed_api_url(path, query);
663 let http_client = self.http_client.clone();
664 cx.spawn(async move |_, _| {
665 let mut response = http_client
666 .get(url?.as_ref(), AsyncBody::empty(), true)
667 .await?;
668
669 let mut body = Vec::new();
670 response
671 .body_mut()
672 .read_to_end(&mut body)
673 .await
674 .context("error reading extensions")?;
675
676 if response.status().is_client_error() {
677 let text = String::from_utf8_lossy(body.as_slice());
678 bail!(
679 "status error {}, response: {text:?}",
680 response.status().as_u16()
681 );
682 }
683
684 let mut response: GetExtensionsResponse = serde_json::from_slice(&body)?;
685
686 response
687 .data
688 .retain(|extension| !SUPPRESSED_EXTENSIONS.contains(&extension.id.as_ref()));
689
690 Ok(response.data)
691 })
692 }
693
694 pub fn install_extension(
695 &mut self,
696 extension_id: Arc<str>,
697 version: Arc<str>,
698 cx: &mut Context<Self>,
699 ) {
700 self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Install, cx)
701 .detach_and_log_err(cx);
702 }
703
704 fn install_or_upgrade_extension_at_endpoint(
705 &mut self,
706 extension_id: Arc<str>,
707 url: Url,
708 operation: ExtensionOperation,
709 cx: &mut Context<Self>,
710 ) -> Task<Result<()>> {
711 let extension_dir = self.installed_dir.join(extension_id.as_ref());
712 let http_client = self.http_client.clone();
713 let fs = self.fs.clone();
714
715 match self.outstanding_operations.entry(extension_id.clone()) {
716 btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
717 btree_map::Entry::Vacant(e) => e.insert(operation),
718 };
719 cx.notify();
720
721 cx.spawn(async move |this, cx| {
722 let _finish = cx.on_drop(&this, {
723 let extension_id = extension_id.clone();
724 move |this, cx| {
725 this.outstanding_operations.remove(extension_id.as_ref());
726 cx.notify();
727 }
728 });
729
730 let mut response = http_client
731 .get(url.as_ref(), Default::default(), true)
732 .await
733 .context("downloading extension")?;
734
735 fs.remove_dir(
736 &extension_dir,
737 RemoveOptions {
738 recursive: true,
739 ignore_if_not_exists: true,
740 },
741 )
742 .await?;
743
744 let content_length = response
745 .headers()
746 .get(http_client::http::header::CONTENT_LENGTH)
747 .and_then(|value| value.to_str().ok()?.parse::<usize>().ok());
748
749 let mut body = BufReader::new(response.body_mut());
750 let mut tar_gz_bytes = Vec::new();
751 body.read_to_end(&mut tar_gz_bytes).await?;
752
753 if let Some(content_length) = content_length {
754 let actual_len = tar_gz_bytes.len();
755 if content_length != actual_len {
756 bail!(concat!(
757 "downloaded extension size {actual_len} ",
758 "does not match content length {content_length}"
759 ));
760 }
761 }
762 let decompressed_bytes = GzipDecoder::new(BufReader::new(tar_gz_bytes.as_slice()));
763 let archive = Archive::new(decompressed_bytes);
764 archive.unpack(extension_dir).await?;
765 this.update(cx, |this, cx| this.reload(Some(extension_id.clone()), cx))?
766 .await;
767
768 if let ExtensionOperation::Install = operation {
769 this.update(cx, |this, cx| {
770 cx.emit(Event::ExtensionInstalled(extension_id.clone()));
771 if let Some(events) = ExtensionEvents::try_global(cx)
772 && let Some(manifest) = this.extension_manifest_for_id(&extension_id)
773 {
774 events.update(cx, |this, cx| {
775 this.emit(extension::Event::ExtensionInstalled(manifest.clone()), cx)
776 });
777 }
778 })
779 .ok();
780 }
781
782 anyhow::Ok(())
783 })
784 }
785
786 pub fn install_latest_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
787 log::info!("installing extension {extension_id} latest version");
788
789 let schema_versions = schema_version_range();
790 let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
791
792 let Some(url) = self
793 .http_client
794 .build_zed_api_url(
795 &format!("/extensions/{extension_id}/download"),
796 &[
797 ("min_schema_version", &schema_versions.start().to_string()),
798 ("max_schema_version", &schema_versions.end().to_string()),
799 (
800 "min_wasm_api_version",
801 &wasm_api_versions.start().to_string(),
802 ),
803 ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
804 ],
805 )
806 .log_err()
807 else {
808 return;
809 };
810
811 self.install_or_upgrade_extension_at_endpoint(
812 extension_id,
813 url,
814 ExtensionOperation::Install,
815 cx,
816 )
817 .detach_and_log_err(cx);
818 }
819
820 pub fn upgrade_extension(
821 &mut self,
822 extension_id: Arc<str>,
823 version: Arc<str>,
824 cx: &mut Context<Self>,
825 ) -> Task<Result<()>> {
826 self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Upgrade, cx)
827 }
828
829 fn install_or_upgrade_extension(
830 &mut self,
831 extension_id: Arc<str>,
832 version: Arc<str>,
833 operation: ExtensionOperation,
834 cx: &mut Context<Self>,
835 ) -> Task<Result<()>> {
836 log::info!("installing extension {extension_id} {version}");
837 let Some(url) = self
838 .http_client
839 .build_zed_api_url(
840 &format!("/extensions/{extension_id}/{version}/download"),
841 &[],
842 )
843 .log_err()
844 else {
845 return Task::ready(Ok(()));
846 };
847
848 self.install_or_upgrade_extension_at_endpoint(extension_id, url, operation, cx)
849 }
850
851 pub fn uninstall_extension(
852 &mut self,
853 extension_id: Arc<str>,
854 cx: &mut Context<Self>,
855 ) -> Task<Result<()>> {
856 let extension_dir = self.installed_dir.join(extension_id.as_ref());
857 let work_dir = self.wasm_host.work_dir.join(extension_id.as_ref());
858 let fs = self.fs.clone();
859
860 let extension_manifest = self.extension_manifest_for_id(&extension_id).cloned();
861
862 match self.outstanding_operations.entry(extension_id.clone()) {
863 btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
864 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
865 };
866
867 cx.spawn(async move |extension_store, cx| {
868 let _finish = cx.on_drop(&extension_store, {
869 let extension_id = extension_id.clone();
870 move |this, cx| {
871 this.outstanding_operations.remove(extension_id.as_ref());
872 cx.notify();
873 }
874 });
875
876 fs.remove_dir(
877 &extension_dir,
878 RemoveOptions {
879 recursive: true,
880 ignore_if_not_exists: true,
881 },
882 )
883 .await
884 .with_context(|| format!("Removing extension dir {extension_dir:?}"))?;
885
886 extension_store
887 .update(cx, |extension_store, cx| extension_store.reload(None, cx))?
888 .await;
889
890 // There's a race between wasm extension fully stopping and the directory removal.
891 // On Windows, it's impossible to remove a directory that has a process running in it.
892 for i in 0..3 {
893 cx.background_executor()
894 .timer(Duration::from_millis(i * 100))
895 .await;
896 let removal_result = fs
897 .remove_dir(
898 &work_dir,
899 RemoveOptions {
900 recursive: true,
901 ignore_if_not_exists: true,
902 },
903 )
904 .await;
905 match removal_result {
906 Ok(()) => break,
907 Err(e) => {
908 if i == 2 {
909 log::error!("Failed to remove extension work dir {work_dir:?} : {e}");
910 }
911 }
912 }
913 }
914
915 extension_store.update(cx, |_, cx| {
916 cx.emit(Event::ExtensionUninstalled(extension_id.clone()));
917 if let Some(events) = ExtensionEvents::try_global(cx)
918 && let Some(manifest) = extension_manifest
919 {
920 events.update(cx, |this, cx| {
921 this.emit(extension::Event::ExtensionUninstalled(manifest.clone()), cx)
922 });
923 }
924 })?;
925
926 anyhow::Ok(())
927 })
928 }
929
930 pub fn install_dev_extension(
931 &mut self,
932 extension_source_path: PathBuf,
933 cx: &mut Context<Self>,
934 ) -> Task<Result<()>> {
935 let extensions_dir = self.extensions_dir();
936 let fs = self.fs.clone();
937 let builder = self.builder.clone();
938
939 cx.spawn(async move |this, cx| {
940 let mut extension_manifest =
941 ExtensionManifest::load(fs.clone(), &extension_source_path).await?;
942 let extension_id = extension_manifest.id.clone();
943
944 if let Some(uninstall_task) = this
945 .update(cx, |this, cx| {
946 this.extension_index
947 .extensions
948 .get(extension_id.as_ref())
949 .is_some_and(|index_entry| !index_entry.dev)
950 .then(|| this.uninstall_extension(extension_id.clone(), cx))
951 })
952 .ok()
953 .flatten()
954 {
955 uninstall_task.await.log_err();
956 }
957
958 if !this.update(cx, |this, cx| {
959 match this.outstanding_operations.entry(extension_id.clone()) {
960 btree_map::Entry::Occupied(_) => return false,
961 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Install),
962 };
963 cx.notify();
964 true
965 })? {
966 return Ok(());
967 }
968
969 let _finish = cx.on_drop(&this, {
970 let extension_id = extension_id.clone();
971 move |this, cx| {
972 this.outstanding_operations.remove(extension_id.as_ref());
973 cx.notify();
974 }
975 });
976
977 cx.background_spawn({
978 let extension_source_path = extension_source_path.clone();
979 let fs = fs.clone();
980 async move {
981 builder
982 .compile_extension(
983 &extension_source_path,
984 &mut extension_manifest,
985 CompileExtensionOptions::dev(),
986 fs,
987 )
988 .await
989 }
990 })
991 .await
992 .inspect_err(|error| {
993 util::log_err(error);
994 })?;
995
996 let output_path = &extensions_dir.join(extension_id.as_ref());
997 if let Some(metadata) = fs.metadata(output_path).await? {
998 if metadata.is_symlink {
999 fs.remove_file(
1000 output_path,
1001 RemoveOptions {
1002 recursive: false,
1003 ignore_if_not_exists: true,
1004 },
1005 )
1006 .await?;
1007 } else {
1008 bail!("extension {extension_id} is still installed");
1009 }
1010 }
1011
1012 fs.create_symlink(output_path, extension_source_path)
1013 .await?;
1014
1015 this.update(cx, |this, cx| this.reload(None, cx))?.await;
1016 this.update(cx, |this, cx| {
1017 cx.emit(Event::ExtensionInstalled(extension_id.clone()));
1018 if let Some(events) = ExtensionEvents::try_global(cx)
1019 && let Some(manifest) = this.extension_manifest_for_id(&extension_id)
1020 {
1021 events.update(cx, |this, cx| {
1022 this.emit(extension::Event::ExtensionInstalled(manifest.clone()), cx)
1023 });
1024 }
1025 })?;
1026
1027 Ok(())
1028 })
1029 }
1030
1031 pub fn rebuild_dev_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
1032 let path = self.installed_dir.join(extension_id.as_ref());
1033 let builder = self.builder.clone();
1034 let fs = self.fs.clone();
1035
1036 match self.outstanding_operations.entry(extension_id.clone()) {
1037 btree_map::Entry::Occupied(_) => return,
1038 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Upgrade),
1039 };
1040
1041 cx.notify();
1042 let compile = cx.background_spawn(async move {
1043 let mut manifest = ExtensionManifest::load(fs.clone(), &path).await?;
1044 builder
1045 .compile_extension(&path, &mut manifest, CompileExtensionOptions::dev(), fs)
1046 .await
1047 });
1048
1049 cx.spawn(async move |this, cx| {
1050 let result = compile.await;
1051
1052 this.update(cx, |this, cx| {
1053 this.outstanding_operations.remove(&extension_id);
1054 cx.notify();
1055 })?;
1056
1057 if result.is_ok() {
1058 this.update(cx, |this, cx| this.reload(Some(extension_id), cx))?
1059 .await;
1060 }
1061
1062 result
1063 })
1064 .detach_and_log_err(cx)
1065 }
1066
1067 /// Updates the set of installed extensions.
1068 ///
1069 /// First, this unloads any themes, languages, or grammars that are
1070 /// no longer in the manifest, or whose files have changed on disk.
1071 /// Then it loads any themes, languages, or grammars that are newly
1072 /// added to the manifest, or whose files have changed on disk.
1073 #[ztracing::instrument(skip_all)]
1074 fn extensions_updated(
1075 &mut self,
1076 mut new_index: ExtensionIndex,
1077 cx: &mut Context<Self>,
1078 ) -> Task<()> {
1079 let old_index = &self.extension_index;
1080
1081 new_index
1082 .extensions
1083 .retain(|extension_id, _| !SUPPRESSED_EXTENSIONS.contains(&extension_id.as_ref()));
1084
1085 // Determine which extensions need to be loaded and unloaded, based
1086 // on the changes to the manifest and the extensions that we know have been
1087 // modified.
1088 let mut extensions_to_unload = Vec::default();
1089 let mut extensions_to_load = Vec::default();
1090 {
1091 let mut old_keys = old_index.extensions.iter().peekable();
1092 let mut new_keys = new_index.extensions.iter().peekable();
1093 loop {
1094 match (old_keys.peek(), new_keys.peek()) {
1095 (None, None) => break,
1096 (None, Some(_)) => {
1097 extensions_to_load.push(new_keys.next().unwrap().0.clone());
1098 }
1099 (Some(_), None) => {
1100 extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1101 }
1102 (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(new_key) {
1103 Ordering::Equal => {
1104 let (old_key, old_value) = old_keys.next().unwrap();
1105 let (new_key, new_value) = new_keys.next().unwrap();
1106 if old_value != new_value || self.modified_extensions.contains(old_key)
1107 {
1108 extensions_to_unload.push(old_key.clone());
1109 extensions_to_load.push(new_key.clone());
1110 }
1111 }
1112 Ordering::Less => {
1113 extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1114 }
1115 Ordering::Greater => {
1116 extensions_to_load.push(new_keys.next().unwrap().0.clone());
1117 }
1118 },
1119 }
1120 }
1121 self.modified_extensions.clear();
1122 }
1123
1124 if extensions_to_load.is_empty() && extensions_to_unload.is_empty() {
1125 self.reload_complete_senders.clear();
1126 return Task::ready(());
1127 }
1128
1129 let reload_count = extensions_to_unload
1130 .iter()
1131 .filter(|id| extensions_to_load.contains(id))
1132 .count();
1133
1134 log::info!(
1135 "extensions updated. loading {}, reloading {}, unloading {}",
1136 extensions_to_load.len() - reload_count,
1137 reload_count,
1138 extensions_to_unload.len() - reload_count
1139 );
1140
1141 let extension_ids = extensions_to_load
1142 .iter()
1143 .filter_map(|id| {
1144 Some((
1145 id.clone(),
1146 new_index.extensions.get(id)?.manifest.version.clone(),
1147 ))
1148 })
1149 .collect::<Vec<_>>();
1150
1151 telemetry::event!("Extensions Loaded", id_and_versions = extension_ids);
1152
1153 let themes_to_remove = old_index
1154 .themes
1155 .iter()
1156 .filter_map(|(name, entry)| {
1157 if extensions_to_unload.contains(&entry.extension) {
1158 Some(name.clone().into())
1159 } else {
1160 None
1161 }
1162 })
1163 .collect::<Vec<_>>();
1164 let icon_themes_to_remove = old_index
1165 .icon_themes
1166 .iter()
1167 .filter_map(|(name, entry)| {
1168 if extensions_to_unload.contains(&entry.extension) {
1169 Some(name.clone().into())
1170 } else {
1171 None
1172 }
1173 })
1174 .collect::<Vec<_>>();
1175 let languages_to_remove = old_index
1176 .languages
1177 .iter()
1178 .filter_map(|(name, entry)| {
1179 if extensions_to_unload.contains(&entry.extension) {
1180 Some(name.clone())
1181 } else {
1182 None
1183 }
1184 })
1185 .collect::<Vec<_>>();
1186 let mut grammars_to_remove = Vec::new();
1187 let mut server_removal_tasks = Vec::with_capacity(extensions_to_unload.len());
1188 for extension_id in &extensions_to_unload {
1189 let Some(extension) = old_index.extensions.get(extension_id) else {
1190 continue;
1191 };
1192 grammars_to_remove.extend(extension.manifest.grammars.keys().cloned());
1193 for (language_server_name, config) in &extension.manifest.language_servers {
1194 for language in config.languages() {
1195 server_removal_tasks.push(self.proxy.remove_language_server(
1196 &language,
1197 language_server_name,
1198 cx,
1199 ));
1200 }
1201 }
1202
1203 for server_id in extension.manifest.context_servers.keys() {
1204 self.proxy.unregister_context_server(server_id.clone(), cx);
1205 }
1206 for adapter in extension.manifest.debug_adapters.keys() {
1207 self.proxy.unregister_debug_adapter(adapter.clone());
1208 }
1209 for locator in extension.manifest.debug_locators.keys() {
1210 self.proxy.unregister_debug_locator(locator.clone());
1211 }
1212 for command_name in extension.manifest.slash_commands.keys() {
1213 self.proxy.unregister_slash_command(command_name.clone());
1214 }
1215 }
1216
1217 self.wasm_extensions
1218 .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
1219 self.proxy.remove_user_themes(themes_to_remove);
1220 self.proxy.remove_icon_themes(icon_themes_to_remove);
1221 self.proxy
1222 .remove_languages(&languages_to_remove, &grammars_to_remove);
1223
1224 // Remove semantic token rules for languages being unloaded.
1225 if !languages_to_remove.is_empty() {
1226 SettingsStore::update_global(cx, |store, cx| {
1227 for language in &languages_to_remove {
1228 store.remove_language_semantic_token_rules(language.as_ref(), cx);
1229 }
1230 });
1231 }
1232
1233 let mut grammars_to_add = Vec::new();
1234 let mut themes_to_add = Vec::new();
1235 let mut icon_themes_to_add = Vec::new();
1236 let mut snippets_to_add = Vec::new();
1237 for extension_id in &extensions_to_load {
1238 let Some(extension) = new_index.extensions.get(extension_id) else {
1239 continue;
1240 };
1241
1242 grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
1243 let mut grammar_path = self.installed_dir.clone();
1244 grammar_path.extend([extension_id.as_ref(), "grammars"]);
1245 grammar_path.push(grammar_name.as_ref());
1246 grammar_path.set_extension("wasm");
1247 (grammar_name.clone(), grammar_path)
1248 }));
1249 themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
1250 let mut path = self.installed_dir.clone();
1251 path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1252 path
1253 }));
1254 icon_themes_to_add.extend(extension.manifest.icon_themes.iter().map(
1255 |icon_theme_path| {
1256 let mut path = self.installed_dir.clone();
1257 path.extend([Path::new(extension_id.as_ref()), icon_theme_path.as_path()]);
1258
1259 let mut icons_root_path = self.installed_dir.clone();
1260 icons_root_path.extend([Path::new(extension_id.as_ref())]);
1261
1262 (path, icons_root_path)
1263 },
1264 ));
1265 snippets_to_add.extend(extension.manifest.snippets.iter().flat_map(|snippets| {
1266 snippets.paths().map(|snippets_path| {
1267 let mut path = self.installed_dir.clone();
1268 path.extend([Path::new(extension_id.as_ref()), snippets_path.as_path()]);
1269 path
1270 })
1271 }));
1272 }
1273
1274 self.proxy.register_grammars(grammars_to_add);
1275 let languages_to_add = new_index
1276 .languages
1277 .iter()
1278 .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
1279 .collect::<Vec<_>>();
1280 let mut semantic_token_rules_to_add: Vec<(LanguageName, SemanticTokenRules)> = Vec::new();
1281 for (language_name, language) in languages_to_add {
1282 let mut language_path = self.installed_dir.clone();
1283 language_path.extend([
1284 Path::new(language.extension.as_ref()),
1285 language.path.as_path(),
1286 ]);
1287
1288 // Load semantic token rules if present in the language directory.
1289 let rules_path = language_path.join(SemanticTokenRules::FILE_NAME);
1290 if std::fs::exists(&rules_path).is_ok_and(|exists| exists)
1291 && let Some(rules) = SemanticTokenRules::load(&rules_path).log_err()
1292 {
1293 semantic_token_rules_to_add.push((language_name.clone(), rules));
1294 }
1295
1296 self.proxy.register_language(
1297 language_name.clone(),
1298 language.grammar.clone(),
1299 language.matcher.clone(),
1300 language.hidden,
1301 Arc::new(move || {
1302 let config =
1303 LanguageConfig::load(language_path.join(LanguageConfig::FILE_NAME))?;
1304 let queries = load_plugin_queries(&language_path);
1305 let context_provider =
1306 std::fs::read_to_string(language_path.join(TaskTemplates::FILE_NAME))
1307 .ok()
1308 .and_then(|contents| {
1309 let definitions =
1310 serde_json_lenient::from_str(&contents).log_err()?;
1311 Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1312 });
1313
1314 Ok(LoadedLanguage {
1315 config,
1316 queries,
1317 context_provider,
1318 toolchain_provider: None,
1319 manifest_name: None,
1320 })
1321 }),
1322 );
1323 }
1324
1325 // Register semantic token rules for newly loaded extension languages.
1326 if !semantic_token_rules_to_add.is_empty() {
1327 SettingsStore::update_global(cx, |store, cx| {
1328 for (language_name, rules) in semantic_token_rules_to_add {
1329 store.set_language_semantic_token_rules(language_name.0.clone(), rules, cx);
1330 }
1331 });
1332 }
1333
1334 let fs = self.fs.clone();
1335 let wasm_host = self.wasm_host.clone();
1336 let root_dir = self.installed_dir.clone();
1337 let proxy = self.proxy.clone();
1338 let extension_entries = extensions_to_load
1339 .iter()
1340 .filter_map(|name| new_index.extensions.get(name).cloned())
1341 .collect::<Vec<_>>();
1342 self.extension_index = new_index;
1343 cx.notify();
1344 cx.emit(Event::ExtensionsUpdated);
1345
1346 cx.spawn(async move |this, cx| {
1347 cx.background_spawn({
1348 let fs = fs.clone();
1349 async move {
1350 let _ = join_all(server_removal_tasks).await;
1351 for theme_path in themes_to_add {
1352 proxy
1353 .load_user_theme(theme_path, fs.clone())
1354 .await
1355 .log_err();
1356 }
1357
1358 for (icon_theme_path, icons_root_path) in icon_themes_to_add {
1359 proxy
1360 .load_icon_theme(icon_theme_path, icons_root_path, fs.clone())
1361 .await
1362 .log_err();
1363 }
1364
1365 for snippets_path in &snippets_to_add {
1366 match fs
1367 .load(snippets_path)
1368 .await
1369 .with_context(|| format!("Loading snippets from {snippets_path:?}"))
1370 {
1371 Ok(snippets_contents) => {
1372 proxy
1373 .register_snippet(snippets_path, &snippets_contents)
1374 .log_err();
1375 }
1376 Err(e) => log::error!("Cannot load snippets: {e:#}"),
1377 }
1378 }
1379 }
1380 })
1381 .await;
1382
1383 let mut wasm_extensions = Vec::new();
1384 for extension in extension_entries {
1385 if extension.manifest.lib.kind.is_none() {
1386 continue;
1387 };
1388
1389 let extension_path = root_dir.join(extension.manifest.id.as_ref());
1390 let wasm_extension = WasmExtension::load(
1391 &extension_path,
1392 &extension.manifest,
1393 wasm_host.clone(),
1394 cx,
1395 )
1396 .await
1397 .with_context(|| format!("Loading extension from {extension_path:?}"));
1398
1399 match wasm_extension {
1400 Ok(wasm_extension) => {
1401 wasm_extensions.push((extension.manifest.clone(), wasm_extension))
1402 }
1403 Err(e) => {
1404 log::error!(
1405 "Failed to load extension: {}, {:#}",
1406 extension.manifest.id,
1407 e
1408 );
1409 this.update(cx, |_, cx| {
1410 cx.emit(Event::ExtensionFailedToLoad(extension.manifest.id.clone()))
1411 })
1412 .ok();
1413 }
1414 }
1415 }
1416
1417 this.update(cx, |this, cx| {
1418 this.reload_complete_senders.clear();
1419
1420 for (manifest, wasm_extension) in &wasm_extensions {
1421 let extension = Arc::new(wasm_extension.clone());
1422
1423 for (language_server_id, language_server_config) in &manifest.language_servers {
1424 for language in language_server_config.languages() {
1425 this.proxy.register_language_server(
1426 extension.clone(),
1427 language_server_id.clone(),
1428 language.clone(),
1429 );
1430 }
1431 }
1432
1433 for (slash_command_name, slash_command) in &manifest.slash_commands {
1434 this.proxy.register_slash_command(
1435 extension.clone(),
1436 extension::SlashCommand {
1437 name: slash_command_name.to_string(),
1438 description: slash_command.description.to_string(),
1439 // We don't currently expose this as a configurable option, as it currently drives
1440 // the `menu_text` on the `SlashCommand` trait, which is not used for slash commands
1441 // defined in extensions, as they are not able to be added to the menu.
1442 tooltip_text: String::new(),
1443 requires_argument: slash_command.requires_argument,
1444 },
1445 );
1446 }
1447
1448 for id in manifest.context_servers.keys() {
1449 this.proxy
1450 .register_context_server(extension.clone(), id.clone(), cx);
1451 }
1452
1453 for (debug_adapter, meta) in &manifest.debug_adapters {
1454 let mut path = root_dir.clone();
1455 path.push(Path::new(manifest.id.as_ref()));
1456 if let Some(schema_path) = &meta.schema_path {
1457 path.push(schema_path);
1458 } else {
1459 path.push("debug_adapter_schemas");
1460 path.push(Path::new(debug_adapter.as_ref()).with_extension("json"));
1461 }
1462
1463 this.proxy.register_debug_adapter(
1464 extension.clone(),
1465 debug_adapter.clone(),
1466 &path,
1467 );
1468 }
1469
1470 for debug_adapter in manifest.debug_locators.keys() {
1471 this.proxy
1472 .register_debug_locator(extension.clone(), debug_adapter.clone());
1473 }
1474 }
1475
1476 this.wasm_extensions.extend(wasm_extensions);
1477 this.proxy.set_extensions_loaded();
1478 this.proxy.reload_current_theme(cx);
1479 this.proxy.reload_current_icon_theme(cx);
1480
1481 if let Some(events) = ExtensionEvents::try_global(cx) {
1482 events.update(cx, |this, cx| {
1483 this.emit(extension::Event::ExtensionsInstalledChanged, cx)
1484 });
1485 }
1486 })
1487 .ok();
1488 })
1489 }
1490
1491 fn rebuild_extension_index(&self, cx: &mut Context<Self>) -> Task<ExtensionIndex> {
1492 let fs = self.fs.clone();
1493 let work_dir = self.wasm_host.work_dir.clone();
1494 let extensions_dir = self.installed_dir.clone();
1495 let index_path = self.index_path.clone();
1496 let proxy = self.proxy.clone();
1497 cx.background_spawn(async move {
1498 let start_time = Instant::now();
1499 let mut index = ExtensionIndex::default();
1500
1501 fs.create_dir(&work_dir).await.log_err();
1502 fs.create_dir(&extensions_dir).await.log_err();
1503
1504 let extension_paths = fs.read_dir(&extensions_dir).await;
1505 if let Ok(mut extension_paths) = extension_paths {
1506 while let Some(extension_dir) = extension_paths.next().await {
1507 let Ok(extension_dir) = extension_dir else {
1508 continue;
1509 };
1510
1511 if extension_dir
1512 .file_name()
1513 .is_some_and(|file_name| file_name == ".DS_Store")
1514 {
1515 continue;
1516 }
1517
1518 Self::add_extension_to_index(
1519 fs.clone(),
1520 extension_dir,
1521 &mut index,
1522 proxy.clone(),
1523 )
1524 .await
1525 .log_err();
1526 }
1527 }
1528
1529 if let Ok(index_json) = serde_json::to_string_pretty(&index) {
1530 fs.save(&index_path, &index_json.as_str().into(), Default::default())
1531 .await
1532 .context("failed to save extension index")
1533 .log_err();
1534 }
1535
1536 log::info!("rebuilt extension index in {:?}", start_time.elapsed());
1537 index
1538 })
1539 }
1540
1541 async fn add_extension_to_index(
1542 fs: Arc<dyn Fs>,
1543 extension_dir: PathBuf,
1544 index: &mut ExtensionIndex,
1545 proxy: Arc<ExtensionHostProxy>,
1546 ) -> Result<()> {
1547 let mut extension_manifest = ExtensionManifest::load(fs.clone(), &extension_dir).await?;
1548 let extension_id = extension_manifest.id.clone();
1549
1550 if SUPPRESSED_EXTENSIONS.contains(&extension_id.as_ref()) {
1551 return Ok(());
1552 }
1553
1554 // TODO: distinguish dev extensions more explicitly, by the absence
1555 // of a checksum file that we'll create when downloading normal extensions.
1556 let is_dev = fs
1557 .metadata(&extension_dir)
1558 .await?
1559 .with_context(|| format!("missing extension directory {extension_dir:?}"))?
1560 .is_symlink;
1561
1562 let language_dir = extension_dir.join("languages");
1563 if let Ok(mut language_paths) = fs.read_dir(&language_dir).await {
1564 while let Some(language_path) = language_paths.next().await {
1565 let language_path = language_path
1566 .with_context(|| format!("reading entries in language dir {language_dir:?}"))?;
1567 let Ok(relative_path) = language_path.strip_prefix(&extension_dir) else {
1568 continue;
1569 };
1570 let Ok(Some(fs_metadata)) = fs.metadata(&language_path).await else {
1571 continue;
1572 };
1573 if !fs_metadata.is_dir {
1574 continue;
1575 }
1576 let language_config_path = language_path.join(LanguageConfig::FILE_NAME);
1577 let config = fs.load(&language_config_path).await.with_context(|| {
1578 format!("loading language config from {language_config_path:?}")
1579 })?;
1580 let config = ::toml::from_str::<LanguageConfig>(&config)?;
1581
1582 let relative_path = relative_path.to_path_buf();
1583 if !extension_manifest.languages.contains(&relative_path) {
1584 extension_manifest.languages.push(relative_path.clone());
1585 }
1586
1587 index.languages.insert(
1588 config.name.clone(),
1589 ExtensionIndexLanguageEntry {
1590 extension: extension_id.clone(),
1591 path: relative_path,
1592 matcher: config.matcher,
1593 hidden: config.hidden,
1594 grammar: config.grammar,
1595 },
1596 );
1597 }
1598 }
1599
1600 if let Ok(mut theme_paths) = fs.read_dir(&extension_dir.join("themes")).await {
1601 while let Some(theme_path) = theme_paths.next().await {
1602 let theme_path = theme_path?;
1603 let Ok(relative_path) = theme_path.strip_prefix(&extension_dir) else {
1604 continue;
1605 };
1606
1607 let Some(theme_families) = proxy
1608 .list_theme_names(theme_path.clone(), fs.clone())
1609 .await
1610 .log_err()
1611 else {
1612 continue;
1613 };
1614
1615 let relative_path = relative_path.to_path_buf();
1616 if !extension_manifest.themes.contains(&relative_path) {
1617 extension_manifest.themes.push(relative_path.clone());
1618 }
1619
1620 for theme_name in theme_families {
1621 index.themes.insert(
1622 theme_name.into(),
1623 ExtensionIndexThemeEntry {
1624 extension: extension_id.clone(),
1625 path: relative_path.clone(),
1626 },
1627 );
1628 }
1629 }
1630 }
1631
1632 if let Ok(mut icon_theme_paths) = fs.read_dir(&extension_dir.join("icon_themes")).await {
1633 while let Some(icon_theme_path) = icon_theme_paths.next().await {
1634 let icon_theme_path = icon_theme_path?;
1635 let Ok(relative_path) = icon_theme_path.strip_prefix(&extension_dir) else {
1636 continue;
1637 };
1638
1639 let Some(icon_theme_families) = proxy
1640 .list_icon_theme_names(icon_theme_path.clone(), fs.clone())
1641 .await
1642 .log_err()
1643 else {
1644 continue;
1645 };
1646
1647 let relative_path = relative_path.to_path_buf();
1648 if !extension_manifest.icon_themes.contains(&relative_path) {
1649 extension_manifest.icon_themes.push(relative_path.clone());
1650 }
1651
1652 for icon_theme_name in icon_theme_families {
1653 index.icon_themes.insert(
1654 icon_theme_name.into(),
1655 ExtensionIndexIconThemeEntry {
1656 extension: extension_id.clone(),
1657 path: relative_path.clone(),
1658 },
1659 );
1660 }
1661 }
1662 }
1663
1664 let extension_wasm_path = extension_dir.join("extension.wasm");
1665 if fs.is_file(&extension_wasm_path).await {
1666 extension_manifest
1667 .lib
1668 .kind
1669 .get_or_insert(ExtensionLibraryKind::Rust);
1670 }
1671
1672 index.extensions.insert(
1673 extension_id.clone(),
1674 ExtensionIndexEntry {
1675 dev: is_dev,
1676 manifest: Arc::new(extension_manifest),
1677 },
1678 );
1679
1680 Ok(())
1681 }
1682
1683 fn prepare_remote_extension(
1684 &mut self,
1685 extension_id: Arc<str>,
1686 is_dev: bool,
1687 tmp_dir: PathBuf,
1688 cx: &mut Context<Self>,
1689 ) -> Task<Result<()>> {
1690 let src_dir = self.extensions_dir().join(extension_id.as_ref());
1691 let Some(loaded_extension) = self.extension_index.extensions.get(&extension_id).cloned()
1692 else {
1693 return Task::ready(Err(anyhow!("extension no longer installed")));
1694 };
1695 let fs = self.fs.clone();
1696 cx.background_spawn(async move {
1697 const EXTENSION_TOML: &str = "extension.toml";
1698 const EXTENSION_WASM: &str = "extension.wasm";
1699 const CONFIG_TOML: &str = LanguageConfig::FILE_NAME;
1700
1701 if is_dev {
1702 let manifest_toml = toml::to_string(&loaded_extension.manifest)?;
1703 fs.save(
1704 &tmp_dir.join(EXTENSION_TOML),
1705 &Rope::from(manifest_toml),
1706 language::LineEnding::Unix,
1707 )
1708 .await?;
1709 } else {
1710 fs.copy_file(
1711 &src_dir.join(EXTENSION_TOML),
1712 &tmp_dir.join(EXTENSION_TOML),
1713 fs::CopyOptions::default(),
1714 )
1715 .await?
1716 }
1717
1718 if fs.is_file(&src_dir.join(EXTENSION_WASM)).await {
1719 fs.copy_file(
1720 &src_dir.join(EXTENSION_WASM),
1721 &tmp_dir.join(EXTENSION_WASM),
1722 fs::CopyOptions::default(),
1723 )
1724 .await?
1725 }
1726
1727 for language_path in loaded_extension.manifest.languages.iter() {
1728 if fs
1729 .is_file(&src_dir.join(language_path).join(CONFIG_TOML))
1730 .await
1731 {
1732 fs.create_dir(&tmp_dir.join(language_path)).await?;
1733 fs.copy_file(
1734 &src_dir.join(language_path).join(CONFIG_TOML),
1735 &tmp_dir.join(language_path).join(CONFIG_TOML),
1736 fs::CopyOptions::default(),
1737 )
1738 .await?
1739 }
1740 }
1741
1742 for (adapter_name, meta) in loaded_extension.manifest.debug_adapters.iter() {
1743 let schema_path = &extension::build_debug_adapter_schema_path(adapter_name, meta);
1744
1745 if fs.is_file(&src_dir.join(schema_path)).await {
1746 if let Some(parent) = schema_path.parent() {
1747 fs.create_dir(&tmp_dir.join(parent)).await?
1748 }
1749 fs.copy_file(
1750 &src_dir.join(schema_path),
1751 &tmp_dir.join(schema_path),
1752 fs::CopyOptions::default(),
1753 )
1754 .await?
1755 }
1756 }
1757
1758 Ok(())
1759 })
1760 }
1761
1762 async fn sync_extensions_to_remotes(
1763 this: &WeakEntity<Self>,
1764 client: WeakEntity<RemoteClient>,
1765 cx: &mut AsyncApp,
1766 ) -> Result<()> {
1767 let extensions = this.update(cx, |this, _cx| {
1768 this.extension_index
1769 .extensions
1770 .iter()
1771 .filter_map(|(id, entry)| {
1772 if !entry.manifest.allow_remote_load() {
1773 return None;
1774 }
1775 Some(proto::Extension {
1776 id: id.to_string(),
1777 version: entry.manifest.version.to_string(),
1778 dev: entry.dev,
1779 })
1780 })
1781 .collect()
1782 })?;
1783
1784 let response = client
1785 .update(cx, |client, _cx| {
1786 client
1787 .proto_client()
1788 .request(proto::SyncExtensions { extensions })
1789 })?
1790 .await?;
1791 let path_style = client.read_with(cx, |client, _| client.path_style())?;
1792
1793 for missing_extension in response.missing_extensions.into_iter() {
1794 let tmp_dir = tempfile::tempdir()?;
1795 this.update(cx, |this, cx| {
1796 this.prepare_remote_extension(
1797 missing_extension.id.clone().into(),
1798 missing_extension.dev,
1799 tmp_dir.path().to_owned(),
1800 cx,
1801 )
1802 })?
1803 .await?;
1804 let dest_dir = RemotePathBuf::new(
1805 path_style
1806 .join(&response.tmp_dir, &missing_extension.id)
1807 .with_context(|| {
1808 format!(
1809 "failed to construct destination path: {:?}, {:?}",
1810 response.tmp_dir, missing_extension.id,
1811 )
1812 })?,
1813 path_style,
1814 );
1815 log::info!(
1816 "Uploading extension {} to {:?}",
1817 missing_extension.clone().id,
1818 dest_dir
1819 );
1820
1821 client
1822 .update(cx, |client, cx| {
1823 client.upload_directory(tmp_dir.path().to_owned(), dest_dir.clone(), cx)
1824 })?
1825 .await?;
1826
1827 log::info!(
1828 "Finished uploading extension {}",
1829 missing_extension.clone().id
1830 );
1831
1832 let result = client
1833 .update(cx, |client, _cx| {
1834 client.proto_client().request(proto::InstallExtension {
1835 tmp_dir: dest_dir.to_proto(),
1836 extension: Some(missing_extension.clone()),
1837 })
1838 })?
1839 .await;
1840
1841 if let Err(e) = result {
1842 log::error!(
1843 "Failed to install extension {}: {}",
1844 missing_extension.id,
1845 e
1846 );
1847 }
1848 }
1849
1850 anyhow::Ok(())
1851 }
1852
1853 pub async fn update_remote_clients(this: &WeakEntity<Self>, cx: &mut AsyncApp) -> Result<()> {
1854 let clients = this.update(cx, |this, _cx| {
1855 this.remote_clients.retain(|v| v.upgrade().is_some());
1856 this.remote_clients.clone()
1857 })?;
1858
1859 for client in clients {
1860 Self::sync_extensions_to_remotes(this, client, cx)
1861 .await
1862 .log_err();
1863 }
1864
1865 anyhow::Ok(())
1866 }
1867
1868 pub fn register_remote_client(
1869 &mut self,
1870 client: Entity<RemoteClient>,
1871 _cx: &mut Context<Self>,
1872 ) {
1873 self.remote_clients.push(client.downgrade());
1874 self.ssh_registered_tx.unbounded_send(()).ok();
1875 }
1876}
1877
1878fn load_plugin_queries(root_path: &Path) -> LanguageQueries {
1879 let mut result = LanguageQueries::default();
1880 if let Some(entries) = std::fs::read_dir(root_path).log_err() {
1881 for entry in entries {
1882 let Some(entry) = entry.log_err() else {
1883 continue;
1884 };
1885 let path = entry.path();
1886 if let Some(remainder) = path.strip_prefix(root_path).ok().and_then(|p| p.to_str()) {
1887 if !remainder.ends_with(".scm") {
1888 continue;
1889 }
1890 for (name, query) in QUERY_FILENAME_PREFIXES {
1891 if remainder.starts_with(name) {
1892 if let Some(contents) = std::fs::read_to_string(&path).log_err() {
1893 match query(&mut result) {
1894 None => *query(&mut result) = Some(contents.into()),
1895 Some(r) => r.to_mut().push_str(contents.as_ref()),
1896 }
1897 }
1898 break;
1899 }
1900 }
1901 }
1902 }
1903 }
1904 result
1905}