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