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