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 "openrouter",
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 // When enabled, this checks if an extension exists locally in the repo's extensions/
716 // directory and installs it as a dev extension instead of fetching from the registry.
717 // This is useful for testing auto-installed extensions before they've been published.
718 // Set to `true` only during local development/testing of new auto-install extensions.
719 #[cfg(debug_assertions)]
720 const DEBUG_ALLOW_UNPUBLISHED_AUTO_EXTENSIONS: bool = false;
721
722 #[cfg(debug_assertions)]
723 if DEBUG_ALLOW_UNPUBLISHED_AUTO_EXTENSIONS {
724 let local_extension_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
725 .parent()
726 .unwrap()
727 .parent()
728 .unwrap()
729 .join("extensions")
730 .join(extension_id.as_ref());
731
732 if local_extension_path.exists() {
733 // Force-remove existing extension directory if it exists and isn't a symlink
734 // This handles the case where the extension was previously installed from the registry
735 if let Some(installed_dir) = this
736 .update(cx, |this, _cx| this.installed_dir.clone())
737 .ok()
738 {
739 let existing_path = installed_dir.join(extension_id.as_ref());
740 if existing_path.exists() {
741 let metadata = std::fs::symlink_metadata(&existing_path);
742 let is_symlink = metadata.map(|m| m.is_symlink()).unwrap_or(false);
743 if !is_symlink {
744 if let Err(e) = std::fs::remove_dir_all(&existing_path) {
745 log::error!(
746 "Failed to remove existing extension directory {:?}: {}",
747 existing_path,
748 e
749 );
750 }
751 }
752 }
753 }
754
755 if let Some(task) = this
756 .update(cx, |this, cx| {
757 this.install_dev_extension(local_extension_path, cx)
758 })
759 .ok()
760 {
761 task.await.log_err();
762 }
763 continue;
764 }
765 }
766
767 this.update(cx, |this, cx| {
768 this.install_latest_extension(extension_id.clone(), cx);
769 })
770 .ok();
771 }
772 })
773 .detach();
774 }
775
776 pub fn check_for_updates(&mut self, cx: &mut Context<Self>) {
777 let task = self.fetch_extensions_with_update_available(cx);
778 cx.spawn(async move |this, cx| Self::upgrade_extensions(this, task.await?, cx).await)
779 .detach();
780 }
781
782 async fn upgrade_extensions(
783 this: WeakEntity<Self>,
784 extensions: Vec<ExtensionMetadata>,
785 cx: &mut AsyncApp,
786 ) -> Result<()> {
787 for extension in extensions {
788 let task = this.update(cx, |this, cx| {
789 if let Some(installed_extension) =
790 this.extension_index.extensions.get(&extension.id)
791 {
792 let installed_version =
793 Version::from_str(&installed_extension.manifest.version).ok()?;
794 let latest_version = Version::from_str(&extension.manifest.version).ok()?;
795
796 if installed_version >= latest_version {
797 return None;
798 }
799 }
800
801 Some(this.upgrade_extension(extension.id, extension.manifest.version, cx))
802 })?;
803
804 if let Some(task) = task {
805 task.await.log_err();
806 }
807 }
808 anyhow::Ok(())
809 }
810
811 fn fetch_extensions_from_api(
812 &self,
813 path: &str,
814 query: &[(&str, &str)],
815 cx: &mut Context<ExtensionStore>,
816 ) -> Task<Result<Vec<ExtensionMetadata>>> {
817 let url = self.http_client.build_zed_api_url(path, query);
818 let http_client = self.http_client.clone();
819 cx.spawn(async move |_, _| {
820 let mut response = http_client
821 .get(url?.as_ref(), AsyncBody::empty(), true)
822 .await?;
823
824 let mut body = Vec::new();
825 response
826 .body_mut()
827 .read_to_end(&mut body)
828 .await
829 .context("error reading extensions")?;
830
831 if response.status().is_client_error() {
832 let text = String::from_utf8_lossy(body.as_slice());
833 bail!(
834 "status error {}, response: {text:?}",
835 response.status().as_u16()
836 );
837 }
838
839 let mut response: GetExtensionsResponse = serde_json::from_slice(&body)?;
840
841 response
842 .data
843 .retain(|extension| !SUPPRESSED_EXTENSIONS.contains(&extension.id.as_ref()));
844
845 Ok(response.data)
846 })
847 }
848
849 pub fn install_extension(
850 &mut self,
851 extension_id: Arc<str>,
852 version: Arc<str>,
853 cx: &mut Context<Self>,
854 ) {
855 self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Install, cx)
856 .detach_and_log_err(cx);
857 }
858
859 fn install_or_upgrade_extension_at_endpoint(
860 &mut self,
861 extension_id: Arc<str>,
862 url: Url,
863 operation: ExtensionOperation,
864 cx: &mut Context<Self>,
865 ) -> Task<Result<()>> {
866 let extension_dir = self.installed_dir.join(extension_id.as_ref());
867 let http_client = self.http_client.clone();
868 let fs = self.fs.clone();
869
870 match self.outstanding_operations.entry(extension_id.clone()) {
871 btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
872 btree_map::Entry::Vacant(e) => e.insert(operation),
873 };
874 cx.notify();
875
876 cx.spawn(async move |this, cx| {
877 let _finish = cx.on_drop(&this, {
878 let extension_id = extension_id.clone();
879 move |this, cx| {
880 this.outstanding_operations.remove(extension_id.as_ref());
881 cx.notify();
882 }
883 });
884
885 let mut response = http_client
886 .get(url.as_ref(), Default::default(), true)
887 .await
888 .context("downloading extension")?;
889
890 fs.remove_dir(
891 &extension_dir,
892 RemoveOptions {
893 recursive: true,
894 ignore_if_not_exists: true,
895 },
896 )
897 .await?;
898
899 let content_length = response
900 .headers()
901 .get(http_client::http::header::CONTENT_LENGTH)
902 .and_then(|value| value.to_str().ok()?.parse::<usize>().ok());
903
904 let mut body = BufReader::new(response.body_mut());
905 let mut tar_gz_bytes = Vec::new();
906 body.read_to_end(&mut tar_gz_bytes).await?;
907
908 if let Some(content_length) = content_length {
909 let actual_len = tar_gz_bytes.len();
910 if content_length != actual_len {
911 bail!(concat!(
912 "downloaded extension size {actual_len} ",
913 "does not match content length {content_length}"
914 ));
915 }
916 }
917 let decompressed_bytes = GzipDecoder::new(BufReader::new(tar_gz_bytes.as_slice()));
918 let archive = Archive::new(decompressed_bytes);
919 archive.unpack(extension_dir).await?;
920 this.update(cx, |this, cx| this.reload(Some(extension_id.clone()), cx))?
921 .await;
922
923 if let ExtensionOperation::Install = operation {
924 this.update(cx, |this, cx| {
925 // Check for legacy LLM provider migration
926 if let Some(manifest) = this.extension_manifest_for_id(&extension_id) {
927 migrate_legacy_llm_provider_env_var(&manifest, cx);
928 }
929
930 cx.emit(Event::ExtensionInstalled(extension_id.clone()));
931 if let Some(events) = ExtensionEvents::try_global(cx)
932 && let Some(manifest) = this.extension_manifest_for_id(&extension_id)
933 {
934 events.update(cx, |this, cx| {
935 this.emit(extension::Event::ExtensionInstalled(manifest.clone()), cx)
936 });
937 }
938
939 // Run extension-specific migrations
940 copilot_migration::migrate_copilot_credentials_if_needed(&extension_id, cx);
941 anthropic_migration::migrate_anthropic_credentials_if_needed(&extension_id, cx);
942 google_ai_migration::migrate_google_ai_credentials_if_needed(&extension_id, cx);
943 openai_migration::migrate_openai_credentials_if_needed(&extension_id, cx);
944 open_router_migration::migrate_open_router_credentials_if_needed(
945 &extension_id,
946 cx,
947 );
948 })
949 .ok();
950 }
951
952 anyhow::Ok(())
953 })
954 }
955
956 pub fn install_latest_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
957 let schema_versions = schema_version_range();
958 let wasm_api_versions = wasm_api_version_range(ReleaseChannel::global(cx));
959
960 let Some(url) = self
961 .http_client
962 .build_zed_api_url(
963 &format!("/extensions/{extension_id}/download"),
964 &[
965 ("min_schema_version", &schema_versions.start().to_string()),
966 ("max_schema_version", &schema_versions.end().to_string()),
967 (
968 "min_wasm_api_version",
969 &wasm_api_versions.start().to_string(),
970 ),
971 ("max_wasm_api_version", &wasm_api_versions.end().to_string()),
972 ],
973 )
974 .log_err()
975 else {
976 return;
977 };
978
979 self.install_or_upgrade_extension_at_endpoint(
980 extension_id,
981 url,
982 ExtensionOperation::Install,
983 cx,
984 )
985 .detach_and_log_err(cx);
986 }
987
988 pub fn upgrade_extension(
989 &mut self,
990 extension_id: Arc<str>,
991 version: Arc<str>,
992 cx: &mut Context<Self>,
993 ) -> Task<Result<()>> {
994 self.install_or_upgrade_extension(extension_id, version, ExtensionOperation::Upgrade, cx)
995 }
996
997 fn install_or_upgrade_extension(
998 &mut self,
999 extension_id: Arc<str>,
1000 version: Arc<str>,
1001 operation: ExtensionOperation,
1002 cx: &mut Context<Self>,
1003 ) -> Task<Result<()>> {
1004 let Some(url) = self
1005 .http_client
1006 .build_zed_api_url(
1007 &format!("/extensions/{extension_id}/{version}/download"),
1008 &[],
1009 )
1010 .log_err()
1011 else {
1012 return Task::ready(Ok(()));
1013 };
1014
1015 self.install_or_upgrade_extension_at_endpoint(extension_id, url, operation, cx)
1016 }
1017
1018 pub fn uninstall_extension(
1019 &mut self,
1020 extension_id: Arc<str>,
1021 cx: &mut Context<Self>,
1022 ) -> Task<Result<()>> {
1023 let extension_dir = self.installed_dir.join(extension_id.as_ref());
1024 let work_dir = self.wasm_host.work_dir.join(extension_id.as_ref());
1025 let fs = self.fs.clone();
1026
1027 let extension_manifest = self.extension_manifest_for_id(&extension_id).cloned();
1028
1029 match self.outstanding_operations.entry(extension_id.clone()) {
1030 btree_map::Entry::Occupied(_) => return Task::ready(Ok(())),
1031 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Remove),
1032 };
1033
1034 cx.spawn(async move |extension_store, cx| {
1035 let _finish = cx.on_drop(&extension_store, {
1036 let extension_id = extension_id.clone();
1037 move |this, cx| {
1038 this.outstanding_operations.remove(extension_id.as_ref());
1039 cx.notify();
1040 }
1041 });
1042
1043 fs.remove_dir(
1044 &extension_dir,
1045 RemoveOptions {
1046 recursive: true,
1047 ignore_if_not_exists: true,
1048 },
1049 )
1050 .await
1051 .with_context(|| format!("Removing extension dir {extension_dir:?}"))?;
1052
1053 extension_store
1054 .update(cx, |extension_store, cx| extension_store.reload(None, cx))?
1055 .await;
1056
1057 // There's a race between wasm extension fully stopping and the directory removal.
1058 // On Windows, it's impossible to remove a directory that has a process running in it.
1059 for i in 0..3 {
1060 cx.background_executor()
1061 .timer(Duration::from_millis(i * 100))
1062 .await;
1063 let removal_result = fs
1064 .remove_dir(
1065 &work_dir,
1066 RemoveOptions {
1067 recursive: true,
1068 ignore_if_not_exists: true,
1069 },
1070 )
1071 .await;
1072 match removal_result {
1073 Ok(()) => break,
1074 Err(e) => {
1075 if i == 2 {
1076 log::error!("Failed to remove extension work dir {work_dir:?} : {e}");
1077 }
1078 }
1079 }
1080 }
1081
1082 extension_store.update(cx, |_, cx| {
1083 cx.emit(Event::ExtensionUninstalled(extension_id.clone()));
1084 if let Some(events) = ExtensionEvents::try_global(cx)
1085 && let Some(manifest) = extension_manifest
1086 {
1087 events.update(cx, |this, cx| {
1088 this.emit(extension::Event::ExtensionUninstalled(manifest.clone()), cx)
1089 });
1090 }
1091 })?;
1092
1093 anyhow::Ok(())
1094 })
1095 }
1096
1097 pub fn install_dev_extension(
1098 &mut self,
1099 extension_source_path: PathBuf,
1100 cx: &mut Context<Self>,
1101 ) -> Task<Result<()>> {
1102 let extensions_dir = self.extensions_dir();
1103 let fs = self.fs.clone();
1104 let builder = self.builder.clone();
1105
1106 cx.spawn(async move |this, cx| {
1107 let mut extension_manifest =
1108 ExtensionManifest::load(fs.clone(), &extension_source_path).await?;
1109 let extension_id = extension_manifest.id.clone();
1110
1111 if let Some(uninstall_task) = this
1112 .update(cx, |this, cx| {
1113 this.extension_index
1114 .extensions
1115 .get(extension_id.as_ref())
1116 .is_some_and(|index_entry| !index_entry.dev)
1117 .then(|| this.uninstall_extension(extension_id.clone(), cx))
1118 })
1119 .ok()
1120 .flatten()
1121 {
1122 uninstall_task.await.log_err();
1123 }
1124
1125 if !this.update(cx, |this, cx| {
1126 match this.outstanding_operations.entry(extension_id.clone()) {
1127 btree_map::Entry::Occupied(_) => return false,
1128 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Install),
1129 };
1130 cx.notify();
1131 true
1132 })? {
1133 return Ok(());
1134 }
1135
1136 let _finish = cx.on_drop(&this, {
1137 let extension_id = extension_id.clone();
1138 move |this, cx| {
1139 this.outstanding_operations.remove(extension_id.as_ref());
1140 cx.notify();
1141 }
1142 });
1143
1144 cx.background_spawn({
1145 let extension_source_path = extension_source_path.clone();
1146 let fs = fs.clone();
1147 async move {
1148 builder
1149 .compile_extension(
1150 &extension_source_path,
1151 &mut extension_manifest,
1152 CompileExtensionOptions { release: false },
1153 fs,
1154 )
1155 .await
1156 }
1157 })
1158 .await
1159 .inspect_err(|error| {
1160 util::log_err(error);
1161 })?;
1162
1163 let output_path = &extensions_dir.join(extension_id.as_ref());
1164 if let Some(metadata) = fs.metadata(output_path).await? {
1165 if metadata.is_symlink {
1166 fs.remove_file(
1167 output_path,
1168 RemoveOptions {
1169 recursive: false,
1170 ignore_if_not_exists: true,
1171 },
1172 )
1173 .await?;
1174 } else {
1175 bail!("extension {extension_id} is still installed");
1176 }
1177 }
1178
1179 fs.create_symlink(output_path, extension_source_path)
1180 .await?;
1181
1182 this.update(cx, |this, cx| this.reload(None, cx))?.await;
1183 this.update(cx, |this, cx| {
1184 // Run migration for legacy LLM provider env vars
1185 if let Some(manifest) = this.extension_manifest_for_id(&extension_id) {
1186 migrate_legacy_llm_provider_env_var(&manifest, cx);
1187 }
1188
1189 cx.emit(Event::ExtensionInstalled(extension_id.clone()));
1190 if let Some(events) = ExtensionEvents::try_global(cx)
1191 && let Some(manifest) = this.extension_manifest_for_id(&extension_id)
1192 {
1193 events.update(cx, |this, cx| {
1194 this.emit(extension::Event::ExtensionInstalled(manifest.clone()), cx)
1195 });
1196 }
1197 })?;
1198
1199 Ok(())
1200 })
1201 }
1202
1203 pub fn rebuild_dev_extension(&mut self, extension_id: Arc<str>, cx: &mut Context<Self>) {
1204 let path = self.installed_dir.join(extension_id.as_ref());
1205 let builder = self.builder.clone();
1206 let fs = self.fs.clone();
1207
1208 match self.outstanding_operations.entry(extension_id.clone()) {
1209 btree_map::Entry::Occupied(_) => return,
1210 btree_map::Entry::Vacant(e) => e.insert(ExtensionOperation::Upgrade),
1211 };
1212
1213 cx.notify();
1214 let compile = cx.background_spawn(async move {
1215 let mut manifest = ExtensionManifest::load(fs.clone(), &path).await?;
1216 builder
1217 .compile_extension(
1218 &path,
1219 &mut manifest,
1220 CompileExtensionOptions { release: true },
1221 fs,
1222 )
1223 .await
1224 });
1225
1226 cx.spawn(async move |this, cx| {
1227 let result = compile.await;
1228
1229 this.update(cx, |this, cx| {
1230 this.outstanding_operations.remove(&extension_id);
1231 cx.notify();
1232 })?;
1233
1234 if result.is_ok() {
1235 this.update(cx, |this, cx| this.reload(Some(extension_id), cx))?
1236 .await;
1237 }
1238
1239 result
1240 })
1241 .detach_and_log_err(cx)
1242 }
1243
1244 /// Updates the set of installed extensions.
1245 ///
1246 /// First, this unloads any themes, languages, or grammars that are
1247 /// no longer in the manifest, or whose files have changed on disk.
1248 /// Then it loads any themes, languages, or grammars that are newly
1249 /// added to the manifest, or whose files have changed on disk.
1250 fn extensions_updated(
1251 &mut self,
1252 mut new_index: ExtensionIndex,
1253 cx: &mut Context<Self>,
1254 ) -> Task<()> {
1255 let old_index = &self.extension_index;
1256
1257 new_index
1258 .extensions
1259 .retain(|extension_id, _| !SUPPRESSED_EXTENSIONS.contains(&extension_id.as_ref()));
1260
1261 // Determine which extensions need to be loaded and unloaded, based
1262 // on the changes to the manifest and the extensions that we know have been
1263 // modified.
1264 let mut extensions_to_unload = Vec::default();
1265 let mut extensions_to_load = Vec::default();
1266 {
1267 let mut old_keys = old_index.extensions.iter().peekable();
1268 let mut new_keys = new_index.extensions.iter().peekable();
1269 loop {
1270 match (old_keys.peek(), new_keys.peek()) {
1271 (None, None) => break,
1272 (None, Some(_)) => {
1273 extensions_to_load.push(new_keys.next().unwrap().0.clone());
1274 }
1275 (Some(_), None) => {
1276 extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1277 }
1278 (Some((old_key, _)), Some((new_key, _))) => match old_key.cmp(new_key) {
1279 Ordering::Equal => {
1280 let (old_key, old_value) = old_keys.next().unwrap();
1281 let (new_key, new_value) = new_keys.next().unwrap();
1282 if old_value != new_value || self.modified_extensions.contains(old_key)
1283 {
1284 extensions_to_unload.push(old_key.clone());
1285 extensions_to_load.push(new_key.clone());
1286 }
1287 }
1288 Ordering::Less => {
1289 extensions_to_unload.push(old_keys.next().unwrap().0.clone());
1290 }
1291 Ordering::Greater => {
1292 extensions_to_load.push(new_keys.next().unwrap().0.clone());
1293 }
1294 },
1295 }
1296 }
1297 self.modified_extensions.clear();
1298 }
1299
1300 if extensions_to_load.is_empty() && extensions_to_unload.is_empty() {
1301 self.reload_complete_senders.clear();
1302 return Task::ready(());
1303 }
1304
1305 let extension_ids = extensions_to_load
1306 .iter()
1307 .filter_map(|id| {
1308 Some((
1309 id.clone(),
1310 new_index.extensions.get(id)?.manifest.version.clone(),
1311 ))
1312 })
1313 .collect::<Vec<_>>();
1314
1315 telemetry::event!("Extensions Loaded", id_and_versions = extension_ids);
1316
1317 let themes_to_remove = old_index
1318 .themes
1319 .iter()
1320 .filter_map(|(name, entry)| {
1321 if extensions_to_unload.contains(&entry.extension) {
1322 Some(name.clone().into())
1323 } else {
1324 None
1325 }
1326 })
1327 .collect::<Vec<_>>();
1328 let icon_themes_to_remove = old_index
1329 .icon_themes
1330 .iter()
1331 .filter_map(|(name, entry)| {
1332 if extensions_to_unload.contains(&entry.extension) {
1333 Some(name.clone().into())
1334 } else {
1335 None
1336 }
1337 })
1338 .collect::<Vec<_>>();
1339 let languages_to_remove = old_index
1340 .languages
1341 .iter()
1342 .filter_map(|(name, entry)| {
1343 if extensions_to_unload.contains(&entry.extension) {
1344 Some(name.clone())
1345 } else {
1346 None
1347 }
1348 })
1349 .collect::<Vec<_>>();
1350 let mut grammars_to_remove = Vec::new();
1351 let mut server_removal_tasks = Vec::with_capacity(extensions_to_unload.len());
1352 for extension_id in &extensions_to_unload {
1353 let Some(extension) = old_index.extensions.get(extension_id) else {
1354 continue;
1355 };
1356 grammars_to_remove.extend(extension.manifest.grammars.keys().cloned());
1357 for (language_server_name, config) in &extension.manifest.language_servers {
1358 for language in config.languages() {
1359 server_removal_tasks.push(self.proxy.remove_language_server(
1360 &language,
1361 language_server_name,
1362 cx,
1363 ));
1364 }
1365 }
1366
1367 for server_id in extension.manifest.context_servers.keys() {
1368 self.proxy.unregister_context_server(server_id.clone(), cx);
1369 }
1370 for adapter in extension.manifest.debug_adapters.keys() {
1371 self.proxy.unregister_debug_adapter(adapter.clone());
1372 }
1373 for locator in extension.manifest.debug_locators.keys() {
1374 self.proxy.unregister_debug_locator(locator.clone());
1375 }
1376 for command_name in extension.manifest.slash_commands.keys() {
1377 self.proxy.unregister_slash_command(command_name.clone());
1378 }
1379 for provider_id in extension.manifest.language_model_providers.keys() {
1380 let full_provider_id: Arc<str> = format!("{}:{}", extension_id, provider_id).into();
1381 self.proxy
1382 .unregister_language_model_provider(full_provider_id, cx);
1383 }
1384 }
1385
1386 self.wasm_extensions
1387 .retain(|(extension, _)| !extensions_to_unload.contains(&extension.id));
1388 self.proxy.remove_user_themes(themes_to_remove);
1389 self.proxy.remove_icon_themes(icon_themes_to_remove);
1390 self.proxy
1391 .remove_languages(&languages_to_remove, &grammars_to_remove);
1392
1393 let mut grammars_to_add = Vec::new();
1394 let mut themes_to_add = Vec::new();
1395 let mut icon_themes_to_add = Vec::new();
1396 let mut snippets_to_add = Vec::new();
1397 for extension_id in &extensions_to_load {
1398 let Some(extension) = new_index.extensions.get(extension_id) else {
1399 continue;
1400 };
1401
1402 grammars_to_add.extend(extension.manifest.grammars.keys().map(|grammar_name| {
1403 let mut grammar_path = self.installed_dir.clone();
1404 grammar_path.extend([extension_id.as_ref(), "grammars"]);
1405 grammar_path.push(grammar_name.as_ref());
1406 grammar_path.set_extension("wasm");
1407 (grammar_name.clone(), grammar_path)
1408 }));
1409 themes_to_add.extend(extension.manifest.themes.iter().map(|theme_path| {
1410 let mut path = self.installed_dir.clone();
1411 path.extend([Path::new(extension_id.as_ref()), theme_path.as_path()]);
1412 path
1413 }));
1414 icon_themes_to_add.extend(extension.manifest.icon_themes.iter().map(
1415 |icon_theme_path| {
1416 let mut path = self.installed_dir.clone();
1417 path.extend([Path::new(extension_id.as_ref()), icon_theme_path.as_path()]);
1418
1419 let mut icons_root_path = self.installed_dir.clone();
1420 icons_root_path.extend([Path::new(extension_id.as_ref())]);
1421
1422 (path, icons_root_path)
1423 },
1424 ));
1425 snippets_to_add.extend(extension.manifest.snippets.iter().map(|snippets_path| {
1426 let mut path = self.installed_dir.clone();
1427 path.extend([Path::new(extension_id.as_ref()), snippets_path.as_path()]);
1428 path
1429 }));
1430 }
1431
1432 self.proxy.register_grammars(grammars_to_add);
1433 let languages_to_add = new_index
1434 .languages
1435 .iter()
1436 .filter(|(_, entry)| extensions_to_load.contains(&entry.extension))
1437 .collect::<Vec<_>>();
1438 for (language_name, language) in languages_to_add {
1439 let mut language_path = self.installed_dir.clone();
1440 language_path.extend([
1441 Path::new(language.extension.as_ref()),
1442 language.path.as_path(),
1443 ]);
1444 self.proxy.register_language(
1445 language_name.clone(),
1446 language.grammar.clone(),
1447 language.matcher.clone(),
1448 language.hidden,
1449 Arc::new(move || {
1450 let config = std::fs::read_to_string(language_path.join("config.toml"))?;
1451 let config: LanguageConfig = ::toml::from_str(&config)?;
1452 let queries = load_plugin_queries(&language_path);
1453 let context_provider =
1454 std::fs::read_to_string(language_path.join("tasks.json"))
1455 .ok()
1456 .and_then(|contents| {
1457 let definitions =
1458 serde_json_lenient::from_str(&contents).log_err()?;
1459 Some(Arc::new(ContextProviderWithTasks::new(definitions)) as Arc<_>)
1460 });
1461
1462 Ok(LoadedLanguage {
1463 config,
1464 queries,
1465 context_provider,
1466 toolchain_provider: None,
1467 manifest_name: None,
1468 })
1469 }),
1470 );
1471 }
1472
1473 let fs = self.fs.clone();
1474 let wasm_host = self.wasm_host.clone();
1475 let root_dir = self.installed_dir.clone();
1476 let proxy = self.proxy.clone();
1477 let extension_entries = extensions_to_load
1478 .iter()
1479 .filter_map(|name| new_index.extensions.get(name).cloned())
1480 .collect::<Vec<_>>();
1481 self.extension_index = new_index;
1482 cx.notify();
1483 cx.emit(Event::ExtensionsUpdated);
1484
1485 cx.spawn(async move |this, cx| {
1486 cx.background_spawn({
1487 let fs = fs.clone();
1488 async move {
1489 let _ = join_all(server_removal_tasks).await;
1490 for theme_path in themes_to_add {
1491 proxy
1492 .load_user_theme(theme_path, fs.clone())
1493 .await
1494 .log_err();
1495 }
1496
1497 for (icon_theme_path, icons_root_path) in icon_themes_to_add {
1498 proxy
1499 .load_icon_theme(icon_theme_path, icons_root_path, fs.clone())
1500 .await
1501 .log_err();
1502 }
1503
1504 for snippets_path in &snippets_to_add {
1505 match fs
1506 .load(snippets_path)
1507 .await
1508 .with_context(|| format!("Loading snippets from {snippets_path:?}"))
1509 {
1510 Ok(snippets_contents) => {
1511 proxy
1512 .register_snippet(snippets_path, &snippets_contents)
1513 .log_err();
1514 }
1515 Err(e) => log::error!("Cannot load snippets: {e:#}"),
1516 }
1517 }
1518 }
1519 })
1520 .await;
1521
1522 let mut wasm_extensions: Vec<(
1523 Arc<ExtensionManifest>,
1524 WasmExtension,
1525 Vec<LlmProviderWithModels>,
1526 )> = Vec::new();
1527 for extension in extension_entries {
1528 if extension.manifest.lib.kind.is_none() {
1529 continue;
1530 };
1531
1532 let extension_path = root_dir.join(extension.manifest.id.as_ref());
1533 let wasm_extension = WasmExtension::load(
1534 &extension_path,
1535 &extension.manifest,
1536 wasm_host.clone(),
1537 cx,
1538 )
1539 .await
1540 .with_context(|| format!("Loading extension from {extension_path:?}"));
1541
1542 match wasm_extension {
1543 Ok(wasm_extension) => {
1544 // Query for LLM providers if the manifest declares any
1545 let mut llm_providers_with_models = Vec::new();
1546 if !extension.manifest.language_model_providers.is_empty() {
1547 let providers_result = wasm_extension
1548 .call(|ext, store| {
1549 async move { ext.call_llm_providers(store).await }.boxed()
1550 })
1551 .await;
1552
1553 if let Ok(Ok(providers)) = providers_result {
1554 for provider_info in providers {
1555 let models_result = wasm_extension
1556 .call({
1557 let provider_id = provider_info.id.clone();
1558 |ext, store| {
1559 async move {
1560 ext.call_llm_provider_models(store, &provider_id)
1561 .await
1562 }
1563 .boxed()
1564 }
1565 })
1566 .await;
1567
1568 let models: Vec<LlmModelInfo> = match models_result {
1569 Ok(Ok(Ok(models))) => models,
1570 Ok(Ok(Err(e))) => {
1571 log::error!(
1572 "Failed to get models for LLM provider {} in extension {}: {}",
1573 provider_info.id,
1574 extension.manifest.id,
1575 e
1576 );
1577 Vec::new()
1578 }
1579 Ok(Err(e)) => {
1580 log::error!(
1581 "Wasm error calling llm_provider_models for {} in extension {}: {:?}",
1582 provider_info.id,
1583 extension.manifest.id,
1584 e
1585 );
1586 Vec::new()
1587 }
1588 Err(e) => {
1589 log::error!(
1590 "Extension call failed for llm_provider_models {} in extension {}: {:?}",
1591 provider_info.id,
1592 extension.manifest.id,
1593 e
1594 );
1595 Vec::new()
1596 }
1597 };
1598
1599 // Query initial authentication state
1600 let is_authenticated = wasm_extension
1601 .call({
1602 let provider_id = provider_info.id.clone();
1603 |ext, store| {
1604 async move {
1605 ext.call_llm_provider_is_authenticated(
1606 store,
1607 &provider_id,
1608 )
1609 .await
1610 }
1611 .boxed()
1612 }
1613 })
1614 .await
1615 .unwrap_or(Ok(false))
1616 .unwrap_or(false);
1617
1618 // Resolve icon path if provided
1619 let icon_path = provider_info.icon.as_ref().map(|icon| {
1620 let icon_file_path = extension_path.join(icon);
1621 // Canonicalize to resolve symlinks (dev extensions are symlinked)
1622 let absolute_icon_path = icon_file_path
1623 .canonicalize()
1624 .unwrap_or(icon_file_path)
1625 .to_string_lossy()
1626 .to_string();
1627 SharedString::from(absolute_icon_path)
1628 });
1629
1630 let provider_id_arc: Arc<str> =
1631 provider_info.id.as_str().into();
1632 let auth_config = extension
1633 .manifest
1634 .language_model_providers
1635 .get(&provider_id_arc)
1636 .and_then(|entry| entry.auth.clone());
1637
1638 llm_providers_with_models.push(LlmProviderWithModels {
1639 provider_info,
1640 models,
1641 is_authenticated,
1642 icon_path,
1643 auth_config,
1644 });
1645 }
1646 } else {
1647 log::error!(
1648 "Failed to get LLM providers from extension {}: {:?}",
1649 extension.manifest.id,
1650 providers_result
1651 );
1652 }
1653 }
1654
1655 wasm_extensions.push((
1656 extension.manifest.clone(),
1657 wasm_extension,
1658 llm_providers_with_models,
1659 ))
1660 }
1661 Err(e) => {
1662 log::error!(
1663 "Failed to load extension: {}, {:#}",
1664 extension.manifest.id,
1665 e
1666 );
1667 this.update(cx, |_, cx| {
1668 cx.emit(Event::ExtensionFailedToLoad(extension.manifest.id.clone()))
1669 })
1670 .ok();
1671 }
1672 }
1673 }
1674
1675 this.update(cx, |this, cx| {
1676 this.reload_complete_senders.clear();
1677
1678 for (manifest, wasm_extension, llm_providers_with_models) in &wasm_extensions {
1679 let extension = Arc::new(wasm_extension.clone());
1680
1681 for (language_server_id, language_server_config) in &manifest.language_servers {
1682 for language in language_server_config.languages() {
1683 this.proxy.register_language_server(
1684 extension.clone(),
1685 language_server_id.clone(),
1686 language.clone(),
1687 );
1688 }
1689 }
1690
1691 for (slash_command_name, slash_command) in &manifest.slash_commands {
1692 this.proxy.register_slash_command(
1693 extension.clone(),
1694 extension::SlashCommand {
1695 name: slash_command_name.to_string(),
1696 description: slash_command.description.to_string(),
1697 // We don't currently expose this as a configurable option, as it currently drives
1698 // the `menu_text` on the `SlashCommand` trait, which is not used for slash commands
1699 // defined in extensions, as they are not able to be added to the menu.
1700 tooltip_text: String::new(),
1701 requires_argument: slash_command.requires_argument,
1702 },
1703 );
1704 }
1705
1706 for id in manifest.context_servers.keys() {
1707 this.proxy
1708 .register_context_server(extension.clone(), id.clone(), cx);
1709 }
1710
1711 for (debug_adapter, meta) in &manifest.debug_adapters {
1712 let mut path = root_dir.clone();
1713 path.push(Path::new(manifest.id.as_ref()));
1714 if let Some(schema_path) = &meta.schema_path {
1715 path.push(schema_path);
1716 } else {
1717 path.push("debug_adapter_schemas");
1718 path.push(Path::new(debug_adapter.as_ref()).with_extension("json"));
1719 }
1720
1721 this.proxy.register_debug_adapter(
1722 extension.clone(),
1723 debug_adapter.clone(),
1724 &path,
1725 );
1726 }
1727
1728 for debug_adapter in manifest.debug_locators.keys() {
1729 this.proxy
1730 .register_debug_locator(extension.clone(), debug_adapter.clone());
1731 }
1732
1733 // Register LLM providers
1734 for llm_provider in llm_providers_with_models {
1735 let provider_id: Arc<str> =
1736 format!("{}:{}", manifest.id, llm_provider.provider_info.id).into();
1737 let wasm_ext = extension.as_ref().clone();
1738 let pinfo = llm_provider.provider_info.clone();
1739 let mods = llm_provider.models.clone();
1740 let auth = llm_provider.is_authenticated;
1741 let icon = llm_provider.icon_path.clone();
1742 let auth_config = llm_provider.auth_config.clone();
1743
1744 this.proxy.register_language_model_provider(
1745 provider_id.clone(),
1746 Box::new(move |cx: &mut App| {
1747 let provider = Arc::new(ExtensionLanguageModelProvider::new(
1748 wasm_ext, pinfo, mods, auth, icon, auth_config, cx,
1749 ));
1750 language_model::LanguageModelRegistry::global(cx).update(
1751 cx,
1752 |registry, cx| {
1753 registry.register_provider(provider, cx);
1754 },
1755 );
1756 }),
1757 cx,
1758 );
1759 }
1760 }
1761
1762 let wasm_extensions_without_llm: Vec<_> = wasm_extensions
1763 .into_iter()
1764 .map(|(manifest, ext, _)| (manifest, ext))
1765 .collect();
1766 this.wasm_extensions.extend(wasm_extensions_without_llm);
1767 this.proxy.set_extensions_loaded();
1768 this.proxy.reload_current_theme(cx);
1769 this.proxy.reload_current_icon_theme(cx);
1770
1771 if let Some(events) = ExtensionEvents::try_global(cx) {
1772 events.update(cx, |this, cx| {
1773 this.emit(extension::Event::ExtensionsInstalledChanged, cx)
1774 });
1775 }
1776 })
1777 .ok();
1778 })
1779 }
1780
1781 fn rebuild_extension_index(&self, cx: &mut Context<Self>) -> Task<ExtensionIndex> {
1782 let fs = self.fs.clone();
1783 let work_dir = self.wasm_host.work_dir.clone();
1784 let extensions_dir = self.installed_dir.clone();
1785 let index_path = self.index_path.clone();
1786 let proxy = self.proxy.clone();
1787 cx.background_spawn(async move {
1788 let mut index = ExtensionIndex::default();
1789
1790 fs.create_dir(&work_dir).await.log_err();
1791 fs.create_dir(&extensions_dir).await.log_err();
1792
1793 let extension_paths = fs.read_dir(&extensions_dir).await;
1794 if let Ok(mut extension_paths) = extension_paths {
1795 while let Some(extension_dir) = extension_paths.next().await {
1796 let Ok(extension_dir) = extension_dir else {
1797 continue;
1798 };
1799
1800 if extension_dir
1801 .file_name()
1802 .is_some_and(|file_name| file_name == ".DS_Store")
1803 {
1804 continue;
1805 }
1806
1807 Self::add_extension_to_index(
1808 fs.clone(),
1809 extension_dir,
1810 &mut index,
1811 proxy.clone(),
1812 )
1813 .await
1814 .log_err();
1815 }
1816 }
1817
1818 if let Ok(index_json) = serde_json::to_string_pretty(&index) {
1819 fs.save(&index_path, &index_json.as_str().into(), Default::default())
1820 .await
1821 .context("failed to save extension index")
1822 .log_err();
1823 }
1824
1825 index
1826 })
1827 }
1828
1829 async fn add_extension_to_index(
1830 fs: Arc<dyn Fs>,
1831 extension_dir: PathBuf,
1832 index: &mut ExtensionIndex,
1833 proxy: Arc<ExtensionHostProxy>,
1834 ) -> Result<()> {
1835 let mut extension_manifest = ExtensionManifest::load(fs.clone(), &extension_dir).await?;
1836 let extension_id = extension_manifest.id.clone();
1837
1838 if SUPPRESSED_EXTENSIONS.contains(&extension_id.as_ref()) {
1839 return Ok(());
1840 }
1841
1842 // TODO: distinguish dev extensions more explicitly, by the absence
1843 // of a checksum file that we'll create when downloading normal extensions.
1844 let is_dev = fs
1845 .metadata(&extension_dir)
1846 .await?
1847 .context("directory does not exist")?
1848 .is_symlink;
1849
1850 if let Ok(mut language_paths) = fs.read_dir(&extension_dir.join("languages")).await {
1851 while let Some(language_path) = language_paths.next().await {
1852 let language_path = language_path?;
1853 let Ok(relative_path) = language_path.strip_prefix(&extension_dir) else {
1854 continue;
1855 };
1856 let Ok(Some(fs_metadata)) = fs.metadata(&language_path).await else {
1857 continue;
1858 };
1859 if !fs_metadata.is_dir {
1860 continue;
1861 }
1862 let config = fs.load(&language_path.join("config.toml")).await?;
1863 let config = ::toml::from_str::<LanguageConfig>(&config)?;
1864
1865 let relative_path = relative_path.to_path_buf();
1866 if !extension_manifest.languages.contains(&relative_path) {
1867 extension_manifest.languages.push(relative_path.clone());
1868 }
1869
1870 index.languages.insert(
1871 config.name.clone(),
1872 ExtensionIndexLanguageEntry {
1873 extension: extension_id.clone(),
1874 path: relative_path,
1875 matcher: config.matcher,
1876 hidden: config.hidden,
1877 grammar: config.grammar,
1878 },
1879 );
1880 }
1881 }
1882
1883 if let Ok(mut theme_paths) = fs.read_dir(&extension_dir.join("themes")).await {
1884 while let Some(theme_path) = theme_paths.next().await {
1885 let theme_path = theme_path?;
1886 let Ok(relative_path) = theme_path.strip_prefix(&extension_dir) else {
1887 continue;
1888 };
1889
1890 let Some(theme_families) = proxy
1891 .list_theme_names(theme_path.clone(), fs.clone())
1892 .await
1893 .log_err()
1894 else {
1895 continue;
1896 };
1897
1898 let relative_path = relative_path.to_path_buf();
1899 if !extension_manifest.themes.contains(&relative_path) {
1900 extension_manifest.themes.push(relative_path.clone());
1901 }
1902
1903 for theme_name in theme_families {
1904 index.themes.insert(
1905 theme_name.into(),
1906 ExtensionIndexThemeEntry {
1907 extension: extension_id.clone(),
1908 path: relative_path.clone(),
1909 },
1910 );
1911 }
1912 }
1913 }
1914
1915 if let Ok(mut icon_theme_paths) = fs.read_dir(&extension_dir.join("icon_themes")).await {
1916 while let Some(icon_theme_path) = icon_theme_paths.next().await {
1917 let icon_theme_path = icon_theme_path?;
1918 let Ok(relative_path) = icon_theme_path.strip_prefix(&extension_dir) else {
1919 continue;
1920 };
1921
1922 let Some(icon_theme_families) = proxy
1923 .list_icon_theme_names(icon_theme_path.clone(), fs.clone())
1924 .await
1925 .log_err()
1926 else {
1927 continue;
1928 };
1929
1930 let relative_path = relative_path.to_path_buf();
1931 if !extension_manifest.icon_themes.contains(&relative_path) {
1932 extension_manifest.icon_themes.push(relative_path.clone());
1933 }
1934
1935 for icon_theme_name in icon_theme_families {
1936 index.icon_themes.insert(
1937 icon_theme_name.into(),
1938 ExtensionIndexIconThemeEntry {
1939 extension: extension_id.clone(),
1940 path: relative_path.clone(),
1941 },
1942 );
1943 }
1944 }
1945 }
1946
1947 let extension_wasm_path = extension_dir.join("extension.wasm");
1948 if fs.is_file(&extension_wasm_path).await {
1949 extension_manifest
1950 .lib
1951 .kind
1952 .get_or_insert(ExtensionLibraryKind::Rust);
1953 }
1954
1955 index.extensions.insert(
1956 extension_id.clone(),
1957 ExtensionIndexEntry {
1958 dev: is_dev,
1959 manifest: Arc::new(extension_manifest),
1960 },
1961 );
1962
1963 Ok(())
1964 }
1965
1966 fn prepare_remote_extension(
1967 &mut self,
1968 extension_id: Arc<str>,
1969 is_dev: bool,
1970 tmp_dir: PathBuf,
1971 cx: &mut Context<Self>,
1972 ) -> Task<Result<()>> {
1973 let src_dir = self.extensions_dir().join(extension_id.as_ref());
1974 let Some(loaded_extension) = self.extension_index.extensions.get(&extension_id).cloned()
1975 else {
1976 return Task::ready(Err(anyhow!("extension no longer installed")));
1977 };
1978 let fs = self.fs.clone();
1979 cx.background_spawn(async move {
1980 const EXTENSION_TOML: &str = "extension.toml";
1981 const EXTENSION_WASM: &str = "extension.wasm";
1982 const CONFIG_TOML: &str = "config.toml";
1983
1984 if is_dev {
1985 let manifest_toml = toml::to_string(&loaded_extension.manifest)?;
1986 fs.save(
1987 &tmp_dir.join(EXTENSION_TOML),
1988 &Rope::from(manifest_toml),
1989 language::LineEnding::Unix,
1990 )
1991 .await?;
1992 } else {
1993 fs.copy_file(
1994 &src_dir.join(EXTENSION_TOML),
1995 &tmp_dir.join(EXTENSION_TOML),
1996 fs::CopyOptions::default(),
1997 )
1998 .await?
1999 }
2000
2001 if fs.is_file(&src_dir.join(EXTENSION_WASM)).await {
2002 fs.copy_file(
2003 &src_dir.join(EXTENSION_WASM),
2004 &tmp_dir.join(EXTENSION_WASM),
2005 fs::CopyOptions::default(),
2006 )
2007 .await?
2008 }
2009
2010 for language_path in loaded_extension.manifest.languages.iter() {
2011 if fs
2012 .is_file(&src_dir.join(language_path).join(CONFIG_TOML))
2013 .await
2014 {
2015 fs.create_dir(&tmp_dir.join(language_path)).await?;
2016 fs.copy_file(
2017 &src_dir.join(language_path).join(CONFIG_TOML),
2018 &tmp_dir.join(language_path).join(CONFIG_TOML),
2019 fs::CopyOptions::default(),
2020 )
2021 .await?
2022 }
2023 }
2024
2025 for (adapter_name, meta) in loaded_extension.manifest.debug_adapters.iter() {
2026 let schema_path = &extension::build_debug_adapter_schema_path(adapter_name, meta);
2027
2028 if fs.is_file(&src_dir.join(schema_path)).await {
2029 if let Some(parent) = schema_path.parent() {
2030 fs.create_dir(&tmp_dir.join(parent)).await?
2031 }
2032 fs.copy_file(
2033 &src_dir.join(schema_path),
2034 &tmp_dir.join(schema_path),
2035 fs::CopyOptions::default(),
2036 )
2037 .await?
2038 }
2039 }
2040
2041 Ok(())
2042 })
2043 }
2044
2045 async fn sync_extensions_to_remotes(
2046 this: &WeakEntity<Self>,
2047 client: WeakEntity<RemoteClient>,
2048 cx: &mut AsyncApp,
2049 ) -> Result<()> {
2050 let extensions = this.update(cx, |this, _cx| {
2051 this.extension_index
2052 .extensions
2053 .iter()
2054 .filter_map(|(id, entry)| {
2055 if !entry.manifest.allow_remote_load() {
2056 return None;
2057 }
2058 Some(proto::Extension {
2059 id: id.to_string(),
2060 version: entry.manifest.version.to_string(),
2061 dev: entry.dev,
2062 })
2063 })
2064 .collect()
2065 })?;
2066
2067 let response = client
2068 .update(cx, |client, _cx| {
2069 client
2070 .proto_client()
2071 .request(proto::SyncExtensions { extensions })
2072 })?
2073 .await?;
2074 let path_style = client.read_with(cx, |client, _| client.path_style())?;
2075
2076 for missing_extension in response.missing_extensions.into_iter() {
2077 let tmp_dir = tempfile::tempdir()?;
2078 this.update(cx, |this, cx| {
2079 this.prepare_remote_extension(
2080 missing_extension.id.clone().into(),
2081 missing_extension.dev,
2082 tmp_dir.path().to_owned(),
2083 cx,
2084 )
2085 })?
2086 .await?;
2087 let dest_dir = RemotePathBuf::new(
2088 path_style
2089 .join(&response.tmp_dir, &missing_extension.id)
2090 .with_context(|| {
2091 format!(
2092 "failed to construct destination path: {:?}, {:?}",
2093 response.tmp_dir, missing_extension.id,
2094 )
2095 })?,
2096 path_style,
2097 );
2098
2099 client
2100 .update(cx, |client, cx| {
2101 client.upload_directory(tmp_dir.path().to_owned(), dest_dir.clone(), cx)
2102 })?
2103 .await?;
2104
2105 let result = client
2106 .update(cx, |client, _cx| {
2107 client.proto_client().request(proto::InstallExtension {
2108 tmp_dir: dest_dir.to_proto(),
2109 extension: Some(missing_extension.clone()),
2110 })
2111 })?
2112 .await;
2113
2114 if let Err(e) = result {
2115 log::error!(
2116 "Failed to install extension {}: {}",
2117 missing_extension.id,
2118 e
2119 );
2120 }
2121 }
2122
2123 anyhow::Ok(())
2124 }
2125
2126 pub async fn update_remote_clients(this: &WeakEntity<Self>, cx: &mut AsyncApp) -> Result<()> {
2127 let clients = this.update(cx, |this, _cx| {
2128 this.remote_clients.retain(|v| v.upgrade().is_some());
2129 this.remote_clients.clone()
2130 })?;
2131
2132 for client in clients {
2133 Self::sync_extensions_to_remotes(this, client, cx)
2134 .await
2135 .log_err();
2136 }
2137
2138 anyhow::Ok(())
2139 }
2140
2141 pub fn register_remote_client(
2142 &mut self,
2143 client: Entity<RemoteClient>,
2144 _cx: &mut Context<Self>,
2145 ) {
2146 self.remote_clients.push(client.downgrade());
2147 self.ssh_registered_tx.unbounded_send(()).ok();
2148 }
2149}
2150
2151fn load_plugin_queries(root_path: &Path) -> LanguageQueries {
2152 let mut result = LanguageQueries::default();
2153 if let Some(entries) = std::fs::read_dir(root_path).log_err() {
2154 for entry in entries {
2155 let Some(entry) = entry.log_err() else {
2156 continue;
2157 };
2158 let path = entry.path();
2159 if let Some(remainder) = path.strip_prefix(root_path).ok().and_then(|p| p.to_str()) {
2160 if !remainder.ends_with(".scm") {
2161 continue;
2162 }
2163 for (name, query) in QUERY_FILENAME_PREFIXES {
2164 if remainder.starts_with(name) {
2165 if let Some(contents) = std::fs::read_to_string(&path).log_err() {
2166 match query(&mut result) {
2167 None => *query(&mut result) = Some(contents.into()),
2168 Some(r) => r.to_mut().push_str(contents.as_ref()),
2169 }
2170 }
2171 break;
2172 }
2173 }
2174 }
2175 }
2176 }
2177 result
2178}