BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / settings / mcp.rs

mcp.rs

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