Skip to repository content

tenant.openagents/omega

No repository description is available.

OpenAgents Git authority 2026-07-28T02:36:59.425Z Public web read
NIP-34 coordinate30617:7649603503856e5148d571eac2766b288a8ff1e9e35d380337a1d2b0015b4f92:omega
MaintainersHidden in public view
References2 branches · 1 tag
Read-only clonegit clone https://openagents.com/git/tenant.openagents/omega.git
Browse files

extension_host.rs

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