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