BlueGit

ict rusty-teams

Files

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

mcp.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
mcp.rs 34.3 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 }
273 self.refresh_wsl(cx);
274 cx.notify();
275 }
276
277 fn refresh_wsl(&mut self, cx: &mut Context<Self>) {
278 let port = agent_api::policy(cx).port;
279 let task = cx.background_spawn(async move { mcp::install::wsl_reachable(port) });
280 cx.spawn(async move |this, cx| {
281 let reachable = task.await;
282 this.update(cx, |this, cx| {
283 this.wsl_unreachable = reachable == Some(false);
284 cx.notify();
285 })
286 .ok();
287 })
288 .detach();
289 }
290
291 fn refresh_installs(&mut self, cx: &mut Context<Self>) {
292 let Some(endpoint) = agent_api::configured_endpoint(cx) else {
293 return;
294 };
295 let demo = agent_api::is_demo(cx);
296 let task = cx.background_spawn(async move {
297 let homes = agent_api::agent_homes(demo);
298 Target::ALL
299 .map(|target| mcp::install::status(target, &endpoint, &homes))
300 .to_vec()
301 });
302 cx.spawn(async move |this, cx| {
303 let states = task.await;
304 this.update(cx, |this, cx| {
305 this.install_states = Some(states);
306 cx.notify();
307 })
308 .ok();
309 })
310 .detach();
311 }
312
313 fn run_install_action(
314 &mut self,
315 target: Target,
316 action: InstallAction,
317 cx: &mut Context<Self>,
318 ) {
319 let Some(endpoint) = agent_api::configured_endpoint(cx) else {
320 return;
321 };
322 self.install_busy = Some((target, action));
323 self.install_errors.remove(&target);
324 let demo = agent_api::is_demo(cx);
325 let task = cx.background_spawn(async move {
326 let homes = agent_api::agent_homes(demo);
327 match action {
328 InstallAction::Remove => mcp::install::uninstall(target, &homes).map(|_| None),
329 _ => mcp::install::install(target, &endpoint, &homes).map(Some),
330 }
331 });
332 cx.spawn(async move |this, cx| {
333 let result = task.await;
334 this.update(cx, |this, cx| {
335 this.install_busy = None;
336 match result {
337 Ok(Some(InstallReport::OpenUrl(url))) => cx.open_url(&url),
338 Ok(_) => {}
339 Err(error) => {
340 this.install_errors.insert(target, error.to_string());
341 }
342 }
343 this.refresh_installs(cx);
344 cx.notify();
345 })
346 .ok();
347 })
348 .detach();
349 cx.notify();
350 }
351
352 fn copy(&mut self, target: Copied, text: String, cx: &mut Context<Self>) {
353 cx.write_to_clipboard(ClipboardItem::new_string(text));
354 self.copied = Some(target);
355 cx.spawn(async move |this, cx| {
356 cx.background_executor().timer(COPIED_SHOWN).await;
357 this.update(cx, |this, cx| {
358 this.copied = None;
359 cx.notify();
360 })
361 .ok();
362 })
363 .detach();
364 cx.notify();
365 }
366
367 fn open_picker(&mut self, scope: Scope, window: &mut Window, cx: &mut Context<Self>) {
368 self.picker = if self.picker == Some(scope) {
369 None
370 } else {
371 Some(scope)
372 };
373 self.search_input
374 .update(cx, |input, cx| input.set_value("", window, cx));
375 if self.picker.is_some() {
376 self.search_input
377 .update(cx, |input, cx| input.focus(window, cx));
378 }
379 cx.notify();
380 }
381}
382
383fn small_button(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Stateful<Div> {
384 inert_button(id, label)
385 .cursor_pointer()
386 .text_color(theme::text())
387 .hover(|button| button.bg(theme::popup_hover()))
388}
389
390fn inert_button(id: impl Into<ElementId>, label: impl Into<SharedString>) -> Stateful<Div> {
391 div()
392 .id(id)
393 .h(px(SMALL_BUTTON_HEIGHT))
394 .px(px(12.))
395 .flex_none()
396 .flex()
397 .items_center()
398 .rounded(px(7.))
399 .bg(theme::surface_raised())
400 .text_size(px(12.))
401 .font_weight(FontWeight::SEMIBOLD)
402 .text_color(theme::text_faint())
403 .child(label.into())
404}
405
406fn note_box(content: impl IntoElement, margin_top: f32) -> Div {
407 h_flex()
408 .mx(px(ROW_INSET))
409 .mt(px(margin_top))
410 .mb(px(12.))
411 .px(px(12.))
412 .py(px(10.))
413 .gap(px(8.))
414 .rounded(px(8.))
415 .bg(theme::surface_raised())
416 .text_size(px(12.))
417 .text_color(theme::text_muted())
418 .child(content)
419}
420
421fn masked_token(token: &str) -> String {
422 let tail: String = token
423 .chars()
424 .rev()
425 .take(TOKEN_TAIL)
426 .collect::<Vec<_>>()
427 .into_iter()
428 .rev()
429 .collect();
430 format!("****...{tail}")
431}
432
433fn chat_kind_label(state: &AppState, conversation_id: &str) -> Option<&'static str> {
434 let chat = state
435 .sidebar
436 .chats
437 .iter()
438 .find(|chat| chat.id == conversation_id)?;
439 Some(if chat.kind.eq_ignore_ascii_case("meeting") {
440 "Meeting"
441 } else if is_one_on_one(chat) {
442 "Chat"
443 } else {
444 "Group"
445 })
446}
447
448impl Render for McpView {
449 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
450 v_flex()
451 .w_full()
452 .child(caption("SERVER"))
453 .child(self.server_tab(cx))
454 .child(caption("ACCESS"))
455 .child(self.access_tab(cx))
456 .child(caption("INSTALL"))
457 .child(self.install_tab(cx))
458 }
459}
460
461impl McpView {
462 fn field_row(
463 &self,
464 label: &'static str,
465 value: String,
466 buttons: Vec<AnyElement>,
467 cx: &App,
468 ) -> Div {
469 h_flex()
470 .w_full()
471 .px(px(ROW_INSET))
472 .py(px(6.))
473 .gap(px(8.))
474 .items_center()
475 .child(
476 div()
477 .w(px(FIELD_LABEL_WIDTH))
478 .flex_none()
479 .text_size(px(12.))
480 .text_color(theme::text_faint())
481 .child(label),
482 )
483 .child(
484 div()
485 .flex_1()
486 .min_w_0()
487 .h(px(FIELD_HEIGHT))
488 .px(px(10.))
489 .flex()
490 .items_center()
491 .rounded(px(7.))
492 .bg(theme::surface_raised())
493 .font_family(cx.theme().mono_font_family.clone())
494 .text_size(px(12.))
495 .text_color(theme::text_soft())
496 .child(div().truncate().child(value)),
497 )
498 .children(buttons)
499 }
500
501 fn copy_button(
502 &self,
503 id: &'static str,
504 target: Copied,
505 text: String,
506 cx: &mut Context<Self>,
507 ) -> AnyElement {
508 let label = if self.copied == Some(target) {
509 "Copied"
510 } else {
511 "Copy"
512 };
513 small_button(id, label)
514 .on_click(cx.listener(move |this, _, _, cx| this.copy(target, text.clone(), cx)))
515 .into_any_element()
516 }
517
518 fn server_tab(&self, cx: &mut Context<Self>) -> Div {
519 let policy = agent_api::policy(cx);
520 let (status, token) = match agent_api::handle(cx) {
521 Some(api) => {
522 let api = api.read(cx);
523 (api.status().clone(), api.token().to_owned())
524 }
525 None => (ServerStatus::Off, String::new()),
526 };
527 let failed = matches!(status, ServerStatus::PortInUse(_) | ServerStatus::Failed(_));
528 let (detail, detail_color) = match (policy.enabled, failed) {
529 (false, _) => ("Off - agents cannot reach Rusty Teams", theme::text_muted()),
530 (true, true) => ("Could not start", theme::red_soft()),
531 (true, false) => (
532 "Agents on this computer can read and write",
533 theme::text_muted(),
534 ),
535 };
536 let enabled = policy.enabled;
537 let running = matches!(status, ServerStatus::Running(_));
538 let reinstall_note =
539 agent_api::handle(cx).and_then(|api| api.read(cx).reinstall_note().map(str::to_owned));
540 let warning = match &status {
541 ServerStatus::PortInUse(port) => Some(format!(
542 "Port {port} is in use by another program. Pick another port, then press Install again for each agent."
543 )),
544 ServerStatus::Failed(reason) => Some(reason.clone()),
545 _ => None,
546 }
547 .or(reinstall_note);
548 let url = agent_api::endpoint_url(policy.port);
549 let regenerate = small_button("mcp-token-new", "New")
550 .on_click(cx.listener(|_, _, _, cx| {
551 if let Some(api) = agent_api::handle(cx) {
552 api.update(cx, |api, cx| api.regenerate_token(cx));
553 }
554 }))
555 .into_any_element();
556 v_flex()
557 .w_full()
558 .child(
559 toggle_row("mcp-enabled", "MCP server", detail, detail_color, enabled).on_click(
560 cx.listener(move |_, _, _, cx| {
561 agent_api::update_policy(cx, |policy| policy.enabled = !enabled)
562 }),
563 ),
564 )
565 .children(warning.map(|text| {
566 note_box(
567 h_flex()
568 .gap(px(8.))
569 .items_start()
570 .child(
571 div()
572 .font_weight(FontWeight::BOLD)
573 .text_color(theme::red_soft())
574 .child("!"),
575 )
576 .child(div().flex_1().child(text)),
577 4.,
578 )
579 }))
580 .child(control_row(
581 "Port",
582 "Only this computer can connect",
583 div()
584 .w(px(PORT_WIDTH))
585 .flex_none()
586 .child(Input::new(&self.port_input)),
587 ))
588 .when(self.port_invalid, |tab| {
589 tab.child(
590 div()
591 .px(px(ROW_INSET))
592 .pb(px(4.))
593 .text_size(px(12.))
594 .text_color(theme::red_soft())
595 .child("Enter a port from 1 to 65535. Nothing was saved."),
596 )
597 })
598 .when(running && self.wsl_unreachable, |tab| {
599 tab.child(wsl_warning())
600 })
601 .child(self.field_row(
602 "URL",
603 url.clone(),
604 vec![self.copy_button("mcp-url-copy", Copied::Url, url, cx)],
605 cx,
606 ))
607 .child(self.field_row(
608 "Token",
609 masked_token(&token),
610 vec![
611 self.copy_button("mcp-token-copy", Copied::Token, token, cx),
612 regenerate,
613 ],
614 cx,
615 ))
616 }
617
618 fn segmented(&self, scope: Scope, access: &Access, cx: &mut Context<Self>) -> Div {
619 let options: [(&'static str, bool, fn() -> Access); 3] = [
620 ("All", matches!(access, Access::All), || Access::All),
621 ("Selected", matches!(access, Access::Selected(_)), || {
622 Access::Selected(BTreeSet::new())
623 }),
624 ("None", matches!(access, Access::None), || Access::None),
625 ];
626 h_flex()
627 .flex_none()
628 .p(px(2.))
629 .rounded(px(8.))
630 .bg(theme::surface_raised())
631 .children(options.map(|(label, active, make)| {
632 div()
633 .id(SharedString::from(format!("{}-{label}", scope.title())))
634 .h(px(24.))
635 .px(px(10.))
636 .flex()
637 .items_center()
638 .rounded(px(6.))
639 .cursor_pointer()
640 .text_size(px(12.))
641 .font_weight(FontWeight::SEMIBOLD)
642 .text_color(if active {
643 theme::text()
644 } else {
645 theme::text_muted()
646 })
647 .when(active, |item| item.bg(theme::popup_hover()))
648 .child(label)
649 .on_click(cx.listener(move |this, _, _, cx| {
650 if !active {
651 this.picker = None;
652 agent_api::update_policy(cx, |policy| {
653 *scope.access_mut(policy) = make()
654 });
655 }
656 }))
657 }))
658 }
659
660 fn scope_detail(scope: Scope, access: &Access) -> String {
661 match (scope, access) {
662 (Scope::Chats, Access::All) => "All chats".to_owned(),
663 (Scope::Channels, Access::All) => "All channels".to_owned(),
664 (Scope::Chats, Access::None) => "No chat visible".to_owned(),
665 (Scope::Channels, Access::None) => "No channel visible".to_owned(),
666 (Scope::Chats, Access::Selected(ids)) => {
667 format!("{} selected, incl. meeting chats", ids.len())
668 }
669 (Scope::Channels, Access::Selected(ids)) => format!("{} selected", ids.len()),
670 }
671 }
672
673 fn scope_block(
674 &self,
675 scope: Scope,
676 policy: &AgentPolicy,
677 titles: &HashMap<String, String>,
678 cx: &mut Context<Self>,
679 ) -> Div {
680 let access = scope.access(policy);
681 let header = control_row(
682 scope.title(),
683 Self::scope_detail(scope, access),
684 self.segmented(scope, access, cx),
685 );
686 let Access::Selected(ids) = access else {
687 return v_flex().w_full().child(header);
688 };
689 let chips = ids.iter().map(|conversation_id| {
690 let title = titles
691 .get(conversation_id)
692 .cloned()
693 .unwrap_or_else(|| "Unknown".to_owned());
694 let conversation_id = conversation_id.clone();
695 h_flex()
696 .h(px(24.))
697 .pl(px(8.))
698 .gap(px(4.))
699 .items_center()
700 .rounded(px(6.))
701 .bg(theme::surface_raised())
702 .text_size(px(12.))
703 .text_color(theme::text_strong())
704 .child(div().max_w(px(CHIP_MAX_WIDTH)).truncate().child(title))
705 .child(
706 div()
707 .id(SharedString::from(format!("remove-{conversation_id}")))
708 .w(px(16.))
709 .h_full()
710 .flex()
711 .items_center()
712 .justify_center()
713 .cursor_pointer()
714 .child(icon(IconName::X, 10., theme::text_faint()))
715 .on_click(cx.listener(move |_, _, _, cx| {
716 let conversation_id = conversation_id.clone();
717 agent_api::update_policy(cx, |policy| {
718 if let Access::Selected(ids) = scope.access_mut(policy) {
719 ids.remove(&conversation_id);
720 }
721 })
722 })),
723 )
724 });
725 let add = div()
726 .id(SharedString::from(format!("add-{}", scope.title())))
727 .h(px(24.))
728 .px(px(8.))
729 .flex()
730 .items_center()
731 .rounded(px(6.))
732 .border_1()
733 .border_color(theme::border_strong())
734 .cursor_pointer()
735 .text_size(px(12.))
736 .text_color(theme::accent_text())
737 .child(scope.add_label())
738 .on_click(cx.listener(move |this, _, window, cx| this.open_picker(scope, window, cx)));
739 v_flex()
740 .w_full()
741 .child(header)
742 .child(
743 h_flex()
744 .w_full()
745 .flex_wrap()
746 .gap(px(6.))
747 .px(px(ROW_INSET))
748 .pb(px(8.))
749 .children(chips)
750 .child(add),
751 )
752 .children(
753 self.picker
754 .filter(|open| *open == scope)
755 .map(|_| self.picker_panel(scope, ids, cx)),
756 )
757 }
758
759 fn picker_panel(
760 &self,
761 scope: Scope,
762 selected: &BTreeSet<String>,
763 cx: &mut Context<Self>,
764 ) -> Div {
765 let query = self.search_input.read(cx).value().to_string();
766 let state = self.app.read(cx);
767 let candidates: Vec<(String, Candidate)> = candidates_from(state)
768 .into_iter()
769 .filter(|(_, candidate)| scope.contains(candidate))
770 .collect();
771 let results = fuzzy::rank(&query, &candidates, PICKER_RESULTS);
772 let rows: Vec<AnyElement> = results
773 .into_iter()
774 .map(|candidate| {
775 let conversation_id = candidate.selection.conversation_id().to_owned();
776 let added = selected.contains(&conversation_id);
777 let kind = match scope {
778 Scope::Chats => chat_kind_label(state, &conversation_id)
779 .unwrap_or("Chat")
780 .to_owned(),
781 Scope::Channels => candidate.subtitle.clone(),
782 };
783 h_flex()
784 .id(SharedString::from(format!("pick-{conversation_id}")))
785 .h(px(PICKER_ROW_HEIGHT))
786 .flex_none()
787 .px(px(6.))
788 .gap(px(8.))
789 .items_center()
790 .rounded(px(6.))
791 .cursor_pointer()
792 .hover(|row| row.bg(theme::popup_hover()))
793 .child(candidate_avatar(
794 &state.directory,
795 &candidate.avatar,
796 20.,
797 theme::popup(),
798 ))
799 .child(
800 div()
801 .flex_1()
802 .min_w_0()
803 .truncate()
804 .text_size(px(13.))
805 .text_color(theme::text())
806 .child(candidate.title.clone()),
807 )
808 .child(
809 div()
810 .flex_none()
811 .text_size(px(11.))
812 .text_color(if added {
813 theme::accent_text()
814 } else {
815 theme::text_faint()
816 })
817 .child(if added { "Added".to_owned() } else { kind }),
818 )
819 .on_click(cx.listener(move |this, _, _, cx| {
820 let conversation_id = conversation_id.clone();
821 this.picker = None;
822 agent_api::update_policy(cx, |policy| {
823 if let Access::Selected(ids) = scope.access_mut(policy) {
824 ids.insert(conversation_id);
825 }
826 });
827 }))
828 .into_any_element()
829 })
830 .collect();
831 v_flex()
832 .mx(px(ROW_INSET))
833 .mb(px(8.))
834 .p(px(6.))
835 .gap(px(4.))
836 .rounded(px(8.))
837 .bg(theme::surface_raised())
838 .child(
839 h_flex()
840 .h(px(30.))
841 .px(px(6.))
842 .gap(px(6.))
843 .items_center()
844 .child(icon(IconName::Search, 14., theme::text_muted()))
845 .child(
846 div().flex_1().child(
847 Input::new(&self.search_input)
848 .appearance(false)
849 .bordered(false),
850 ),
851 ),
852 )
853 .child(
854 v_flex()
855 .id("mcp-picker-list")
856 .w_full()
857 .max_h(px(PICKER_ROW_HEIGHT * PICKER_MAX_ROWS as f32))
858 .overflow_y_scrollbar()
859 .children(rows),
860 )
861 }
862
863 fn access_tab(&self, cx: &mut Context<Self>) -> Div {
864 let policy = agent_api::policy(cx);
865 let titles: HashMap<String, String> = candidates_from(self.app.read(cx))
866 .into_iter()
867 .map(|(label, candidate)| (candidate.selection.conversation_id().to_owned(), label))
868 .collect();
869 let toggles: [(
870 &'static str,
871 &'static str,
872 &'static str,
873 Hsla,
874 bool,
875 fn(&mut AgentPolicy),
876 ); 5] = [
877 (
878 "mcp-write",
879 "Write messages and reactions",
880 "Agents can answer in the chats and channels above",
881 theme::text_muted(),
882 policy.write,
883 |policy| policy.write = !policy.write,
884 ),
885 (
886 "mcp-review",
887 "Review before sending",
888 if policy.review {
889 "Card above the composer, note under a message. You decide"
890 } else {
891 "Off: agents send and react right away, as you"
892 },
893 if policy.review {
894 theme::text_muted()
895 } else {
896 theme::amber()
897 },
898 policy.review,
899 |policy| policy.review = !policy.review,
900 ),
901 (
902 "mcp-calendar",
903 "Calendar and meetings",
904 "Times, titles, organizers, join links",
905 theme::text_muted(),
906 policy.calendar,
907 |policy| policy.calendar = !policy.calendar,
908 ),
909 (
910 "mcp-meetings",
911 "Organize meetings",
912 if policy.review {
913 "Free/busy of people, meeting card in Calendar. You create it"
914 } else {
915 "Without review: agents create meetings and invite people right away"
916 },
917 if policy.review {
918 theme::text_muted()
919 } else {
920 theme::amber()
921 },
922 policy.meetings,
923 |policy| policy.meetings = !policy.meetings,
924 ),
925 (
926 "mcp-transcripts",
927 "Meeting transcripts",
928 "Spoken text goes to the agent's provider",
929 theme::amber(),
930 policy.transcripts,
931 |policy| policy.transcripts = !policy.transcripts,
932 ),
933 ];
934 v_flex()
935 .w_full()
936 .child(self.scope_block(Scope::Chats, &policy, &titles, cx))
937 .child(self.scope_block(Scope::Channels, &policy, &titles, cx))
938 .children(toggles.map(|(id, title, detail, color, on, flip)| {
939 toggle_row(id, title, detail, color, on)
940 .on_click(cx.listener(move |_, _, _, cx| agent_api::update_policy(cx, flip)))
941 }))
942 .child(note_box(
943 if policy.review {
944 "Agents only see what is allowed here. They never send - you do."
945 } else {
946 "Agents only see what is allowed here. Without review they send as you."
947 },
948 4.,
949 ))
950 }
951
952 fn install_row(&self, index: usize, target: Target, cx: &mut Context<Self>) -> Div {
953 let state = self
954 .install_states
955 .as_ref()
956 .and_then(|states| states.get(index));
957 let busy = self.install_busy;
958 let action = state.and_then(target_action);
959 let button = match (busy, action) {
960 (Some((busy_target, busy_action)), _) if busy_target == target => {
961 inert_button(target.label(), busy_action.busy_label()).into_any_element()
962 }
963 (None, Some(action)) => small_button(target.label(), action.label())
964 .on_click(
965 cx.listener(move |this, _, _, cx| this.run_install_action(target, action, cx)),
966 )
967 .into_any_element(),
968 _ => inert_button(target.label(), InstallAction::Install.label()).into_any_element(),
969 };
970 v_flex()
971 .w_full()
972 .child(
973 h_flex()
974 .w_full()
975 .px(px(ROW_INSET))
976 .py(px(8.))
977 .gap(px(12.))
978 .items_center()
979 .child(
980 div()
981 .size(px(28.))
982 .flex_none()
983 .flex()
984 .items_center()
985 .justify_center()
986 .rounded(px(7.))
987 .bg(theme::surface_raised())
988 .text_size(px(11.))
989 .font_weight(FontWeight::BOLD)
990 .text_color(theme::text_soft())
991 .child(target_logo(target)),
992 )
993 .child(
994 v_flex()
995 .flex_1()
996 .child(
997 div()
998 .text_size(px(14.))
999 .font_weight(FontWeight::SEMIBOLD)
1000 .text_color(theme::text())
1001 .child(target.label()),
1002 )
1003 .child(install_detail(target, state)),
1004 )
1005 .child(button),
1006 )
1007 .children(self.install_errors.get(&target).map(|message| {
1008 div()
1009 .px(px(ROW_INSET))
1010 .pb(px(4.))
1011 .pl(px(60.))
1012 .text_size(px(12.))
1013 .text_color(theme::red_soft())
1014 .child(message.clone())
1015 }))
1016 }
1017
1018 fn install_tab(&self, cx: &mut Context<Self>) -> Div {
1019 let rows: Vec<Div> = Target::ALL
1020 .into_iter()
1021 .enumerate()
1022 .map(|(index, target)| self.install_row(index, target, cx))
1023 .collect();
1024 v_flex().w_full().children(rows)
1025 }
1026}