agent_registry_ui.rs

  1use std::ops::Range;
  2
  3use collections::HashMap;
  4use editor::{Editor, EditorElement, EditorStyle};
  5use fs::Fs;
  6use gpui::{
  7    AnyElement, App, Context, Entity, EventEmitter, Focusable, KeyContext, ParentElement, Render,
  8    RenderOnce, SharedString, Styled, TextStyle, UniformListScrollHandle, Window, point,
  9    uniform_list,
 10};
 11use project::agent_server_store::{AllAgentServersSettings, CustomAgentServerSettings};
 12use project::{AgentRegistryStore, RegistryAgent};
 13use settings::{Settings, SettingsStore, update_settings_file};
 14use theme::ThemeSettings;
 15use ui::{
 16    ButtonStyle, ScrollableHandle, ToggleButtonGroup, ToggleButtonGroupSize,
 17    ToggleButtonGroupStyle, ToggleButtonSimple, Tooltip, WithScrollbar, prelude::*,
 18};
 19use workspace::{
 20    Workspace,
 21    item::{Item, ItemEvent},
 22};
 23
 24/// Registry IDs for built-in agents that Zed already provides first-class support for.
 25/// These are filtered out of the ACP Agent Registry UI to avoid showing duplicates.
 26const BUILT_IN_REGISTRY_IDS: [&str; 3] = ["claude-acp", "codex-acp", "gemini"];
 27
 28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 29enum RegistryFilter {
 30    All,
 31    Installed,
 32    NotInstalled,
 33}
 34
 35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
 36enum RegistryInstallStatus {
 37    NotInstalled,
 38    InstalledRegistry,
 39    InstalledCustom,
 40    InstalledExtension,
 41}
 42
 43#[derive(IntoElement)]
 44struct AgentRegistryCard {
 45    children: Vec<AnyElement>,
 46}
 47
 48impl AgentRegistryCard {
 49    fn new() -> Self {
 50        Self {
 51            children: Vec::new(),
 52        }
 53    }
 54}
 55
 56impl ParentElement for AgentRegistryCard {
 57    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>) {
 58        self.children.extend(elements)
 59    }
 60}
 61
 62impl RenderOnce for AgentRegistryCard {
 63    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
 64        div().w_full().child(
 65            v_flex()
 66                .mt_4()
 67                .w_full()
 68                .min_h(rems_from_px(110.))
 69                .p_3()
 70                .gap_2()
 71                .bg(cx.theme().colors().elevated_surface_background.opacity(0.5))
 72                .border_1()
 73                .border_color(cx.theme().colors().border_variant)
 74                .rounded_md()
 75                .children(self.children),
 76        )
 77    }
 78}
 79
 80pub struct AgentRegistryPage {
 81    registry_store: Entity<AgentRegistryStore>,
 82    list: UniformListScrollHandle,
 83    registry_agents: Vec<RegistryAgent>,
 84    filtered_registry_indices: Vec<usize>,
 85    installed_statuses: HashMap<String, RegistryInstallStatus>,
 86    query_editor: Entity<Editor>,
 87    filter: RegistryFilter,
 88    _subscriptions: Vec<gpui::Subscription>,
 89}
 90
 91impl AgentRegistryPage {
 92    pub fn new(
 93        _workspace: &Workspace,
 94        window: &mut Window,
 95        cx: &mut Context<Workspace>,
 96    ) -> Entity<Self> {
 97        cx.new(|cx| {
 98            let registry_store = AgentRegistryStore::global(cx);
 99            let query_editor = cx.new(|cx| {
100                let mut input = Editor::single_line(window, cx);
101                input.set_placeholder_text("Search agents...", window, cx);
102                input
103            });
104            cx.subscribe(&query_editor, Self::on_query_change).detach();
105
106            let mut subscriptions = Vec::new();
107            subscriptions.push(cx.observe(&registry_store, |this, _, cx| {
108                this.reload_registry_agents(cx);
109            }));
110            subscriptions.push(cx.observe_global::<SettingsStore>(|this, cx| {
111                this.filter_registry_agents(cx);
112            }));
113
114            let mut this = Self {
115                registry_store,
116                list: UniformListScrollHandle::new(),
117                registry_agents: Vec::new(),
118                filtered_registry_indices: Vec::new(),
119                installed_statuses: HashMap::default(),
120                query_editor,
121                filter: RegistryFilter::All,
122                _subscriptions: subscriptions,
123            };
124
125            this.reload_registry_agents(cx);
126            this.registry_store
127                .update(cx, |store, cx| store.refresh(cx));
128
129            this
130        })
131    }
132
133    fn reload_registry_agents(&mut self, cx: &mut Context<Self>) {
134        self.registry_agents = self.registry_store.read(cx).agents().to_vec();
135        self.registry_agents.sort_by(|left, right| {
136            left.name()
137                .as_ref()
138                .cmp(right.name().as_ref())
139                .then_with(|| left.id().as_ref().cmp(right.id().as_ref()))
140        });
141        self.filter_registry_agents(cx);
142    }
143
144    fn refresh_installed_statuses(&mut self, cx: &mut Context<Self>) {
145        let settings = cx
146            .global::<SettingsStore>()
147            .get::<AllAgentServersSettings>(None);
148        self.installed_statuses.clear();
149        for (id, settings) in &settings.custom {
150            let status = match settings {
151                CustomAgentServerSettings::Registry { .. } => {
152                    RegistryInstallStatus::InstalledRegistry
153                }
154                CustomAgentServerSettings::Custom { .. } => RegistryInstallStatus::InstalledCustom,
155                CustomAgentServerSettings::Extension { .. } => {
156                    RegistryInstallStatus::InstalledExtension
157                }
158            };
159            self.installed_statuses.insert(id.clone(), status);
160        }
161    }
162
163    fn install_status(&self, id: &str) -> RegistryInstallStatus {
164        self.installed_statuses
165            .get(id)
166            .copied()
167            .unwrap_or(RegistryInstallStatus::NotInstalled)
168    }
169
170    fn search_query(&self, cx: &mut App) -> Option<String> {
171        let search = self.query_editor.read(cx).text(cx);
172        if search.trim().is_empty() {
173            None
174        } else {
175            Some(search)
176        }
177    }
178
179    fn filter_registry_agents(&mut self, cx: &mut Context<Self>) {
180        self.refresh_installed_statuses(cx);
181        let search = self.search_query(cx).map(|search| search.to_lowercase());
182        let filter = self.filter;
183        let installed_statuses = self.installed_statuses.clone();
184
185        let filtered_indices = self
186            .registry_agents
187            .iter()
188            .enumerate()
189            .filter(|(_, agent)| {
190                // Filter out built-in agents since they already appear in the main
191                // agent configuration UI and don't need to be installed from the registry.
192                if BUILT_IN_REGISTRY_IDS.contains(&agent.id().as_ref()) {
193                    return false;
194                }
195
196                let matches_search = search.as_ref().is_none_or(|query| {
197                    let query = query.as_str();
198                    agent.id().as_ref().to_lowercase().contains(query)
199                        || agent.name().as_ref().to_lowercase().contains(query)
200                        || agent.description().as_ref().to_lowercase().contains(query)
201                });
202
203                let install_status = installed_statuses
204                    .get(agent.id().as_ref())
205                    .copied()
206                    .unwrap_or(RegistryInstallStatus::NotInstalled);
207                let matches_filter = match filter {
208                    RegistryFilter::All => true,
209                    RegistryFilter::Installed => {
210                        install_status != RegistryInstallStatus::NotInstalled
211                    }
212                    RegistryFilter::NotInstalled => {
213                        install_status == RegistryInstallStatus::NotInstalled
214                    }
215                };
216
217                matches_search && matches_filter
218            })
219            .map(|(index, _)| index)
220            .collect();
221
222        self.filtered_registry_indices = filtered_indices;
223
224        cx.notify();
225    }
226
227    fn scroll_to_top(&mut self, cx: &mut Context<Self>) {
228        self.list.set_offset(point(px(0.), px(0.)));
229        cx.notify();
230    }
231
232    fn on_query_change(
233        &mut self,
234        _: Entity<Editor>,
235        event: &editor::EditorEvent,
236        cx: &mut Context<Self>,
237    ) {
238        if let editor::EditorEvent::Edited { .. } = event {
239            self.filter_registry_agents(cx);
240            self.scroll_to_top(cx);
241        }
242    }
243
244    fn render_search(&self, cx: &mut Context<Self>) -> Div {
245        let mut key_context = KeyContext::new_with_defaults();
246        key_context.add("BufferSearchBar");
247
248        h_flex()
249            .key_context(key_context)
250            .h_8()
251            .min_w(rems_from_px(384.))
252            .flex_1()
253            .pl_1p5()
254            .pr_2()
255            .gap_2()
256            .border_1()
257            .border_color(cx.theme().colors().border)
258            .rounded_md()
259            .child(Icon::new(IconName::MagnifyingGlass).color(Color::Muted))
260            .child(self.render_text_input(&self.query_editor, cx))
261    }
262
263    fn render_text_input(
264        &self,
265        editor: &Entity<Editor>,
266        cx: &mut Context<Self>,
267    ) -> impl IntoElement {
268        let settings = ThemeSettings::get_global(cx);
269        let text_style = TextStyle {
270            color: if editor.read(cx).read_only(cx) {
271                cx.theme().colors().text_disabled
272            } else {
273                cx.theme().colors().text
274            },
275            font_family: settings.ui_font.family.clone(),
276            font_features: settings.ui_font.features.clone(),
277            font_fallbacks: settings.ui_font.fallbacks.clone(),
278            font_size: rems(0.875).into(),
279            font_weight: settings.ui_font.weight,
280            line_height: relative(1.3),
281            ..Default::default()
282        };
283
284        EditorElement::new(
285            editor,
286            EditorStyle {
287                background: cx.theme().colors().editor_background,
288                local_player: cx.theme().players().local(),
289                text: text_style,
290                ..Default::default()
291            },
292        )
293    }
294
295    fn render_empty_state(&self, cx: &mut Context<Self>) -> impl IntoElement {
296        let has_search = self.search_query(cx).is_some();
297        let registry_store = self.registry_store.read(cx);
298
299        let message = if registry_store.is_fetching() {
300            "Loading registry..."
301        } else if registry_store.fetch_error().is_some() {
302            "Failed to load the agent registry. Please check your connection and try again."
303        } else {
304            match self.filter {
305                RegistryFilter::All => {
306                    if has_search {
307                        "No agents match your search."
308                    } else {
309                        "No agents available."
310                    }
311                }
312                RegistryFilter::Installed => {
313                    if has_search {
314                        "No installed agents match your search."
315                    } else {
316                        "No installed agents."
317                    }
318                }
319                RegistryFilter::NotInstalled => {
320                    if has_search {
321                        "No uninstalled agents match your search."
322                    } else {
323                        "No uninstalled agents."
324                    }
325                }
326            }
327        };
328
329        h_flex()
330            .py_4()
331            .gap_1p5()
332            .when(registry_store.fetch_error().is_some(), |this| {
333                this.child(
334                    Icon::new(IconName::Warning)
335                        .size(IconSize::Small)
336                        .color(Color::Warning),
337                )
338            })
339            .child(Label::new(message))
340    }
341
342    fn render_agents(
343        &mut self,
344        range: Range<usize>,
345        _: &mut Window,
346        cx: &mut Context<Self>,
347    ) -> Vec<AgentRegistryCard> {
348        range
349            .map(|index| {
350                let Some(agent_index) = self.filtered_registry_indices.get(index).copied() else {
351                    return self.render_missing_agent();
352                };
353                let Some(agent) = self.registry_agents.get(agent_index) else {
354                    return self.render_missing_agent();
355                };
356                self.render_registry_agent(agent, cx)
357            })
358            .collect()
359    }
360
361    fn render_missing_agent(&self) -> AgentRegistryCard {
362        AgentRegistryCard::new().child(
363            Label::new("Missing registry entry.")
364                .size(LabelSize::Small)
365                .color(Color::Muted),
366        )
367    }
368
369    fn render_registry_agent(
370        &self,
371        agent: &RegistryAgent,
372        cx: &mut Context<Self>,
373    ) -> AgentRegistryCard {
374        let install_status = self.install_status(agent.id().as_ref());
375        let supports_current_platform = agent.supports_current_platform();
376
377        let icon = match agent.icon_path() {
378            Some(icon_path) => Icon::from_external_svg(icon_path.clone()),
379            None => Icon::new(IconName::Sparkle),
380        }
381        .size(IconSize::Medium)
382        .color(Color::Muted);
383
384        let install_button =
385            self.install_button(agent, install_status, supports_current_platform, cx);
386
387        let repository_button = agent.repository().map(|repository| {
388            let repository = repository.clone();
389            IconButton::new(
390                SharedString::from(format!("agent-repo-{}", agent.id())),
391                IconName::Link,
392            )
393            .icon_size(IconSize::Small)
394            .tooltip(Tooltip::text("Visit agent repository"))
395            .on_click(move |_, _, cx| {
396                cx.open_url(repository.as_ref());
397            })
398        });
399
400        AgentRegistryCard::new()
401            .child(
402                h_flex()
403                    .justify_between()
404                    .items_start()
405                    .child(
406                        h_flex().gap_2().items_center().child(icon).child(
407                            v_flex().gap_0p5().child(
408                                h_flex()
409                                    .gap_2()
410                                    .items_end()
411                                    .child(
412                                        Headline::new(agent.name().clone())
413                                            .size(HeadlineSize::Small),
414                                    )
415                                    .child(
416                                        Headline::new(format!("v{}", agent.version()))
417                                            .size(HeadlineSize::XSmall),
418                                    ),
419                            ),
420                        ),
421                    )
422                    .child(install_button),
423            )
424            .child(
425                h_flex()
426                    .gap_2()
427                    .justify_between()
428                    .child(
429                        Label::new(agent.description().clone())
430                            .size(LabelSize::Small)
431                            .color(Color::Default)
432                            .truncate(),
433                    )
434                    .when_some(repository_button, |this, button| this.child(button)),
435            )
436            .child(
437                h_flex()
438                    .gap_2()
439                    .justify_between()
440                    .child(
441                        Label::new(format!("ID: {}", agent.id()))
442                            .size(LabelSize::Small)
443                            .color(Color::Muted)
444                            .truncate(),
445                    )
446                    .when(!supports_current_platform, |this| {
447                        this.child(
448                            Label::new("Not supported on this platform")
449                                .size(LabelSize::Small)
450                                .color(Color::Warning),
451                        )
452                    }),
453            )
454    }
455
456    fn install_button(
457        &self,
458        agent: &RegistryAgent,
459        install_status: RegistryInstallStatus,
460        supports_current_platform: bool,
461        cx: &mut Context<Self>,
462    ) -> Button {
463        let button_id = SharedString::from(format!("install-agent-{}", agent.id()));
464
465        if !supports_current_platform {
466            return Button::new(button_id, "Unavailable")
467                .style(ButtonStyle::OutlinedGhost)
468                .disabled(true);
469        }
470
471        match install_status {
472            RegistryInstallStatus::NotInstalled => {
473                let fs = <dyn Fs>::global(cx);
474                let agent_id = agent.id().to_string();
475                Button::new(button_id, "Install")
476                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
477                    .icon(IconName::Download)
478                    .icon_size(IconSize::Small)
479                    .icon_color(Color::Muted)
480                    .icon_position(IconPosition::Start)
481                    .on_click(move |_, _, cx| {
482                        let agent_id = agent_id.clone();
483                        update_settings_file(fs.clone(), cx, move |settings, _| {
484                            let agent_servers = settings.agent_servers.get_or_insert_default();
485                            agent_servers.custom.entry(agent_id).or_insert_with(|| {
486                                settings::CustomAgentServerSettings::Registry {
487                                    default_mode: None,
488                                    default_model: None,
489                                    env: Default::default(),
490                                    favorite_models: Vec::new(),
491                                    default_config_options: HashMap::default(),
492                                    favorite_config_option_values: HashMap::default(),
493                                }
494                            });
495                        });
496                    })
497            }
498            RegistryInstallStatus::InstalledRegistry => {
499                let fs = <dyn Fs>::global(cx);
500                let agent_id = agent.id().to_string();
501                Button::new(button_id, "Remove")
502                    .style(ButtonStyle::OutlinedGhost)
503                    .on_click(move |_, _, cx| {
504                        let agent_id = agent_id.clone();
505                        update_settings_file(fs.clone(), cx, move |settings, _| {
506                            let Some(agent_servers) = settings.agent_servers.as_mut() else {
507                                return;
508                            };
509                            if let Some(entry) = agent_servers.custom.get(agent_id.as_str())
510                                && matches!(
511                                    entry,
512                                    settings::CustomAgentServerSettings::Registry { .. }
513                                )
514                            {
515                                agent_servers.custom.remove(agent_id.as_str());
516                            }
517                        });
518                    })
519            }
520            RegistryInstallStatus::InstalledCustom => Button::new(button_id, "Installed")
521                .style(ButtonStyle::OutlinedGhost)
522                .disabled(true),
523            RegistryInstallStatus::InstalledExtension => Button::new(button_id, "Installed")
524                .style(ButtonStyle::OutlinedGhost)
525                .disabled(true),
526        }
527    }
528}
529
530impl Render for AgentRegistryPage {
531    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
532        v_flex()
533            .size_full()
534            .bg(cx.theme().colors().editor_background)
535            .child(
536                v_flex()
537                    .gap_4()
538                    .pt_4()
539                    .px_4()
540                    .bg(cx.theme().colors().editor_background)
541                    .child(
542                        h_flex()
543                            .w_full()
544                            .gap_1p5()
545                            .justify_between()
546                            .child(Headline::new("ACP Agent Registry").size(HeadlineSize::XLarge)),
547                    )
548                    .child(
549                        h_flex()
550                            .w_full()
551                            .flex_wrap()
552                            .gap_2()
553                            .child(self.render_search(cx))
554                            .child(
555                                div().child(
556                                    ToggleButtonGroup::single_row(
557                                        "registry-filter-buttons",
558                                        [
559                                            ToggleButtonSimple::new(
560                                                "All",
561                                                cx.listener(|this, _event, _, cx| {
562                                                    this.filter = RegistryFilter::All;
563                                                    this.filter_registry_agents(cx);
564                                                    this.scroll_to_top(cx);
565                                                }),
566                                            ),
567                                            ToggleButtonSimple::new(
568                                                "Installed",
569                                                cx.listener(|this, _event, _, cx| {
570                                                    this.filter = RegistryFilter::Installed;
571                                                    this.filter_registry_agents(cx);
572                                                    this.scroll_to_top(cx);
573                                                }),
574                                            ),
575                                            ToggleButtonSimple::new(
576                                                "Not Installed",
577                                                cx.listener(|this, _event, _, cx| {
578                                                    this.filter = RegistryFilter::NotInstalled;
579                                                    this.filter_registry_agents(cx);
580                                                    this.scroll_to_top(cx);
581                                                }),
582                                            ),
583                                        ],
584                                    )
585                                    .style(ToggleButtonGroupStyle::Outlined)
586                                    .size(ToggleButtonGroupSize::Custom(rems_from_px(30.)))
587                                    .label_size(LabelSize::Default)
588                                    .auto_width()
589                                    .selected_index(match self.filter {
590                                        RegistryFilter::All => 0,
591                                        RegistryFilter::Installed => 1,
592                                        RegistryFilter::NotInstalled => 2,
593                                    })
594                                    .into_any_element(),
595                                ),
596                            ),
597                    ),
598            )
599            .child(v_flex().px_4().size_full().overflow_y_hidden().map(|this| {
600                let count = self.filtered_registry_indices.len();
601                if count == 0 {
602                    this.child(self.render_empty_state(cx)).into_any_element()
603                } else {
604                    let scroll_handle = &self.list;
605                    this.child(
606                        uniform_list("registry-entries", count, cx.processor(Self::render_agents))
607                            .flex_grow()
608                            .pb_4()
609                            .track_scroll(scroll_handle),
610                    )
611                    .vertical_scrollbar_for(scroll_handle, window, cx)
612                    .into_any_element()
613                }
614            }))
615    }
616}
617
618impl EventEmitter<ItemEvent> for AgentRegistryPage {}
619
620impl Focusable for AgentRegistryPage {
621    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
622        self.query_editor.read(cx).focus_handle(cx)
623    }
624}
625
626impl Item for AgentRegistryPage {
627    type Event = ItemEvent;
628
629    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
630        "ACP Agent Registry".into()
631    }
632
633    fn telemetry_event_text(&self) -> Option<&'static str> {
634        Some("ACP Agent Registry Page Opened")
635    }
636
637    fn show_toolbar(&self) -> bool {
638        false
639    }
640
641    fn to_item_events(event: &Self::Event, mut f: impl FnMut(workspace::item::ItemEvent)) {
642        f(*event)
643    }
644}