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 let fs = fs.clone();
1105 async move {
1106 builder
1107 .compile_extension(
1108 &extension_source_path,
1109 &mut extension_manifest,
1110 CompileExtensionOptions { release: false },
1111 fs,
1112 )
1113 .await
1114 }
1115 })
1116 .await
1117 .inspect_err(|error| {
1118 util::log_err(error);
1119 })?;
1120
1121 let output_path = &extensions_dir.join(extension_id.as_ref());
1122 if let Some(metadata) = fs.metadata(output_path).await? {
1123 if metadata.is_symlink {
1124 fs.remove_file(
1125 output_path,
1126 RemoveOptions {
1127 recursive: false,
1128 ignore_if_not_exists: true,
1129 },
1130 )
1131 .await?;
1132 } else {
1133 bail!("extension {extension_id} is still installed");
1134 }
1135 }
1136
1137 fs.create_symlink(output_path, extension_source_path)
1138 .await?;
1139
1140 this.update(cx, |this, cx| this.reload(None, cx))?.await;
1141 this.update(cx, |this, cx| {
1142 cx.emit(Event::ExtensionInstalled(extension_id.clone()));
1143 if let Some(events) = ExtensionEvents::try_global(cx)
1144 && let Some(manifest) = this.extension_manifest_for_id(&extension_id)
1145 {
1146 events.update(cx, |this, cx| {
1147 this.emit(extension::Event::ExtensionInstalled(manifest.clone()), cx)
1148 });
1149 }
1150 })?;
1151
1152 Ok(())
1153 })
1154 }
1155
1156 pub fn rebuild_dev_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
1157 let path = self.installed_dir.join(extension_id.as_ref());
1158 let builder = self.builder.clone();
1159 let fs = self.fs.clone();
1160
1161 match self.outstanding_operations.entry(extension_id.clone()) {
1162 btree_map::Entry::Occupied(_) => return,
1163 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Upgrade),
1164 };
1165
1166 cx.notify();
1167 let compile = cx.background_spawn(async move {
1168 let mut manifest = ExtensionManifest::load(fs.clone(), &path).await?;
1169 builder
1170 .compile_extension(
1171 &path,
1172 &mut manifest,
1173 CompileExtensionOptions { release: true },
1174 fs,
1175 )
1176 .await
1177 });
1178
1179 cx.spawn(async move |this, cx| {
1180 let result = compile.await;
1181
1182 this.update(cx, |this, cx| {
1183 this.outstanding_operations.remove(&extension_id);
1184 cx.notify();
1185 })?;
1186
1187 if result.is_ok() {
1188 this.update(cx, |this, cx| this.reload(Some(extension_id), cx))?
1189 .await;
1190 }
1191
1192 result
1193 })
1194 .detach_and_log_err(cx)
1195 }
1196
1197 /// Updates the set of installed extensions.
1198 ///
1199 /// First, this unloads any themes, languages, or grammars that are
1200 /// no longer in the manifest, or whose files have changed on disk.
1201 /// Then it loads any themes, languages, or grammars that are newly
1202 /// added to the manifest, or whose files have changed on disk.
1203 fn extensions_updated(
1204 &mut self,
1205 mut new_index: ExtensionIndex,
1206 cx: &mut Context<Self>,
1207 ) -> Task<()> {
1208 let old_index = &self.extension_index;
1209
1210 new_index
1211 .extensions
1212 .retain(|extension_id, _| !SUPPRESSED_EXTENSIONS.contains(&extension_id.as_ref()));
1213
1214 // Determine which extensions need to be loaded and unloaded, based
1215 // on the changes to the manifest and the extensions that we know have been
1216 // modified.
1217 let mut extensions_to_unload = Vec::default();
1218 let mut extensions_to_load = Vec::default();
1219 {
1220 let mut old_keys = old_index.extensions.iter().peekable();
1221 let mut new_keys = new_index.extensions.iter().peekable();
1222 loop {
1223 match (old_keys.peek(), new_keys.peek()) {
1224 (None, None) => break,
1225 (None, Some(_)) => {
1226 extensions_to_load.push(new_keys.next().unwrap().0.clone());
1227 }
1228 (Some(_), None) => {
1229 extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1230 }
1231 (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(new_key) {
1232 Ordering::Equal => {
1233 let (old_key, old_value) = old_keys.next().unwrap();
1234 let (new_key, new_value) = new_keys.next().unwrap();
1235 if old_value != new_value || self.modified_extensions.contains(old_key)
1236 {
1237 extensions_to_unload.push(old_key.clone());
1238 extensions_to_load.push(new_key.clone());
1239 }
1240 }
1241 Ordering::Less => {
1242 extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1243 }
1244 Ordering::Greater => {
1245 extensions_to_load.push(new_keys.next().unwrap().0.clone());
1246 }
1247 },
1248 }
1249 }
1250 self.modified_extensions.clear();
1251 }
1252
1253 if extensions_to_load.is_empty() && extensions_to_unload.is_empty() {
1254 self.reload_complete_senders.clear();
1255 return Task::ready(());
1256 }
1257
1258 let reload_count = extensions_to_unload
1259 .iter()
1260 .filter(|id| extensions_to_load.contains(id))
1261 .count();
1262
1263 log::info!(
1264 "extensions updated. loading {}, reloading {}, unloading {}",
1265 extensions_to_load.len() - reload_count,
1266 reload_count,
1267 extensions_to_unload.len() - reload_count
1268 );
1269
1270 let extension_ids = extensions_to_load
1271 .iter()
1272 .filter_map(|id| {
1273 Some((
1274 id.clone(),
1275 new_index.extensions.get(id)?.manifest.version.clone(),
1276 ))
1277 })
1278 .collect::<Vec<_>>();
1279
1280 telemetry::event!("Extensions Loaded", id_and_versions = extension_ids);
1281
1282 let themes_to_remove = old_index
1283 .themes
1284 .iter()
1285 .filter_map(|(name, entry)| {
1286 if extensions_to_unload.contains(&entry.extension) {
1287 Some(name.clone().into())
1288 } else {
1289 None
1290 }
1291 })
1292 .collect::<Vec<_>>();
1293 let icon_themes_to_remove = old_index
1294 .icon_themes
1295 .iter()
1296 .filter_map(|(name, entry)| {
1297 if extensions_to_unload.contains(&entry.extension) {
1298 Some(name.clone().into())
1299 } else {
1300 None
1301 }
1302 })
1303 .collect::<Vec<_>>();
1304 let languages_to_remove = old_index
1305 .languages
1306 .iter()
1307 .filter_map(|(name, entry)| {
1308 if extensions_to_unload.contains(&entry.extension) {
1309 Some(name.clone())
1310 } else {
1311 None
1312 }
1313 })
1314 .collect::<Vec<_>>();
1315 let mut grammars_to_remove = Vec::new();
1316 let mut server_removal_tasks = Vec::with_capacity(extensions_to_unload.len());
1317 for extension_id in &extensions_to_unload {
1318 let Some(extension) = old_index.extensions.get(extension_id) else {
1319 continue;
1320 };
1321 grammars_to_remove.extend(extension.manifest.grammars.keys().cloned());
1322 for (language_server_name, config) in &extension.manifest.language_servers {
1323 for language in config.languages() {
1324 server_removal_tasks.push(self.proxy.remove_language_server(
1325 &language,
1326 language_server_name,
1327 cx,
1328 ));
1329 }
1330 }
1331
1332 for server_id in extension.manifest.context_servers.keys() {
1333 self.proxy.unregister_context_server(server_id.clone(), cx);
1334 }
1335 for adapter in extension.manifest.debug_adapters.keys() {
1336 self.proxy.unregister_debug_adapter(adapter.clone());
1337 }
1338 for locator in extension.manifest.debug_locators.keys() {
1339 self.proxy.unregister_debug_locator(locator.clone());
1340 }
1341 for command_name in extension.manifest.slash_commands.keys() {
1342 self.proxy.unregister_slash_command(command_name.clone());
1343 }
1344 for provider_id in extension.manifest.language_model_providers.keys() {
1345 let full_provider_id: Arc<str> = format!("{}:{}", extension_id, provider_id).into();
1346 self.proxy
1347 .unregister_language_model_provider(full_provider_id, cx);
1348 }
1349 }
1350
1351 self.wasm_extensions
1352 .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
1353 self.proxy.remove_user_themes(themes_to_remove);
1354 self.proxy.remove_icon_themes(icon_themes_to_remove);
1355 self.proxy
1356 .remove_languages(&languages_to_remove, &grammars_to_remove);
1357
1358 let mut grammars_to_add = Vec::new();
1359 let mut themes_to_add = Vec::new();
1360 let mut icon_themes_to_add = Vec::new();
1361 let mut snippets_to_add = Vec::new();
1362 for extension_id in &extensions_to_load {
1363 let Some(extension) = new_index.extensions.get(extension_id) else {
1364 continue;
1365 };
1366
1367 grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
1368 let mut grammar_path = self.installed_dir.clone();
1369 grammar_path.extend([extension_id.as_ref(), "grammars"]);
1370 grammar_path.push(grammar_name.as_ref());
1371 grammar_path.set_extension("wasm");
1372 (grammar_name.clone(), grammar_path)
1373 }));
1374 themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
1375 let mut path = self.installed_dir.clone();
1376 path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1377 path
1378 }));
1379 icon_themes_to_add.extend(extension.manifest.icon_themes.iter().map(
1380 |icon_theme_path| {
1381 let mut path = self.installed_dir.clone();
1382 path.extend([Path::new(extension_id.as_ref()), icon_theme_path.as_path()]);
1383
1384 let mut icons_root_path = self.installed_dir.clone();
1385 icons_root_path.extend([Path::new(extension_id.as_ref())]);
1386
1387 (path, icons_root_path)
1388 },
1389 ));
1390 snippets_to_add.extend(extension.manifest.snippets.iter().map(|snippets_path| {
1391 let mut path = self.installed_dir.clone();
1392 path.extend([Path::new(extension_id.as_ref()), snippets_path.as_path()]);
1393 path
1394 }));
1395 }
1396
1397 self.proxy.register_grammars(grammars_to_add);
1398 let languages_to_add = new_index
1399 .languages
1400 .iter()
1401 .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
1402 .collect::<Vec<_>>();
1403 for (language_name, language) in languages_to_add {
1404 let mut language_path = self.installed_dir.clone();
1405 language_path.extend([
1406 Path::new(language.extension.as_ref()),
1407 language.path.as_path(),
1408 ]);
1409 self.proxy.register_language(
1410 language_name.clone(),
1411 language.grammar.clone(),
1412 language.matcher.clone(),
1413 language.hidden,
1414 Arc::new(move || {
1415 let config = std::fs::read_to_string(language_path.join("config.toml"))?;
1416 let config: LanguageConfig = ::toml::from_str(&config)?;
1417 let queries = load_plugin_queries(&language_path);
1418 let context_provider =
1419 std::fs::read_to_string(language_path.join("tasks.json"))
1420 .ok()
1421 .and_then(|contents| {
1422 let definitions =
1423 serde_json_lenient::from_str(&contents).log_err()?;
1424 Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1425 });
1426
1427 Ok(LoadedLanguage {
1428 config,
1429 queries,
1430 context_provider,
1431 toolchain_provider: None,
1432 manifest_name: None,
1433 })
1434 }),
1435 );
1436 }
1437
1438 let fs = self.fs.clone();
1439 let wasm_host = self.wasm_host.clone();
1440 let root_dir = self.installed_dir.clone();
1441 let proxy = self.proxy.clone();
1442 let extension_entries = extensions_to_load
1443 .iter()
1444 .filter_map(|name| new_index.extensions.get(name).cloned())
1445 .collect::<Vec<_>>();
1446 self.extension_index = new_index;
1447 cx.notify();
1448 cx.emit(Event::ExtensionsUpdated);
1449
1450 cx.spawn(async move |this, cx| {
1451 cx.background_spawn({
1452 let fs = fs.clone();
1453 async move {
1454 let _ = join_all(server_removal_tasks).await;
1455 for theme_path in themes_to_add {
1456 proxy
1457 .load_user_theme(theme_path, fs.clone())
1458 .await
1459 .log_err();
1460 }
1461
1462 for (icon_theme_path, icons_root_path) in icon_themes_to_add {
1463 proxy
1464 .load_icon_theme(icon_theme_path, icons_root_path, fs.clone())
1465 .await
1466 .log_err();
1467 }
1468
1469 for snippets_path in &snippets_to_add {
1470 match fs
1471 .load(snippets_path)
1472 .await
1473 .with_context(|| format!("Loading snippets from {snippets_path:?}"))
1474 {
1475 Ok(snippets_contents) => {
1476 proxy
1477 .register_snippet(snippets_path, &snippets_contents)
1478 .log_err();
1479 }
1480 Err(e) => log::error!("Cannot load snippets: {e:#}"),
1481 }
1482 }
1483 }
1484 })
1485 .await;
1486
1487 let mut wasm_extensions: Vec<(
1488 Arc<ExtensionManifest>,
1489 WasmExtension,
1490 Vec<LlmProviderWithModels>,
1491 )> = Vec::new();
1492 for extension in extension_entries {
1493 if extension.manifest.lib.kind.is_none() {
1494 continue;
1495 };
1496
1497 let extension_path = root_dir.join(extension.manifest.id.as_ref());
1498 let wasm_extension = WasmExtension::load(
1499 &extension_path,
1500 &extension.manifest,
1501 wasm_host.clone(),
1502 cx,
1503 )
1504 .await
1505 .with_context(|| format!("Loading extension from {extension_path:?}"));
1506
1507 match wasm_extension {
1508 Ok(wasm_extension) => {
1509 // Query for LLM providers if the manifest declares any
1510 let mut llm_providers_with_models = Vec::new();
1511 if !extension.manifest.language_model_providers.is_empty() {
1512 let providers_result = wasm_extension
1513 .call(|ext, store| {
1514 async move { ext.call_llm_providers(store).await }.boxed()
1515 })
1516 .await;
1517
1518 if let Ok(Ok(providers)) = providers_result {
1519 for provider_info in providers {
1520 let models_result = wasm_extension
1521 .call({
1522 let provider_id = provider_info.id.clone();
1523 |ext, store| {
1524 async move {
1525 ext.call_llm_provider_models(store, &provider_id)
1526 .await
1527 }
1528 .boxed()
1529 }
1530 })
1531 .await;
1532
1533 let models: Vec<LlmModelInfo> = match models_result {
1534 Ok(Ok(Ok(models))) => models,
1535 Ok(Ok(Err(e))) => {
1536 log::error!(
1537 "Failed to get models for LLM provider {} in extension {}: {}",
1538 provider_info.id,
1539 extension.manifest.id,
1540 e
1541 );
1542 Vec::new()
1543 }
1544 Ok(Err(e)) => {
1545 log::error!(
1546 "Wasm error calling llm_provider_models for {} in extension {}: {:?}",
1547 provider_info.id,
1548 extension.manifest.id,
1549 e
1550 );
1551 Vec::new()
1552 }
1553 Err(e) => {
1554 log::error!(
1555 "Extension call failed for llm_provider_models {} in extension {}: {:?}",
1556 provider_info.id,
1557 extension.manifest.id,
1558 e
1559 );
1560 Vec::new()
1561 }
1562 };
1563
1564 // Query initial authentication state
1565 let is_authenticated = wasm_extension
1566 .call({
1567 let provider_id = provider_info.id.clone();
1568 |ext, store| {
1569 async move {
1570 ext.call_llm_provider_is_authenticated(
1571 store,
1572 &provider_id,
1573 )
1574 .await
1575 }
1576 .boxed()
1577 }
1578 })
1579 .await
1580 .unwrap_or(Ok(false))
1581 .unwrap_or(false);
1582
1583 // Resolve icon path if provided
1584 let icon_path = provider_info.icon.as_ref().map(|icon| {
1585 let icon_file_path = extension_path.join(icon);
1586 // Canonicalize to resolve symlinks (dev extensions are symlinked)
1587 let absolute_icon_path = icon_file_path
1588 .canonicalize()
1589 .unwrap_or(icon_file_path)
1590 .to_string_lossy()
1591 .to_string();
1592 SharedString::from(absolute_icon_path)
1593 });
1594
1595 let provider_id_arc: Arc<str> =
1596 provider_info.id.as_str().into();
1597 let auth_config = extension
1598 .manifest
1599 .language_model_providers
1600 .get(&provider_id_arc)
1601 .and_then(|entry| entry.auth.clone());
1602
1603 llm_providers_with_models.push(LlmProviderWithModels {
1604 provider_info,
1605 models,
1606 is_authenticated,
1607 icon_path,
1608 auth_config,
1609 });
1610 }
1611 } else {
1612 log::error!(
1613 "Failed to get LLM providers from extension {}: {:?}",
1614 extension.manifest.id,
1615 providers_result
1616 );
1617 }
1618 }
1619
1620 wasm_extensions.push((
1621 extension.manifest.clone(),
1622 wasm_extension,
1623 llm_providers_with_models,
1624 ))
1625 }
1626 Err(e) => {
1627 log::error!(
1628 "Failed to load extension: {}, {:#}",
1629 extension.manifest.id,
1630 e
1631 );
1632 this.update(cx, |_, cx| {
1633 cx.emit(Event::ExtensionFailedToLoad(extension.manifest.id.clone()))
1634 })
1635 .ok();
1636 }
1637 }
1638 }
1639
1640 this.update(cx, |this, cx| {
1641 this.reload_complete_senders.clear();
1642
1643 for (manifest, wasm_extension, llm_providers_with_models) in &wasm_extensions {
1644 let extension = Arc::new(wasm_extension.clone());
1645
1646 for (language_server_id, language_server_config) in &manifest.language_servers {
1647 for language in language_server_config.languages() {
1648 this.proxy.register_language_server(
1649 extension.clone(),
1650 language_server_id.clone(),
1651 language.clone(),
1652 );
1653 }
1654 }
1655
1656 for (slash_command_name, slash_command) in &manifest.slash_commands {
1657 this.proxy.register_slash_command(
1658 extension.clone(),
1659 extension::SlashCommand {
1660 name: slash_command_name.to_string(),
1661 description: slash_command.description.to_string(),
1662 // We don't currently expose this as a configurable option, as it currently drives
1663 // the `menu_text` on the `SlashCommand` trait, which is not used for slash commands
1664 // defined in extensions, as they are not able to be added to the menu.
1665 tooltip_text: String::new(),
1666 requires_argument: slash_command.requires_argument,
1667 },
1668 );
1669 }
1670
1671 for id in manifest.context_servers.keys() {
1672 this.proxy
1673 .register_context_server(extension.clone(), id.clone(), cx);
1674 }
1675
1676 for (debug_adapter, meta) in &manifest.debug_adapters {
1677 let mut path = root_dir.clone();
1678 path.push(Path::new(manifest.id.as_ref()));
1679 if let Some(schema_path) = &meta.schema_path {
1680 path.push(schema_path);
1681 } else {
1682 path.push("debug_adapter_schemas");
1683 path.push(Path::new(debug_adapter.as_ref()).with_extension("json"));
1684 }
1685
1686 this.proxy.register_debug_adapter(
1687 extension.clone(),
1688 debug_adapter.clone(),
1689 &path,
1690 );
1691 }
1692
1693 for debug_adapter in manifest.debug_locators.keys() {
1694 this.proxy
1695 .register_debug_locator(extension.clone(), debug_adapter.clone());
1696 }
1697
1698 // Register LLM providers
1699 for llm_provider in llm_providers_with_models {
1700 let provider_id: Arc<str> =
1701 format!("{}:{}", manifest.id, llm_provider.provider_info.id).into();
1702 let wasm_ext = extension.as_ref().clone();
1703 let pinfo = llm_provider.provider_info.clone();
1704 let mods = llm_provider.models.clone();
1705 let auth = llm_provider.is_authenticated;
1706 let icon = llm_provider.icon_path.clone();
1707 let auth_config = llm_provider.auth_config.clone();
1708
1709 this.proxy.register_language_model_provider(
1710 provider_id.clone(),
1711 Box::new(move |cx: &mut App| {
1712 let provider = Arc::new(ExtensionLanguageModelProvider::new(
1713 wasm_ext, pinfo, mods, auth, icon, auth_config, cx,
1714 ));
1715 language_model::LanguageModelRegistry::global(cx).update(
1716 cx,
1717 |registry, cx| {
1718 registry.register_provider(provider, cx);
1719 },
1720 );
1721 }),
1722 cx,
1723 );
1724 }
1725 }
1726
1727 let wasm_extensions_without_llm: Vec<_> = wasm_extensions
1728 .into_iter()
1729 .map(|(manifest, ext, _)| (manifest, ext))
1730 .collect();
1731 this.wasm_extensions.extend(wasm_extensions_without_llm);
1732 this.proxy.set_extensions_loaded();
1733 this.proxy.reload_current_theme(cx);
1734 this.proxy.reload_current_icon_theme(cx);
1735
1736 if let Some(events) = ExtensionEvents::try_global(cx) {
1737 events.update(cx, |this, cx| {
1738 this.emit(extension::Event::ExtensionsInstalledChanged, cx)
1739 });
1740 }
1741 })
1742 .ok();
1743 })
1744 }
1745
1746 fn rebuild_extension_index(&self, cx: &mut Context<Self>) -> Task<ExtensionIndex> {
1747 let fs = self.fs.clone();
1748 let work_dir = self.wasm_host.work_dir.clone();
1749 let extensions_dir = self.installed_dir.clone();
1750 let index_path = self.index_path.clone();
1751 let proxy = self.proxy.clone();
1752 cx.background_spawn(async move {
1753 let start_time = Instant::now();
1754 let mut index = ExtensionIndex::default();
1755
1756 fs.create_dir(&work_dir).await.log_err();
1757 fs.create_dir(&extensions_dir).await.log_err();
1758
1759 let extension_paths = fs.read_dir(&extensions_dir).await;
1760 if let Ok(mut extension_paths) = extension_paths {
1761 while let Some(extension_dir) = extension_paths.next().await {
1762 let Ok(extension_dir) = extension_dir else {
1763 continue;
1764 };
1765
1766 if extension_dir
1767 .file_name()
1768 .is_some_and(|file_name| file_name == ".DS_Store")
1769 {
1770 continue;
1771 }
1772
1773 Self::add_extension_to_index(
1774 fs.clone(),
1775 extension_dir,
1776 &mut index,
1777 proxy.clone(),
1778 )
1779 .await
1780 .log_err();
1781 }
1782 }
1783
1784 if let Ok(index_json) = serde_json::to_string_pretty(&index) {
1785 fs.save(&index_path, &index_json.as_str().into(), Default::default())
1786 .await
1787 .context("failed to save extension index")
1788 .log_err();
1789 }
1790
1791 log::info!("rebuilt extension index in {:?}", start_time.elapsed());
1792 index
1793 })
1794 }
1795
1796 async fn add_extension_to_index(
1797 fs: Arc<dyn Fs>,
1798 extension_dir: PathBuf,
1799 index: &mut ExtensionIndex,
1800 proxy: Arc<ExtensionHostProxy>,
1801 ) -> Result<()> {
1802 let mut extension_manifest = ExtensionManifest::load(fs.clone(), &extension_dir).await?;
1803 let extension_id = extension_manifest.id.clone();
1804
1805 if SUPPRESSED_EXTENSIONS.contains(&extension_id.as_ref()) {
1806 return Ok(());
1807 }
1808
1809 // TODO: distinguish dev extensions more explicitly, by the absence
1810 // of a checksum file that we'll create when downloading normal extensions.
1811 let is_dev = fs
1812 .metadata(&extension_dir)
1813 .await?
1814 .context("directory does not exist")?
1815 .is_symlink;
1816
1817 if let Ok(mut language_paths) = fs.read_dir(&extension_dir.join("languages")).await {
1818 while let Some(language_path) = language_paths.next().await {
1819 let language_path = language_path?;
1820 let Ok(relative_path) = language_path.strip_prefix(&extension_dir) else {
1821 continue;
1822 };
1823 let Ok(Some(fs_metadata)) = fs.metadata(&language_path).await else {
1824 continue;
1825 };
1826 if !fs_metadata.is_dir {
1827 continue;
1828 }
1829 let config = fs.load(&language_path.join("config.toml")).await?;
1830 let config = ::toml::from_str::<LanguageConfig>(&config)?;
1831
1832 let relative_path = relative_path.to_path_buf();
1833 if !extension_manifest.languages.contains(&relative_path) {
1834 extension_manifest.languages.push(relative_path.clone());
1835 }
1836
1837 index.languages.insert(
1838 config.name.clone(),
1839 ExtensionIndexLanguageEntry {
1840 extension: extension_id.clone(),
1841 path: relative_path,
1842 matcher: config.matcher,
1843 hidden: config.hidden,
1844 grammar: config.grammar,
1845 },
1846 );
1847 }
1848 }
1849
1850 if let Ok(mut theme_paths) = fs.read_dir(&extension_dir.join("themes")).await {
1851 while let Some(theme_path) = theme_paths.next().await {
1852 let theme_path = theme_path?;
1853 let Ok(relative_path) = theme_path.strip_prefix(&extension_dir) else {
1854 continue;
1855 };
1856
1857 let Some(theme_families) = proxy
1858 .list_theme_names(theme_path.clone(), fs.clone())
1859 .await
1860 .log_err()
1861 else {
1862 continue;
1863 };
1864
1865 let relative_path = relative_path.to_path_buf();
1866 if !extension_manifest.themes.contains(&relative_path) {
1867 extension_manifest.themes.push(relative_path.clone());
1868 }
1869
1870 for theme_name in theme_families {
1871 index.themes.insert(
1872 theme_name.into(),
1873 ExtensionIndexThemeEntry {
1874 extension: extension_id.clone(),
1875 path: relative_path.clone(),
1876 },
1877 );
1878 }
1879 }
1880 }
1881
1882 if let Ok(mut icon_theme_paths) = fs.read_dir(&extension_dir.join("icon_themes")).await {
1883 while let Some(icon_theme_path) = icon_theme_paths.next().await {
1884 let icon_theme_path = icon_theme_path?;
1885 let Ok(relative_path) = icon_theme_path.strip_prefix(&extension_dir) else {
1886 continue;
1887 };
1888
1889 let Some(icon_theme_families) = proxy
1890 .list_icon_theme_names(icon_theme_path.clone(), fs.clone())
1891 .await
1892 .log_err()
1893 else {
1894 continue;
1895 };
1896
1897 let relative_path = relative_path.to_path_buf();
1898 if !extension_manifest.icon_themes.contains(&relative_path) {
1899 extension_manifest.icon_themes.push(relative_path.clone());
1900 }
1901
1902 for icon_theme_name in icon_theme_families {
1903 index.icon_themes.insert(
1904 icon_theme_name.into(),
1905 ExtensionIndexIconThemeEntry {
1906 extension: extension_id.clone(),
1907 path: relative_path.clone(),
1908 },
1909 );
1910 }
1911 }
1912 }
1913
1914 let extension_wasm_path = extension_dir.join("extension.wasm");
1915 if fs.is_file(&extension_wasm_path).await {
1916 extension_manifest
1917 .lib
1918 .kind
1919 .get_or_insert(ExtensionLibraryKind::Rust);
1920 }
1921
1922 index.extensions.insert(
1923 extension_id.clone(),
1924 ExtensionIndexEntry {
1925 dev: is_dev,
1926 manifest: Arc::new(extension_manifest),
1927 },
1928 );
1929
1930 Ok(())
1931 }
1932
1933 fn prepare_remote_extension(
1934 &mut self,
1935 extension_id: Arc<str>,
1936 is_dev: bool,
1937 tmp_dir: PathBuf,
1938 cx: &mut Context<Self>,
1939 ) -> Task<Result<()>> {
1940 let src_dir = self.extensions_dir().join(extension_id.as_ref());
1941 let Some(loaded_extension) = self.extension_index.extensions.get(&extension_id).cloned()
1942 else {
1943 return Task::ready(Err(anyhow!("extension no longer installed")));
1944 };
1945 let fs = self.fs.clone();
1946 cx.background_spawn(async move {
1947 const EXTENSION_TOML: &str = "extension.toml";
1948 const EXTENSION_WASM: &str = "extension.wasm";
1949 const CONFIG_TOML: &str = "config.toml";
1950
1951 if is_dev {
1952 let manifest_toml = toml::to_string(&loaded_extension.manifest)?;
1953 fs.save(
1954 &tmp_dir.join(EXTENSION_TOML),
1955 &Rope::from(manifest_toml),
1956 language::LineEnding::Unix,
1957 )
1958 .await?;
1959 } else {
1960 fs.copy_file(
1961 &src_dir.join(EXTENSION_TOML),
1962 &tmp_dir.join(EXTENSION_TOML),
1963 fs::CopyOptions::default(),
1964 )
1965 .await?
1966 }
1967
1968 if fs.is_file(&src_dir.join(EXTENSION_WASM)).await {
1969 fs.copy_file(
1970 &src_dir.join(EXTENSION_WASM),
1971 &tmp_dir.join(EXTENSION_WASM),
1972 fs::CopyOptions::default(),
1973 )
1974 .await?
1975 }
1976
1977 for language_path in loaded_extension.manifest.languages.iter() {
1978 if fs
1979 .is_file(&src_dir.join(language_path).join(CONFIG_TOML))
1980 .await
1981 {
1982 fs.create_dir(&tmp_dir.join(language_path)).await?;
1983 fs.copy_file(
1984 &src_dir.join(language_path).join(CONFIG_TOML),
1985 &tmp_dir.join(language_path).join(CONFIG_TOML),
1986 fs::CopyOptions::default(),
1987 )
1988 .await?
1989 }
1990 }
1991
1992 for (adapter_name, meta) in loaded_extension.manifest.debug_adapters.iter() {
1993 let schema_path = &extension::build_debug_adapter_schema_path(adapter_name, meta);
1994
1995 if fs.is_file(&src_dir.join(schema_path)).await {
1996 if let Some(parent) = schema_path.parent() {
1997 fs.create_dir(&tmp_dir.join(parent)).await?
1998 }
1999 fs.copy_file(
2000 &src_dir.join(schema_path),
2001 &tmp_dir.join(schema_path),
2002 fs::CopyOptions::default(),
2003 )
2004 .await?
2005 }
2006 }
2007
2008 Ok(())
2009 })
2010 }
2011
2012 async fn sync_extensions_to_remotes(
2013 this: &WeakEntity<Self>,
2014 client: WeakEntity<RemoteClient>,
2015 cx: &mut AsyncApp,
2016 ) -> Result<()> {
2017 let extensions = this.update(cx, |this, _cx| {
2018 this.extension_index
2019 .extensions
2020 .iter()
2021 .filter_map(|(id, entry)| {
2022 if !entry.manifest.allow_remote_load() {
2023 return None;
2024 }
2025 Some(proto::Extension {
2026 id: id.to_string(),
2027 version: entry.manifest.version.to_string(),
2028 dev: entry.dev,
2029 })
2030 })
2031 .collect()
2032 })?;
2033
2034 let response = client
2035 .update(cx, |client, _cx| {
2036 client
2037 .proto_client()
2038 .request(proto::SyncExtensions { extensions })
2039 })?
2040 .await?;
2041 let path_style = client.read_with(cx, |client, _| client.path_style())?;
2042
2043 for missing_extension in response.missing_extensions.into_iter() {
2044 let tmp_dir = tempfile::tempdir()?;
2045 this.update(cx, |this, cx| {
2046 this.prepare_remote_extension(
2047 missing_extension.id.clone().into(),
2048 missing_extension.dev,
2049 tmp_dir.path().to_owned(),
2050 cx,
2051 )
2052 })?
2053 .await?;
2054 let dest_dir = RemotePathBuf::new(
2055 path_style
2056 .join(&response.tmp_dir, &missing_extension.id)
2057 .with_context(|| {
2058 format!(
2059 "failed to construct destination path: {:?}, {:?}",
2060 response.tmp_dir, missing_extension.id,
2061 )
2062 })?,
2063 path_style,
2064 );
2065 log::info!(
2066 "Uploading extension {} to {:?}",
2067 missing_extension.clone().id,
2068 dest_dir
2069 );
2070
2071 client
2072 .update(cx, |client, cx| {
2073 client.upload_directory(tmp_dir.path().to_owned(), dest_dir.clone(), cx)
2074 })?
2075 .await?;
2076
2077 log::info!(
2078 "Finished uploading extension {}",
2079 missing_extension.clone().id
2080 );
2081
2082 let result = client
2083 .update(cx, |client, _cx| {
2084 client.proto_client().request(proto::InstallExtension {
2085 tmp_dir: dest_dir.to_proto(),
2086 extension: Some(missing_extension.clone()),
2087 })
2088 })?
2089 .await;
2090
2091 if let Err(e) = result {
2092 log::error!(
2093 "Failed to install extension {}: {}",
2094 missing_extension.id,
2095 e
2096 );
2097 }
2098 }
2099
2100 anyhow::Ok(())
2101 }
2102
2103 pub async fn update_remote_clients(this: &WeakEntity<Self>, cx: &mut AsyncApp) -> Result<()> {
2104 let clients = this.update(cx, |this, _cx| {
2105 this.remote_clients.retain(|v| v.upgrade().is_some());
2106 this.remote_clients.clone()
2107 })?;
2108
2109 for client in clients {
2110 Self::sync_extensions_to_remotes(this, client, cx)
2111 .await
2112 .log_err();
2113 }
2114
2115 anyhow::Ok(())
2116 }
2117
2118 pub fn register_remote_client(
2119 &mut self,
2120 client: Entity<RemoteClient>,
2121 _cx: &mut Context<Self>,
2122 ) {
2123 self.remote_clients.push(client.downgrade());
2124 self.ssh_registered_tx.unbounded_send(()).ok();
2125 }
2126}
2127
2128fn load_plugin_queries(root_path: &Path) -> LanguageQueries {
2129 let mut result = LanguageQueries::default();
2130 if let Some(entries) = std::fs::read_dir(root_path).log_err() {
2131 for entry in entries {
2132 let Some(entry) = entry.log_err() else {
2133 continue;
2134 };
2135 let path = entry.path();
2136 if let Some(remainder) = path.strip_prefix(root_path).ok().and_then(|p| p.to_str()) {
2137 if !remainder.ends_with(".scm") {
2138 continue;
2139 }
2140 for (name, query) in QUERY_FILENAME_PREFIXES {
2141 if remainder.starts_with(name) {
2142 if let Some(contents) = std::fs::read_to_string(&path).log_err() {
2143 match query(&mut result) {
2144 None => *query(&mut result) = Some(contents.into()),
2145 Some(r) => r.to_mut().push_str(contents.as_ref()),
2146 }
2147 }
2148 break;
2149 }
2150 }
2151 }
2152 }
2153 }
2154 result
2155}