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