BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / notify / settings_mcp.rs

settings_mcp.rs

settings_mcp.rs 36.0 KiB Download Raw
1use std::collections::{BTreeSet, HashMap};
2use std::time::Duration;
3
4use gpui_kit::assets::IconName;
5use gpui_kit::component::{
6 ActiveTheme as _, h_flex,
7 input::{Input, InputEvent, InputState},
8 v_flex,
9};
10use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::*;
12use mcp::install::{Homes, InstallReport, InstallState, Location, Target};
13use mcp::{Access, AgentPolicy};
14
15use super::settings_view::{control_row, switch, titled_with};
16use crate::agent_api::{self, ServerStatus};
17use crate::app_state::AppState;
18use crate::data::is_one_on_one;
19use crate::fuzzy;
20use crate::theme;
21use crate::views::switcher::{Candidate, candidate_avatar, candidates_from};
22use crate::views::widgets::icon;
23
24const COPIED_SHOWN: Duration = Duration::from_millis(1500);
25const PORT_WIDTH: f32 = 72.;
26const FIELD_HEIGHT: f32 = 36.;
27const SMALL_BUTTON_HEIGHT: f32 = 28.;
28const PICKER_ROW_HEIGHT: f32 = 30.;
29const PICKER_MAX_ROWS: usize = 6;
30const PICKER_RESULTS: usize = 40;
31const TOKEN_TAIL: usize = 4;
32const CHIP_MAX_WIDTH: f32 = 180.;
33const WSL_WARNING: &str = "WSL agents cannot reach 127.0.0.1 on Windows. Add networkingMode=mirrored to .wslconfig and run wsl --shutdown.";
34
35#[derive(Clone, Copy, PartialEq, Eq)]
36enum McpTab {
37 Server,
38 Access,
39 Install,
40}
41
42impl McpTab {
43 const ALL: [McpTab; 3] = [McpTab::Server, McpTab::Access, McpTab::Install];
44
45 fn label(self) -> &'static str {
46 match self {
47 McpTab::Server => "Server",
48 McpTab::Access => "Access",
49 McpTab::Install => "Install",
50 }
51 }
52}
53
54#[derive(Clone, Copy, PartialEq, Eq)]
55enum Scope {
56 Chats,
57 Channels,
58}
59
60impl Scope {
61 fn access(self, policy: &AgentPolicy) -> &Access {
62 match self {
63 Scope::Chats => &policy.chats,
64 Scope::Channels => &policy.channels,
65 }
66 }
67
68 fn access_mut(self, policy: &mut AgentPolicy) -> &mut Access {
69 match self {
70 Scope::Chats => &mut policy.chats,
71 Scope::Channels => &mut policy.channels,
72 }
73 }
74
75 fn title(self) -> &'static str {
76 match self {
77 Scope::Chats => "Chats",
78 Scope::Channels => "Channels",
79 }
80 }
81
82 fn add_label(self) -> &'static str {
83 match self {
84 Scope::Chats => "+ Add chat",
85 Scope::Channels => "+ Add channel",
86 }
87 }
88
89 fn contains(self, candidate: &Candidate) -> bool {
90 use crate::app_state::Selection;
91 matches!(
92 (self, &candidate.selection),
93 (Scope::Chats, Selection::Chat(_)) | (Scope::Channels, Selection::Channel(_))
94 )
95 }
96}
97
98#[derive(Clone, Copy, PartialEq, Eq)]
99enum Copied {
100 Url,
101 Token,
102 Manual,
103}
104
105#[derive(Clone, Copy, PartialEq, Eq)]
106enum InstallAction {
107 Install,
108 Update,
109 Remove,
110}
111
112impl InstallAction {
113 fn label(self) -> &'static str {
114 match self {
115 InstallAction::Install => "Install",
116 InstallAction::Update => "Update",
117 InstallAction::Remove => "Remove",
118 }
119 }
120
121 fn busy_label(self) -> &'static str {
122 match self {
123 InstallAction::Install => "Installing...",
124 InstallAction::Update => "Updating...",
125 InstallAction::Remove => "Removing...",
126 }
127 }
128}
129
130fn target_logo(target: Target) -> &'static str {
131 match target {
132 Target::ClaudeCode => "CC",
133 Target::Codex => "CX",
134 Target::CopilotCli => "GH",
135 Target::VsCode => "VS",
136 Target::Cursor => "CU",
137 }
138}
139
140fn target_action(state: &InstallState) -> Option<InstallAction> {
141 if state.stale {
142 Some(InstallAction::Update)
143 } else if !state.installed_at.is_empty() {
144 Some(InstallAction::Remove)
145 } else if state.available {
146 Some(InstallAction::Install)
147 } else {
148 None
149 }
150}
151
152fn locations_label(locations: &[Location]) -> &'static str {
153 let windows = locations.contains(&Location::Windows);
154 let wsl = locations
155 .iter()
156 .any(|location| matches!(location, Location::Wsl { .. }));
157 match (windows, wsl) {
158 (true, true) => "Windows + WSL",
159 (true, false) => "Windows",
160 (false, true) => "WSL",
161 (false, false) => "Installed",
162 }
163}
164
165fn install_detail(target: Target, state: Option<&InstallState>) -> AnyElement {
166 let muted = |text: &'static str| {
167 div()
168 .text_size(px(12.))
169 .text_color(theme::text_muted())
170 .child(text)
171 .into_any_element()
172 };
173 let Some(state) = state else {
174 return muted(target.config_hint());
175 };
176 if state.stale {
177 return div()
178 .text_size(px(12.))
179 .text_color(theme::amber())
180 .child("Out of date - Update")
181 .into_any_element();
182 }
183 if !state.installed_at.is_empty() {
184 return h_flex()
185 .gap(px(6.))
186 .items_center()
187 .text_size(px(12.))
188 .text_color(theme::green())
189 .child(div().size(px(6.)).rounded_full().bg(theme::green()))
190 .child(locations_label(&state.installed_at))
191 .into_any_element();
192 }
193 if state.available {
194 muted(target.config_hint())
195 } else {
196 muted("Not installed")
197 }
198}
199
200fn wsl_warning() -> Div {
201 note_box(
202 h_flex()
203 .gap(px(8.))
204 .items_start()
205 .child(
206 div()
207 .font_weight(FontWeight::BOLD)
208 .text_color(theme::amber())
209 .child("!"),
210 )
211 .child(div().flex_1().child(WSL_WARNING)),
212 4.,
213 )
214}
215
216pub struct McpView {
217 app: Entity<AppState>,
218 tab: McpTab,
219 picker: Option<Scope>,
220 port_input: Entity<InputState>,
221 search_input: Entity<InputState>,
222 copied: Option<Copied>,
223 install_states: Option<Vec<InstallState>>,
224 install_busy: Option<(Target, InstallAction)>,
225 install_errors: HashMap<Target, String>,
226 wsl_unreachable: bool,
227 _subscriptions: Vec<Subscription>,
228}
229
230impl McpView {
231 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
232 let port = agent_api::policy(cx).port;
233 let port_input = cx.new(|cx| InputState::new(window, cx));
234 port_input.update(cx, |input, cx| {
235 input.set_value(port.to_string(), window, cx)
236 });
237 let search_input = cx.new(|cx| InputState::new(window, cx).placeholder("Search"));
238 let mut subscriptions = vec![
239 cx.subscribe_in(&port_input, window, Self::on_port_event),
240 cx.subscribe_in(&search_input, window, |_, _, event, _, cx| {
241 if matches!(event, InputEvent::Change) {
242 cx.notify();
243 }
244 }),
245 ];
246 if let Some(api) = agent_api::handle(cx) {
247 subscriptions.push(cx.observe(&api, |_, _, cx| cx.notify()));
248 }
249 let mut view = McpView {
250 app,
251 tab: McpTab::Server,
252 picker: None,
253 port_input,
254 search_input,
255 copied: None,
256 install_states: None,
257 install_busy: None,
258 install_errors: HashMap::new(),
259 wsl_unreachable: false,
260 _subscriptions: subscriptions,
261 };
262 view.refresh_wsl(cx);
263 view
264 }
265
266 fn on_port_event(
267 &mut self,
268 input: &Entity<InputState>,
269 event: &InputEvent,
270 window: &mut Window,
271 cx: &mut Context<Self>,
272 ) {
273 if !matches!(event, InputEvent::Blur | InputEvent::PressEnter { .. }) {
274 return;
275 }
276 let current = agent_api::policy(cx).port;
277 let typed = input.read(cx).value().trim().parse::<u16>().ok();
278 match typed.filter(|port| *port != 0) {
279 Some(port) if port != current => {
280 agent_api::update_policy(cx, |policy| policy.port = port)
281 }
282 Some(_) => {}
283 None => input.update(cx, |input, cx| {
284 input.set_value(current.to_string(), window, cx)
285 }),
286 }
287 self.refresh_wsl(cx);
288 }
289
290 fn refresh_wsl(&mut self, cx: &mut Context<Self>) {
291 let port = agent_api::policy(cx).port;
292 let task = cx.background_spawn(async move { mcp::install::wsl_reachable(port) });
293 cx.spawn(async move |this, cx| {
294 let reachable = task.await;
295 this.update(cx, |this, cx| {
296 this.wsl_unreachable = reachable == Some(false);
297 cx.notify();
298 })
299 .ok();
300 })
301 .detach();
302 }
303
304 fn refresh_installs(&mut self, cx: &mut Context<Self>) {
305 let Some(endpoint) = agent_api::configured_endpoint(cx) else {
306 return;
307 };
308 let task = cx.background_spawn(async move {
309 let homes = Homes::detect();
310 Target::ALL
311 .map(|target| mcp::install::status(target, &endpoint, &homes))
312 .to_vec()
313 });
314 cx.spawn(async move |this, cx| {
315 let states = task.await;
316 this.update(cx, |this, cx| {
317 this.install_states = Some(states);
318 cx.notify();
319 })
320 .ok();
321 })
322 .detach();
323 }
324
325 fn run_install_action(
326 &mut self,
327 target: Target,
328 action: InstallAction,
329 cx: &mut Context<Self>,
330 ) {
331 let Some(endpoint) = agent_api::configured_endpoint(cx) else {
332 return;
333 };
334 self.install_busy = Some((target, action));
335 self.install_errors.remove(&target);
336 let task = cx.background_spawn(async move {
337 let homes = Homes::detect();
338 match action {
339 InstallAction::Remove => mcp::install::uninstall(target, &homes).map(|_| None),
340 _ => mcp::install::install(target, &endpoint, &homes).map(Some),
341 }
342 });
343 cx.spawn(async move |this, cx| {
344 let result = task.await;
345 this.update(cx, |this, cx| {
346 this.install_busy = None;
347 match result {
348 Ok(Some(InstallReport::OpenUrl(url))) => cx.open_url(&url),
349 Ok(_) => {}
350 Err(error) => {
351 this.install_errors.insert(target, error.to_string());
352 }
353 }
354 this.refresh_installs(cx);
355 cx.notify();
356 })
357 .ok();
358 })
359 .detach();
360 cx.notify();
361 }
362
363 fn select_tab(&mut self, tab: McpTab, cx: &mut Context<Self>) {
364 self.tab = tab;
365 self.picker = None;
366 match tab {
367 McpTab::Install => {
368 self.refresh_installs(cx);
369 self.refresh_wsl(cx);
370 }
371 McpTab::Server => self.refresh_wsl(cx),
372 McpTab::Access => {}
373 }
374 cx.notify();
375 }
376
377 fn copy(&mut self, target: Copied, text: String, cx: &mut Context<Self>) {
378 cx.write_to_clipboard(ClipboardItem::new_string(text));
379 self.copied = Some(target);
380 cx.spawn(async move |this, cx| {
381 cx.background_executor().timer(COPIED_SHOWN).await;
382 this.update(cx, |this, cx| {
383 this.copied = None;
384 cx.notify();
385 })
386 .ok();
387 })
388 .detach();
389 cx.notify();
390 }
391
392 fn open_picker(&mut self, scope: Scope, window: &mut Window, cx: &mut Context<Self>) {
393 self.picker = if self.picker == Some(scope) {
394 None
395 } else {
396 Some(scope)
397 };
398 self.search_input
399 .update(cx, |input, cx| input.set_value("", window, cx));
400 if self.picker.is_some() {
401 self.search_input
402 .update(cx, |input, cx| input.focus(window, cx));
403 }
404 cx.notify();
405 }
406}
407
408fn small_button(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Stateful<Div> {
409 inert_button(id, label)
410 .cursor_pointer()
411 .text_color(theme::text())
412 .hover(|button| button.bg(theme::popup_hover()))
413}
414
415fn inert_button(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Stateful<Div> {
416 div()
417 .id(id)
418 .h(px(SMALL_BUTTON_HEIGHT))
419 .px(px(12.))
420 .flex_none()
421 .flex()
422 .items_center()
423 .rounded(px(7.))
424 .bg(theme::surface_raised())
425 .text_size(px(12.))
426 .font_weight(FontWeight::SEMIBOLD)
427 .text_color(theme::text_faint())
428 .child(label.into())
429}
430
431fn caption(label: &'static str) -> Div {
432 div()
433 .px(px(20.))
434 .pt(px(16.))
435 .pb(px(4.))
436 .text_size(px(12.))
437 .font_weight(FontWeight::SEMIBOLD)
438 .text_color(theme::text_muted())
439 .child(label)
440}
441
442fn toggle_row(
443 id: &'static str,
444 title: &'static str,
445 detail: &'static str,
446 detail_color: Hsla,
447 on: bool,
448) -> Stateful<Div> {
449 h_flex()
450 .id(id)
451 .w_full()
452 .px(px(20.))
453 .py(px(10.))
454 .gap(px(12.))
455 .items_center()
456 .cursor_pointer()
457 .hover(|row| row.bg(theme::row_hover()))
458 .child(titled_with(title, detail, detail_color))
459 .child(switch(on))
460}
461
462fn note_box(content: impl IntoElement, margin_top: f32) -> Div {
463 h_flex()
464 .mx(px(20.))
465 .mt(px(margin_top))
466 .mb(px(12.))
467 .px(px(12.))
468 .py(px(10.))
469 .gap(px(8.))
470 .rounded(px(8.))
471 .bg(theme::row_hover())
472 .text_size(px(12.))
473 .text_color(theme::text_muted())
474 .child(content)
475}
476
477fn masked_token(token: &str) -> String {
478 let tail: String = token
479 .chars()
480 .rev()
481 .take(TOKEN_TAIL)
482 .collect::<Vec<_>>()
483 .into_iter()
484 .rev()
485 .collect();
486 format!("****...{tail}")
487}
488
489fn chat_kind_label(state: &AppState, conversation_id: &str) -> Option<&'static str> {
490 let chat = state
491 .sidebar
492 .chats
493 .iter()
494 .find(|chat| chat.id == conversation_id)?;
495 Some(if chat.kind.eq_ignore_ascii_case("meeting") {
496 "Meeting"
497 } else if is_one_on_one(chat) {
498 "Chat"
499 } else {
500 "Group"
501 })
502}
503
504impl Render for McpView {
505 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
506 let view = cx.entity();
507 let tabs = h_flex()
508 .mx(px(20.))
509 .mt(px(12.))
510 .mb(px(4.))
511 .p(px(2.))
512 .rounded(px(8.))
513 .bg(theme::surface())
514 .children(McpTab::ALL.map(|tab| {
515 let active = tab == self.tab;
516 let view = view.clone();
517 div()
518 .id(tab.label())
519 .flex_1()
520 .h(px(SMALL_BUTTON_HEIGHT))
521 .flex()
522 .items_center()
523 .justify_center()
524 .rounded(px(6.))
525 .cursor_pointer()
526 .text_size(px(12.))
527 .font_weight(FontWeight::SEMIBOLD)
528 .text_color(if active {
529 theme::text()
530 } else {
531 theme::text_muted()
532 })
533 .when(active, |tab| tab.bg(theme::surface_raised()))
534 .child(tab.label())
535 .on_click(move |_, _, cx| view.update(cx, |view, cx| view.select_tab(tab, cx)))
536 }));
537 let body = match self.tab {
538 McpTab::Server => self.server_tab(cx).into_any_element(),
539 McpTab::Access => self.access_tab(cx).into_any_element(),
540 McpTab::Install => self.install_tab(cx).into_any_element(),
541 };
542 v_flex().w_full().flex_1().min_h_0().child(tabs).child(
543 div()
544 .id("mcp-body")
545 .w_full()
546 .flex_1()
547 .min_h_0()
548 .overflow_y_scroll()
549 .child(body),
550 )
551 }
552}
553
554impl McpView {
555 fn field_row(
556 &self,
557 label: &'static str,
558 value: String,
559 buttons: Vec<AnyElement>,
560 cx: &App,
561 ) -> Div {
562 v_flex()
563 .w_full()
564 .px(px(20.))
565 .pb(px(8.))
566 .gap(px(4.))
567 .child(
568 div()
569 .text_size(px(11.))
570 .text_color(theme::text_faint())
571 .child(label),
572 )
573 .child(
574 h_flex()
575 .w_full()
576 .gap(px(8.))
577 .items_center()
578 .child(
579 div()
580 .flex_1()
581 .min_w_0()
582 .h(px(FIELD_HEIGHT))
583 .px(px(12.))
584 .flex()
585 .items_center()
586 .rounded(px(8.))
587 .bg(theme::surface())
588 .font_family(cx.theme().mono_font_family.clone())
589 .text_size(px(12.))
590 .text_color(theme::text_soft())
591 .child(div().truncate().child(value)),
592 )
593 .children(buttons),
594 )
595 }
596
597 fn copy_button(
598 &self,
599 id: &'static str,
600 target: Copied,
601 text: String,
602 cx: &mut Context<Self>,
603 ) -> AnyElement {
604 let label = if self.copied == Some(target) {
605 "Copied"
606 } else {
607 "Copy"
608 };
609 small_button(id, label)
610 .on_click(cx.listener(move |this, _, _, cx| this.copy(target, text.clone(), cx)))
611 .into_any_element()
612 }
613
614 fn server_tab(&self, cx: &mut Context<Self>) -> Div {
615 let policy = agent_api::policy(cx);
616 let (status, token) = match agent_api::handle(cx) {
617 Some(api) => {
618 let api = api.read(cx);
619 (api.status().clone(), api.token().to_owned())
620 }
621 None => (ServerStatus::Off, String::new()),
622 };
623 let failed = matches!(status, ServerStatus::PortInUse(_) | ServerStatus::Failed(_));
624 let (detail, detail_color) = match (policy.enabled, failed) {
625 (false, _) => ("Off - agents cannot reach Rusty Teams", theme::text_muted()),
626 (true, true) => ("Could not start", theme::red_soft()),
627 (true, false) => (
628 "Agents on this computer can read and propose",
629 theme::text_muted(),
630 ),
631 };
632 let enabled = policy.enabled;
633 let running = matches!(status, ServerStatus::Running(_));
634 let reinstall_note =
635 agent_api::handle(cx).and_then(|api| api.read(cx).reinstall_note().map(str::to_owned));
636 let warning = match &status {
637 ServerStatus::PortInUse(port) => Some(format!(
638 "Port {port} is in use by another program. Pick another port, then press Install again for each agent."
639 )),
640 ServerStatus::Failed(reason) => Some(reason.clone()),
641 _ => None,
642 }
643 .or(reinstall_note);
644 let url = agent_api::endpoint_url(policy.port);
645 let regenerate = small_button("mcp-token-new", "New")
646 .on_click(cx.listener(|_, _, _, cx| {
647 if let Some(api) = agent_api::handle(cx) {
648 api.update(cx, |api, cx| api.regenerate_token(cx));
649 }
650 }))
651 .into_any_element();
652 v_flex()
653 .w_full()
654 .child(
655 toggle_row("mcp-enabled", "MCP server", detail, detail_color, enabled).on_click(
656 cx.listener(move |_, _, _, cx| {
657 agent_api::update_policy(cx, |policy| policy.enabled = !enabled)
658 }),
659 ),
660 )
661 .children(warning.map(|text| {
662 note_box(
663 h_flex()
664 .gap(px(8.))
665 .items_start()
666 .child(
667 div()
668 .font_weight(FontWeight::BOLD)
669 .text_color(theme::red_soft())
670 .child("!"),
671 )
672 .child(div().flex_1().child(text)),
673 4.,
674 )
675 }))
676 .child(control_row(
677 "Port",
678 "Only this computer can connect",
679 div()
680 .w(px(PORT_WIDTH))
681 .flex_none()
682 .child(Input::new(&self.port_input)),
683 ))
684 .when(running && self.wsl_unreachable, |tab| {
685 tab.child(wsl_warning())
686 })
687 .child(caption("CONNECTION"))
688 .child(self.field_row(
689 "URL",
690 url.clone(),
691 vec![self.copy_button("mcp-url-copy", Copied::Url, url, cx)],
692 cx,
693 ))
694 .child(self.field_row(
695 "Token",
696 masked_token(&token),
697 vec![
698 self.copy_button("mcp-token-copy", Copied::Token, token, cx),
699 regenerate,
700 ],
701 cx,
702 ))
703 }
704
705 fn segmented(&self, scope: Scope, access: &Access, cx: &mut Context<Self>) -> Div {
706 let options: [(&'static str, bool, fn() -> Access); 3] = [
707 ("All", matches!(access, Access::All), || Access::All),
708 ("Selected", matches!(access, Access::Selected(_)), || {
709 Access::Selected(BTreeSet::new())
710 }),
711 ("None", matches!(access, Access::None), || Access::None),
712 ];
713 h_flex()
714 .flex_none()
715 .p(px(2.))
716 .rounded(px(8.))
717 .bg(theme::surface_raised())
718 .children(options.map(|(label, active, make)| {
719 div()
720 .id(SharedString::from(format!("{}-{label}", scope.title())))
721 .h(px(24.))
722 .px(px(10.))
723 .flex()
724 .items_center()
725 .rounded(px(6.))
726 .cursor_pointer()
727 .text_size(px(12.))
728 .font_weight(FontWeight::SEMIBOLD)
729 .text_color(if active {
730 theme::text()
731 } else {
732 theme::text_muted()
733 })
734 .when(active, |item| item.bg(theme::popup_hover()))
735 .child(label)
736 .on_click(cx.listener(move |this, _, _, cx| {
737 if !active {
738 this.picker = None;
739 agent_api::update_policy(cx, |policy| {
740 *scope.access_mut(policy) = make()
741 });
742 }
743 }))
744 }))
745 }
746
747 fn scope_detail(scope: Scope, access: &Access) -> String {
748 match (scope, access) {
749 (Scope::Chats, Access::All) => "All chats".to_owned(),
750 (Scope::Channels, Access::All) => "All channels".to_owned(),
751 (Scope::Chats, Access::None) => "No chat visible".to_owned(),
752 (Scope::Channels, Access::None) => "No channel visible".to_owned(),
753 (Scope::Chats, Access::Selected(ids)) => {
754 format!("{} selected, incl. meeting chats", ids.len())
755 }
756 (Scope::Channels, Access::Selected(ids)) => format!("{} selected", ids.len()),
757 }
758 }
759
760 fn scope_block(
761 &self,
762 scope: Scope,
763 policy: &AgentPolicy,
764 titles: &HashMap<String, String>,
765 cx: &mut Context<Self>,
766 ) -> Div {
767 let access = scope.access(policy);
768 let header = control_row(
769 scope.title(),
770 Self::scope_detail(scope, access),
771 self.segmented(scope, access, cx),
772 );
773 let Access::Selected(ids) = access else {
774 return v_flex().w_full().child(header);
775 };
776 let chips = ids.iter().map(|conversation_id| {
777 let title = titles
778 .get(conversation_id)
779 .cloned()
780 .unwrap_or_else(|| "Unknown".to_owned());
781 let conversation_id = conversation_id.clone();
782 h_flex()
783 .h(px(24.))
784 .pl(px(8.))
785 .gap(px(4.))
786 .items_center()
787 .rounded(px(6.))
788 .bg(theme::surface_raised())
789 .text_size(px(12.))
790 .text_color(theme::text_strong())
791 .child(div().max_w(px(CHIP_MAX_WIDTH)).truncate().child(title))
792 .child(
793 div()
794 .id(SharedString::from(format!("remove-{conversation_id}")))
795 .w(px(16.))
796 .h_full()
797 .flex()
798 .items_center()
799 .justify_center()
800 .cursor_pointer()
801 .child(icon(IconName::X, 10., theme::text_faint()))
802 .on_click(cx.listener(move |_, _, _, cx| {
803 let conversation_id = conversation_id.clone();
804 agent_api::update_policy(cx, |policy| {
805 if let Access::Selected(ids) = scope.access_mut(policy) {
806 ids.remove(&conversation_id);
807 }
808 })
809 })),
810 )
811 });
812 let add = div()
813 .id(SharedString::from(format!("add-{}", scope.title())))
814 .h(px(24.))
815 .px(px(8.))
816 .flex()
817 .items_center()
818 .rounded(px(6.))
819 .border_1()
820 .border_dashed()
821 .border_color(theme::border_strong())
822 .cursor_pointer()
823 .text_size(px(12.))
824 .text_color(theme::accent_text())
825 .child(scope.add_label())
826 .on_click(cx.listener(move |this, _, window, cx| this.open_picker(scope, window, cx)));
827 v_flex()
828 .w_full()
829 .child(header)
830 .child(
831 h_flex()
832 .w_full()
833 .flex_wrap()
834 .gap(px(6.))
835 .px(px(20.))
836 .pb(px(8.))
837 .children(chips)
838 .child(add),
839 )
840 .children(
841 self.picker
842 .filter(|open| *open == scope)
843 .map(|_| self.picker_panel(scope, ids, cx)),
844 )
845 }
846
847 fn picker_panel(
848 &self,
849 scope: Scope,
850 selected: &BTreeSet<String>,
851 cx: &mut Context<Self>,
852 ) -> Div {
853 let query = self.search_input.read(cx).value().to_string();
854 let state = self.app.read(cx);
855 let candidates: Vec<(String, Candidate)> = candidates_from(state)
856 .into_iter()
857 .filter(|(_, candidate)| scope.contains(candidate))
858 .collect();
859 let results = fuzzy::rank(&query, &candidates, PICKER_RESULTS);
860 let rows: Vec<AnyElement> = results
861 .into_iter()
862 .map(|candidate| {
863 let conversation_id = candidate.selection.conversation_id().to_owned();
864 let added = selected.contains(&conversation_id);
865 let kind = match scope {
866 Scope::Chats => chat_kind_label(state, &conversation_id)
867 .unwrap_or("Chat")
868 .to_owned(),
869 Scope::Channels => candidate.subtitle.clone(),
870 };
871 h_flex()
872 .id(SharedString::from(format!("pick-{conversation_id}")))
873 .h(px(PICKER_ROW_HEIGHT))
874 .flex_none()
875 .px(px(6.))
876 .gap(px(8.))
877 .items_center()
878 .rounded(px(6.))
879 .cursor_pointer()
880 .hover(|row| row.bg(theme::popup_hover()))
881 .child(candidate_avatar(
882 &state.directory,
883 &candidate.avatar,
884 20.,
885 theme::popup(),
886 ))
887 .child(
888 div()
889 .flex_1()
890 .min_w_0()
891 .truncate()
892 .text_size(px(13.))
893 .text_color(theme::text())
894 .child(candidate.title.clone()),
895 )
896 .child(
897 div()
898 .flex_none()
899 .text_size(px(11.))
900 .text_color(if added {
901 theme::accent_text()
902 } else {
903 theme::text_faint()
904 })
905 .child(if added { "Added".to_owned() } else { kind }),
906 )
907 .on_click(cx.listener(move |this, _, _, cx| {
908 let conversation_id = conversation_id.clone();
909 this.picker = None;
910 agent_api::update_policy(cx, |policy| {
911 if let Access::Selected(ids) = scope.access_mut(policy) {
912 ids.insert(conversation_id);
913 }
914 });
915 }))
916 .into_any_element()
917 })
918 .collect();
919 v_flex()
920 .mx(px(20.))
921 .mb(px(8.))
922 .p(px(6.))
923 .gap(px(4.))
924 .rounded(px(8.))
925 .bg(theme::popup())
926 .border_1()
927 .border_color(theme::border())
928 .child(
929 h_flex()
930 .h(px(30.))
931 .px(px(6.))
932 .gap(px(6.))
933 .items_center()
934 .child(icon(IconName::Search, 14., theme::text_muted()))
935 .child(
936 div().flex_1().child(
937 Input::new(&self.search_input)
938 .appearance(false)
939 .bordered(false),
940 ),
941 ),
942 )
943 .child(
944 v_flex()
945 .id("mcp-picker-list")
946 .w_full()
947 .max_h(px(PICKER_ROW_HEIGHT * PICKER_MAX_ROWS as f32))
948 .overflow_y_scroll()
949 .children(rows),
950 )
951 }
952
953 fn access_tab(&self, cx: &mut Context<Self>) -> Div {
954 let policy = agent_api::policy(cx);
955 let titles: HashMap<String, String> = candidates_from(self.app.read(cx))
956 .into_iter()
957 .map(|(label, candidate)| (candidate.selection.conversation_id().to_owned(), label))
958 .collect();
959 let toggles: [(
960 &'static str,
961 &'static str,
962 &'static str,
963 Hsla,
964 bool,
965 fn(&mut AgentPolicy),
966 ); 3] = [
967 (
968 "mcp-propose",
969 "Propose messages",
970 "Card above the composer, you send",
971 theme::text_muted(),
972 policy.propose,
973 |policy| policy.propose = !policy.propose,
974 ),
975 (
976 "mcp-calendar",
977 "Calendar and meetings",
978 "Times, titles, organizers, join links",
979 theme::text_muted(),
980 policy.calendar,
981 |policy| policy.calendar = !policy.calendar,
982 ),
983 (
984 "mcp-transcripts",
985 "Meeting transcripts",
986 "Spoken text goes to the agent's provider",
987 theme::amber(),
988 policy.transcripts,
989 |policy| policy.transcripts = !policy.transcripts,
990 ),
991 ];
992 v_flex()
993 .w_full()
994 .child(self.scope_block(Scope::Chats, &policy, &titles, cx))
995 .child(self.scope_block(Scope::Channels, &policy, &titles, cx))
996 .children(toggles.map(|(id, title, detail, color, on, flip)| {
997 toggle_row(id, title, detail, color, on)
998 .on_click(cx.listener(move |_, _, _, cx| agent_api::update_policy(cx, flip)))
999 }))
1000 .child(note_box(
1001 "Agents only see what is allowed here. They never send - you do.",
1002 4.,
1003 ))
1004 }
1005
1006 fn install_row(&self, index: usize, target: Target, cx: &mut Context<Self>) -> Div {
1007 let state = self
1008 .install_states
1009 .as_ref()
1010 .and_then(|states| states.get(index));
1011 let busy = self.install_busy;
1012 let action = state.and_then(target_action);
1013 let button = match (busy, action) {
1014 (Some((busy_target, busy_action)), _) if busy_target == target => {
1015 inert_button(target.label(), busy_action.busy_label()).into_any_element()
1016 }
1017 (None, Some(action)) => small_button(target.label(), action.label())
1018 .on_click(
1019 cx.listener(move |this, _, _, cx| this.run_install_action(target, action, cx)),
1020 )
1021 .into_any_element(),
1022 _ => inert_button(target.label(), InstallAction::Install.label()).into_any_element(),
1023 };
1024 v_flex()
1025 .w_full()
1026 .child(
1027 h_flex()
1028 .w_full()
1029 .px(px(20.))
1030 .py(px(8.))
1031 .gap(px(12.))
1032 .items_center()
1033 .child(
1034 div()
1035 .size(px(28.))
1036 .flex_none()
1037 .flex()
1038 .items_center()
1039 .justify_center()
1040 .rounded(px(7.))
1041 .bg(theme::surface_raised())
1042 .text_size(px(11.))
1043 .font_weight(FontWeight::BOLD)
1044 .text_color(theme::text_soft())
1045 .child(target_logo(target)),
1046 )
1047 .child(
1048 v_flex()
1049 .flex_1()
1050 .child(
1051 div()
1052 .text_size(px(14.))
1053 .font_weight(FontWeight::SEMIBOLD)
1054 .text_color(theme::text())
1055 .child(target.label()),
1056 )
1057 .child(install_detail(target, state)),
1058 )
1059 .child(button),
1060 )
1061 .children(self.install_errors.get(&target).map(|message| {
1062 div()
1063 .px(px(20.))
1064 .pb(px(4.))
1065 .pl(px(60.))
1066 .text_size(px(12.))
1067 .text_color(theme::red_soft())
1068 .child(message.clone())
1069 }))
1070 }
1071
1072 fn install_tab(&self, cx: &mut Context<Self>) -> Div {
1073 let url = agent_api::endpoint_url(agent_api::policy(cx).port);
1074 let running = agent_api::handle(cx)
1075 .is_some_and(|api| matches!(api.read(cx).status(), ServerStatus::Running(_)));
1076 let rows: Vec<Div> = Target::ALL
1077 .into_iter()
1078 .enumerate()
1079 .map(|(index, target)| self.install_row(index, target, cx))
1080 .collect();
1081 v_flex()
1082 .w_full()
1083 .pt(px(8.))
1084 .children(rows)
1085 .child(caption("MANUAL"))
1086 .child(self.field_row(
1087 "URL",
1088 url.clone(),
1089 vec![self.copy_button("mcp-manual-copy", Copied::Manual, url, cx)],
1090 cx,
1091 ))
1092 .when(running && self.wsl_unreachable, |tab| {
1093 tab.child(wsl_warning())
1094 })
1095 }
1096}