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