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