BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / agents / settings_section.rs

settings_section.rs

settings_section.rs 34.6 KiB Download Raw
1use agents::{AgentAction, AgentBackend, AgentProfile, Environment, OutputFormat};
2use gpui_kit::assets::IconName;
3use gpui_kit::component::{
4 button::{Button, ButtonVariants as _},
5 h_flex,
6 input::{InputEvent, InputState, TextareaState},
7 v_flex,
8};
9use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::*;
11
12use super::environment_label;
13use super::runs::AgentRuns;
14use super::settings_controls::{
15 Choice, MenuEntry, PAGE_PADDING, dropdown, link_dropdown, section_header,
16};
17use super::settings_forms::resume_toggle;
18use crate::runtime;
19use crate::theme;
20use crate::views::widgets::icon;
21
22const NOTE: &str = "Agents get the message, its sender and up to 20 earlier messages. Nothing is sent to Teams without you.";
23const DEFAULT_DISTRO: &str = "Ubuntu";
24const PROMPT_MIN_ROWS: usize = 4;
25const PROMPT_MAX_ROWS: usize = 8;
26
27#[derive(Clone, Copy, PartialEq, Eq)]
28pub(super) enum Page {
29 List,
30 Agent,
31 Action,
32}
33
34#[derive(Clone, PartialEq, Eq)]
35pub(super) enum Probe {
36 Idle,
37 Running,
38 Found(String),
39 Missing(String),
40}
41
42pub(super) struct AgentForm {
43 pub id: String,
44 pub name: Entity<InputState>,
45 pub distro: Entity<InputState>,
46 pub command: Entity<InputState>,
47 pub open_session: Entity<InputState>,
48 pub mcp_flag: Entity<InputState>,
49 pub base_url: Entity<InputState>,
50 pub model: Entity<InputState>,
51 pub api_key: Entity<InputState>,
52}
53
54pub(super) struct ActionForm {
55 pub id: String,
56 pub label: Entity<InputState>,
57 pub working_dir: Entity<InputState>,
58 pub prompt: Entity<TextareaState>,
59 pub extra_args: Entity<InputState>,
60}
61
62pub struct AgentsSettings {
63 pub(super) runs: Entity<AgentRuns>,
64 pub(super) page: Page,
65 pub(super) agent_form: Option<AgentForm>,
66 pub(super) action_form: Option<ActionForm>,
67 pub(super) probe: Probe,
68 pub(super) models: Vec<String>,
69 models_request: u64,
70 pub(super) found: Vec<agents::CliHit>,
71 scanned: bool,
72 form_subscriptions: Vec<Subscription>,
73 _runs_subscription: Subscription,
74}
75
76pub fn unique_id(base: &str, taken: impl Fn(&str) -> bool) -> String {
77 if !taken(base) {
78 return base.to_owned();
79 }
80 (2..)
81 .map(|suffix| format!("{base}-{suffix}"))
82 .find(|candidate| !taken(candidate))
83 .unwrap_or_else(|| base.to_owned())
84}
85
86pub fn move_item<T>(items: &mut [T], index: usize, up: bool) -> bool {
87 let target = if up {
88 index.checked_sub(1)
89 } else {
90 Some(index + 1).filter(|target| *target < items.len())
91 };
92 match target {
93 Some(target) if index < items.len() => {
94 items.swap(index, target);
95 true
96 }
97 _ => false,
98 }
99}
100
101impl AgentsSettings {
102 pub fn new(runs: Entity<AgentRuns>, cx: &mut Context<Self>) -> Self {
103 let subscription = cx.observe(&runs, |_, _, cx| cx.notify());
104 AgentsSettings {
105 runs,
106 page: Page::List,
107 agent_form: None,
108 action_form: None,
109 probe: Probe::Idle,
110 models: Vec::new(),
111 models_request: 0,
112 found: Vec::new(),
113 scanned: false,
114 form_subscriptions: Vec::new(),
115 _runs_subscription: subscription,
116 }
117 }
118
119 pub(super) fn go_back(&mut self, cx: &mut Context<Self>) {
120 self.page = Page::List;
121 self.agent_form = None;
122 self.action_form = None;
123 self.form_subscriptions.clear();
124 self.probe = Probe::Idle;
125 self.models.clear();
126 self.models_request += 1;
127 cx.notify();
128 }
129
130 fn line_input(
131 &mut self,
132 value: &str,
133 window: &mut Window,
134 cx: &mut Context<Self>,
135 on_change: fn(&mut Self, &mut Context<Self>),
136 ) -> Entity<InputState> {
137 let value = value.to_owned();
138 let input = cx.new(|cx| InputState::new(window, cx).default_value(value));
139 self.form_subscriptions.push(cx.subscribe(
140 &input,
141 move |this, _, event: &InputEvent, cx| {
142 if matches!(event, InputEvent::Change) {
143 on_change(this, cx);
144 }
145 },
146 ));
147 input
148 }
149
150 fn open_agent(&mut self, agent_id: &str, window: &mut Window, cx: &mut Context<Self>) {
151 let Some(profile) = self
152 .runs
153 .read(cx)
154 .settings()
155 .agents
156 .iter()
157 .find(|profile| profile.id == agent_id)
158 .cloned()
159 else {
160 return;
161 };
162 self.go_back(cx);
163 let distro = match &profile.environment {
164 Environment::Wsl {
165 distro: Some(distro),
166 } => distro.clone(),
167 _ => String::new(),
168 };
169 let (base_url, model) = match &profile.backend {
170 AgentBackend::OpenAi {
171 base_url, model, ..
172 } => (base_url.clone(), model.clone()),
173 AgentBackend::Anthropic { model, .. } => (String::new(), model.clone()),
174 AgentBackend::Command => (String::new(), String::new()),
175 };
176 self.agent_form = Some(AgentForm {
177 id: profile.id.clone(),
178 name: self.line_input(&profile.name, window, cx, Self::commit_agent),
179 distro: self.line_input(&distro, window, cx, Self::commit_agent),
180 command: self.line_input(&profile.command, window, cx, Self::commit_agent),
181 open_session: self.line_input(
182 &profile.open_session_command,
183 window,
184 cx,
185 Self::commit_agent,
186 ),
187 mcp_flag: self.line_input(&profile.mcp_config_flag, window, cx, Self::commit_agent),
188 base_url: self.line_input(&base_url, window, cx, Self::commit_agent),
189 model: self.line_input(&model, window, cx, Self::commit_agent),
190 api_key: self.line_input("", window, cx, Self::commit_agent),
191 });
192 let inputs = self
193 .agent_form
194 .as_ref()
195 .map(|form| (form.base_url.clone(), form.api_key.clone()));
196 if let Some((base_url, api_key)) = inputs {
197 self.watch_model_refresh(&base_url, cx);
198 self.watch_model_refresh(&api_key, cx);
199 }
200 self.page = Page::Agent;
201 if profile.is_chat() {
202 self.refresh_models(cx);
203 }
204 cx.notify();
205 }
206
207 fn watch_model_refresh(&mut self, input: &Entity<InputState>, cx: &mut Context<Self>) {
208 self.form_subscriptions
209 .push(cx.subscribe(input, |this, _, event: &InputEvent, cx| {
210 if matches!(event, InputEvent::Blur) {
211 this.commit_agent(cx);
212 this.refresh_models(cx);
213 }
214 }));
215 }
216
217 fn open_action(&mut self, action_id: &str, window: &mut Window, cx: &mut Context<Self>) {
218 let Some(action) = self
219 .runs
220 .read(cx)
221 .settings()
222 .actions
223 .iter()
224 .find(|action| action.id == action_id)
225 .cloned()
226 else {
227 return;
228 };
229 self.go_back(cx);
230 let prompt = cx.new(|cx| {
231 TextareaState::new(window, cx)
232 .auto_grow(PROMPT_MIN_ROWS, PROMPT_MAX_ROWS)
233 .default_value(action.prompt_template.clone())
234 });
235 self.form_subscriptions
236 .push(cx.subscribe(&prompt, |this, _, event: &InputEvent, cx| {
237 if matches!(event, InputEvent::Change) {
238 this.commit_action(cx);
239 }
240 }));
241 self.action_form = Some(ActionForm {
242 id: action.id.clone(),
243 label: self.line_input(&action.label, window, cx, Self::commit_action),
244 working_dir: self.line_input(&action.working_dir, window, cx, Self::commit_action),
245 prompt,
246 extra_args: self.line_input(&action.extra_args, window, cx, Self::commit_action),
247 });
248 self.page = Page::Action;
249 cx.notify();
250 }
251
252 pub(super) fn commit_agent(&mut self, cx: &mut Context<Self>) {
253 let Some(form) = &self.agent_form else {
254 return;
255 };
256 let id = form.id.clone();
257 let name = form.name.read(cx).value().to_string();
258 let distro = form.distro.read(cx).value().trim().to_owned();
259 let command = form.command.read(cx).value().to_string();
260 let open_session = form.open_session.read(cx).value().to_string();
261 let mcp_flag = form.mcp_flag.read(cx).value().trim().to_owned();
262 let base_url = form.base_url.read(cx).value().trim().to_owned();
263 let model = form.model.read(cx).value().trim().to_owned();
264 let typed_key = form.api_key.read(cx).value().trim().to_owned();
265 self.runs.update(cx, |runs, cx| {
266 runs.update_settings(
267 |settings| {
268 let Some(agent) = settings.agents.iter_mut().find(|agent| agent.id == id)
269 else {
270 return;
271 };
272 agent.name = name;
273 if agent.is_chat() {
274 match &mut agent.backend {
275 AgentBackend::OpenAi {
276 base_url: url,
277 model: current,
278 api_key,
279 } => {
280 *url = base_url;
281 *current = model;
282 if !typed_key.is_empty() {
283 *api_key = typed_key;
284 }
285 }
286 AgentBackend::Anthropic {
287 model: current,
288 api_key,
289 } => {
290 *current = model;
291 if !typed_key.is_empty() {
292 *api_key = typed_key;
293 }
294 }
295 AgentBackend::Command => {}
296 }
297 } else {
298 agent.command = command;
299 agent.open_session_command = open_session;
300 agent.mcp_config_flag = mcp_flag;
301 if let Environment::Wsl {
302 distro: Some(current),
303 } = &mut agent.environment
304 {
305 *current = distro;
306 }
307 }
308 },
309 cx,
310 )
311 });
312 }
313
314 pub(super) fn set_model(&mut self, model: String, window: &mut Window, cx: &mut Context<Self>) {
315 let Some(form) = &self.agent_form else {
316 return;
317 };
318 form.model
319 .update(cx, |input, cx| input.set_value(model, window, cx));
320 self.commit_agent(cx);
321 }
322
323 pub(super) fn refresh_models(&mut self, cx: &mut Context<Self>) {
324 let Some(profile) = self.current_agent(cx) else {
325 return;
326 };
327 if !profile.is_chat() {
328 return;
329 }
330 self.models_request += 1;
331 let ticket = self.models_request;
332 self.probe = Probe::Running;
333 cx.notify();
334 let receiver = runtime::spawn(async move { agents::list_models(&profile).await });
335 cx.spawn(async move |this, cx| {
336 let result = receiver
337 .await
338 .unwrap_or_else(|_| Err("cancelled".to_owned()));
339 this.update(cx, |this, cx| {
340 if this.models_request != ticket {
341 return;
342 }
343 match result {
344 Ok(names) => {
345 let count = names.len();
346 this.models = names;
347 this.probe = Probe::Found(if count == 1 {
348 "1 model".to_owned()
349 } else {
350 format!("{count} models")
351 });
352 }
353 Err(error) => {
354 this.models.clear();
355 this.probe = Probe::Missing(error);
356 }
357 }
358 cx.notify();
359 })
360 .ok();
361 })
362 .detach();
363 }
364
365 pub(super) fn commit_action(&mut self, cx: &mut Context<Self>) {
366 let Some(form) = &self.action_form else {
367 return;
368 };
369 let id = form.id.clone();
370 let label = form.label.read(cx).value().to_string();
371 let working_dir = form.working_dir.read(cx).value().trim().to_owned();
372 let prompt = form.prompt.read(cx).value().to_string();
373 let extra_args = form.extra_args.read(cx).value().to_string();
374 self.runs.update(cx, |runs, cx| {
375 runs.update_settings(
376 |settings| {
377 let Some(action) = settings.actions.iter_mut().find(|action| action.id == id)
378 else {
379 return;
380 };
381 action.label = label;
382 action.working_dir = working_dir;
383 action.prompt_template = prompt;
384 action.extra_args = extra_args;
385 },
386 cx,
387 )
388 });
389 }
390
391 pub(super) fn set_environment(
392 &mut self,
393 environment: Environment,
394 window: &mut Window,
395 cx: &mut Context<Self>,
396 ) {
397 let Some(form) = &self.agent_form else {
398 return;
399 };
400 let id = form.id.clone();
401 if matches!(environment, Environment::Wsl { distro: Some(_) })
402 && form.distro.read(cx).value().trim().is_empty()
403 {
404 form.distro
405 .update(cx, |input, cx| input.set_value(DEFAULT_DISTRO, window, cx));
406 }
407 let distro = form.distro.read(cx).value().trim().to_owned();
408 let environment = match environment {
409 Environment::Wsl { distro: Some(_) } => Environment::Wsl {
410 distro: Some(distro),
411 },
412 other => other,
413 };
414 self.runs.update(cx, |runs, cx| {
415 runs.update_settings(
416 |settings| {
417 if let Some(agent) = settings.agents.iter_mut().find(|agent| agent.id == id) {
418 agent.environment = environment;
419 }
420 },
421 cx,
422 )
423 });
424 self.probe = Probe::Idle;
425 }
426
427 pub(super) fn set_output(&mut self, output: OutputFormat, cx: &mut Context<Self>) {
428 let Some(id) = self.agent_form.as_ref().map(|form| form.id.clone()) else {
429 return;
430 };
431 self.runs.update(cx, |runs, cx| {
432 runs.update_settings(
433 |settings| {
434 if let Some(agent) = settings.agents.iter_mut().find(|agent| agent.id == id) {
435 agent.output = output;
436 }
437 },
438 cx,
439 )
440 });
441 }
442
443 pub(super) fn set_action_agent(&mut self, agent_id: String, cx: &mut Context<Self>) {
444 self.update_action(cx, move |action| action.agent_id = agent_id);
445 }
446
447 pub(super) fn set_write_with(&mut self, agent_id: String, cx: &mut Context<Self>) {
448 self.runs.update(cx, |runs, cx| {
449 runs.update_settings(|settings| settings.write_with = agent_id, cx)
450 });
451 }
452
453 pub(super) fn rescan(&mut self, cx: &mut Context<Self>) {
454 self.found = agents::scan_clis();
455 self.scanned = true;
456 cx.notify();
457 }
458
459 pub(super) fn set_resume_interrupted_runs(&mut self, resume: bool, cx: &mut Context<Self>) {
460 self.runs.update(cx, |runs, cx| {
461 runs.update_settings(|settings| settings.resume_interrupted_runs = resume, cx)
462 });
463 }
464
465 pub(super) fn set_ask_extra(&mut self, ask: bool, cx: &mut Context<Self>) {
466 self.update_action(cx, move |action| action.ask_extra_instructions = ask);
467 }
468
469 fn update_action(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut AgentAction)) {
470 let Some(id) = self.action_form.as_ref().map(|form| form.id.clone()) else {
471 return;
472 };
473 self.runs.update(cx, |runs, cx| {
474 runs.update_settings(
475 |settings| {
476 if let Some(action) = settings.actions.iter_mut().find(|action| action.id == id)
477 {
478 change(action);
479 }
480 },
481 cx,
482 )
483 });
484 }
485
486 pub(super) fn insert_placeholder(
487 &mut self,
488 placeholder: &str,
489 window: &mut Window,
490 cx: &mut Context<Self>,
491 ) {
492 let Some(prompt) = self.action_form.as_ref().map(|form| form.prompt.clone()) else {
493 return;
494 };
495 let text = format!("{{{placeholder}}}");
496 prompt.update(cx, |prompt, cx| {
497 prompt.insert(text, window, cx);
498 prompt.focus(window, cx);
499 });
500 self.commit_action(cx);
501 }
502
503 pub(super) fn delete_agent(&mut self, cx: &mut Context<Self>) {
504 let Some(id) = self.agent_form.as_ref().map(|form| form.id.clone()) else {
505 return;
506 };
507 self.go_back(cx);
508 self.runs.update(cx, |runs, cx| {
509 runs.update_settings(
510 |settings| settings.agents.retain(|agent| agent.id != id),
511 cx,
512 )
513 });
514 }
515
516 pub(super) fn delete_action(&mut self, cx: &mut Context<Self>) {
517 let Some(id) = self.action_form.as_ref().map(|form| form.id.clone()) else {
518 return;
519 };
520 self.go_back(cx);
521 self.runs.update(cx, |runs, cx| {
522 runs.update_settings(
523 |settings| settings.actions.retain(|action| action.id != id),
524 cx,
525 )
526 });
527 }
528
529 pub(super) fn test_agent(&mut self, cx: &mut Context<Self>) {
530 let Some(profile) = self.current_agent(cx) else {
531 return;
532 };
533 if profile.is_chat() {
534 self.refresh_models(cx);
535 return;
536 }
537 if profile.command.trim().is_empty() {
538 self.probe = Probe::Missing("The command is empty".to_owned());
539 cx.notify();
540 return;
541 }
542 self.probe = Probe::Running;
543 cx.notify();
544 let invocation = agents::version_check_invocation(&profile);
545 let receiver = runtime::spawn(async move { agents::probe(&invocation).await });
546 cx.spawn(async move |this, cx| {
547 let result = receiver
548 .await
549 .unwrap_or_else(|_| Err("cancelled".to_owned()));
550 this.update(cx, |this, cx| {
551 this.probe = match result {
552 Ok(line) => Probe::Found(line),
553 Err(error) => Probe::Missing(error),
554 };
555 cx.notify();
556 })
557 .ok();
558 })
559 .detach();
560 }
561
562 pub(super) fn current_agent(&self, cx: &App) -> Option<AgentProfile> {
563 let id = &self.agent_form.as_ref()?.id;
564 self.runs
565 .read(cx)
566 .settings()
567 .agents
568 .iter()
569 .find(|agent| &agent.id == id)
570 .cloned()
571 }
572
573 fn add_agent(&mut self, preset: AgentProfile, window: &mut Window, cx: &mut Context<Self>) {
574 let mut profile = preset;
575 let existing: Vec<String> = self
576 .runs
577 .read(cx)
578 .settings()
579 .agents
580 .iter()
581 .map(|agent| agent.id.clone())
582 .collect();
583 profile.id = unique_id(&profile.id, |candidate| {
584 existing.iter().any(|id| id == candidate)
585 });
586 let id = profile.id.clone();
587 let chat = profile.is_chat();
588 let mut action = AgentAction::answer_this(&id);
589 action.extra_args.clear();
590 action.label = format!("Answer with {}", profile.name);
591 action.id = unique_id(&format!("answer-{id}"), |candidate| {
592 self.runs
593 .read(cx)
594 .settings()
595 .actions
596 .iter()
597 .any(|action| action.id == candidate)
598 });
599 self.runs.update(cx, |runs, cx| {
600 runs.update_settings(
601 |settings| {
602 settings.agents.push(profile);
603 if chat {
604 settings.actions.push(action);
605 }
606 },
607 cx,
608 )
609 });
610 self.open_agent(&id, window, cx);
611 }
612
613 fn add_action(&mut self, window: &mut Window, cx: &mut Context<Self>) {
614 let settings = self.runs.read(cx).settings();
615 let agent_id = settings
616 .agents
617 .first()
618 .map(|agent| agent.id.clone())
619 .unwrap_or_default();
620 let mut action = AgentAction::answer_this(&agent_id);
621 action.label = "New action".to_owned();
622 action.id = unique_id("action", |candidate| {
623 settings.actions.iter().any(|action| action.id == candidate)
624 });
625 let id = action.id.clone();
626 self.runs.update(cx, |runs, cx| {
627 runs.update_settings(|settings| settings.actions.push(action), cx)
628 });
629 self.open_action(&id, window, cx);
630 }
631
632 fn move_action(&mut self, index: usize, up: bool, cx: &mut Context<Self>) {
633 self.runs.update(cx, |runs, cx| {
634 runs.update_settings(
635 |settings| {
636 move_item(&mut settings.actions, index, up);
637 },
638 cx,
639 )
640 });
641 }
642}
643
644type Preset = (&'static str, fn() -> AgentProfile);
645
646fn agent_presets() -> [Preset; 9] {
647 fn custom() -> AgentProfile {
648 AgentProfile {
649 id: "custom".to_owned(),
650 name: "Custom agent".to_owned(),
651 environment: Environment::Host,
652 output: OutputFormat::Text,
653 ..AgentProfile::default()
654 }
655 }
656 [
657 (
658 "Claude Code (WSL)",
659 AgentProfile::claude_wsl as fn() -> AgentProfile,
660 ),
661 ("Claude Code (Windows)", AgentProfile::claude_host),
662 ("Copilot CLI (WSL)", AgentProfile::copilot_wsl),
663 ("Ollama", AgentProfile::ollama),
664 ("OpenAI", AgentProfile::openai),
665 ("OpenRouter", AgentProfile::openrouter),
666 ("Anthropic", AgentProfile::anthropic),
667 ("OpenAI-compatible", AgentProfile::openai_compatible),
668 ("Custom", custom),
669 ]
670}
671
672fn write_with_label(settings: &agents::AgentSettings) -> String {
673 if settings.write_with.is_empty() {
674 return "Microsoft Copilot".to_owned();
675 }
676 settings
677 .agents
678 .iter()
679 .find(|agent| agent.id == settings.write_with && agent.is_chat())
680 .map(|agent| agent.name.clone())
681 .unwrap_or_else(|| "Microsoft Copilot".to_owned())
682}
683
684fn write_with_entries(
685 settings: &agents::AgentSettings,
686 this: &Entity<AgentsSettings>,
687) -> Vec<MenuEntry> {
688 let mut entries = vec![write_with_entry(
689 this,
690 "Microsoft Copilot",
691 "",
692 settings.write_with.is_empty(),
693 )];
694 for agent in settings.agents.iter().filter(|agent| agent.is_chat()) {
695 entries.push(write_with_entry(
696 this,
697 &agent.name,
698 &agent.id,
699 settings.write_with == agent.id,
700 ));
701 }
702 entries
703}
704
705fn write_with_entry(
706 this: &Entity<AgentsSettings>,
707 label: &str,
708 agent_id: &str,
709 selected: bool,
710) -> MenuEntry {
711 let (this, agent_id) = (this.clone(), agent_id.to_owned());
712 let choose: Choice = std::rc::Rc::new(move |_, cx| {
713 let agent_id = agent_id.clone();
714 this.update(cx, |this, cx| this.set_write_with(agent_id, cx))
715 });
716 MenuEntry {
717 label: label.to_owned(),
718 selected,
719 choose,
720 }
721}
722
723fn list_row(
724 id: (&'static str, usize),
725 leading: Option<AnyElement>,
726 title: String,
727 detail: String,
728 mono: Option<String>,
729) -> Stateful<Div> {
730 h_flex()
731 .id(id)
732 .w_full()
733 .px(px(12.))
734 .py(px(8.))
735 .gap(px(12.))
736 .items_center()
737 .rounded(px(8.))
738 .cursor_pointer()
739 .hover(|row| row.bg(theme::popup_hover()))
740 .children(leading)
741 .child(
742 v_flex()
743 .flex_1()
744 .min_w(px(0.))
745 .gap(px(2.))
746 .child(
747 div()
748 .text_size(px(14.))
749 .font_weight(FontWeight::SEMIBOLD)
750 .child(title),
751 )
752 .child(
753 div()
754 .truncate()
755 .text_size(px(12.))
756 .text_color(theme::text_muted())
757 .child(detail),
758 )
759 .children(mono.map(|command| {
760 div()
761 .truncate()
762 .text_size(px(11.))
763 .text_color(theme::text_faint())
764 .child(command)
765 })),
766 )
767}
768
769fn small_button(id: (&'static str, usize), name: IconName, enabled: bool) -> Stateful<Div> {
770 div()
771 .id(id)
772 .size(px(28.))
773 .flex()
774 .flex_none()
775 .items_center()
776 .justify_center()
777 .rounded(px(7.))
778 .when(enabled, |button| {
779 button
780 .cursor_pointer()
781 .hover(|button| button.bg(theme::surface_raised()))
782 })
783 .when(!enabled, |button| button.opacity(0.4))
784 .child(icon(name, 14., theme::text_muted()))
785}
786
787impl AgentsSettings {
788 fn list_page(&mut self, cx: &mut Context<Self>) -> Div {
789 if !self.scanned {
790 self.found = agents::scan_clis();
791 self.scanned = true;
792 }
793 let settings = self.runs.read(cx).settings().clone();
794 let found: Vec<agents::CliHit> = self
795 .found
796 .iter()
797 .filter(|hit| !agents::already_installed(&settings.agents, &hit.profile))
798 .cloned()
799 .collect();
800 let this = cx.entity();
801 let preset_entries: Vec<MenuEntry> = agent_presets()
802 .into_iter()
803 .map(|(label, build)| {
804 let this = this.clone();
805 let choose: Choice = std::rc::Rc::new(move |window, cx| {
806 this.update(cx, |this, cx| this.add_agent(build(), window, cx))
807 });
808 MenuEntry {
809 label: label.to_owned(),
810 selected: false,
811 choose,
812 }
813 })
814 .collect();
815 let add_action = {
816 let this = this.clone();
817 Button::new("add-action")
818 .link()
819 .label("+ Add action")
820 .on_click(move |_, window, cx| {
821 this.update(cx, |this, cx| this.add_action(window, cx))
822 })
823 };
824 let action_count = settings.actions.len();
825 let agent_rows = settings.agents.iter().enumerate().map(|(index, agent)| {
826 let (open, id) = (cx.entity(), agent.id.clone());
827 list_row(
828 ("agent-row", index),
829 Some(
830 div()
831 .size(px(28.))
832 .flex()
833 .flex_none()
834 .items_center()
835 .justify_center()
836 .rounded(px(7.))
837 .bg(theme::surface_raised())
838 .child(icon(IconName::Bot, 14., theme::accent_text()))
839 .into_any_element(),
840 ),
841 agent.name.clone(),
842 if agent.is_chat() {
843 agent.backend_label()
844 } else {
845 environment_label(&agent.environment)
846 },
847 agent.is_command().then(|| agent.command.clone()),
848 )
849 .on_click(move |_, window, cx| {
850 open.update(cx, |this, cx| this.open_agent(&id, window, cx))
851 })
852 });
853 let action_rows = settings.actions.iter().enumerate().map(|(index, action)| {
854 let (open, id) = (cx.entity(), action.id.clone());
855 let (up, down) = (cx.entity(), cx.entity());
856 let agent_name = settings
857 .agents
858 .iter()
859 .find(|agent| agent.id == action.agent_id)
860 .map_or("Unknown agent", |agent| agent.name.as_str());
861 list_row(
862 ("action-row", index),
863 None,
864 action.label.clone(),
865 format!("{agent_name} - {}", action.working_dir),
866 None,
867 )
868 .on_click(move |_, window, cx| {
869 open.update(cx, |this, cx| this.open_action(&id, window, cx))
870 })
871 .child(
872 h_flex()
873 .flex_none()
874 .child(
875 small_button(("action-up", index), IconName::ArrowUp, index > 0).on_click(
876 move |_, _, cx| {
877 cx.stop_propagation();
878 up.update(cx, |this, cx| this.move_action(index, true, cx))
879 },
880 ),
881 )
882 .child(
883 small_button(
884 ("action-down", index),
885 IconName::ArrowDown,
886 index + 1 < action_count,
887 )
888 .on_click(move |_, _, cx| {
889 cx.stop_propagation();
890 down.update(cx, |this, cx| this.move_action(index, false, cx))
891 }),
892 ),
893 )
894 });
895 let write_entries = write_with_entries(&settings, &this);
896 let write_label = write_with_label(&settings);
897 let rescan = this.clone();
898 let found_rows = found.iter().enumerate().map(|(index, hit)| {
899 let (this, profile) = (this.clone(), hit.profile.clone());
900 list_row(
901 ("found-cli", index),
902 None,
903 hit.profile.name.clone(),
904 hit.binary.display().to_string(),
905 Some(hit.profile.command.clone()),
906 )
907 .child(
908 Button::new(("add-found", index))
909 .link()
910 .label("Add")
911 .on_click(move |_, window, cx| {
912 let profile = profile.clone();
913 this.update(cx, |this, cx| this.add_agent(profile, window, cx))
914 }),
915 )
916 });
917 v_flex()
918 .w_full()
919 .child(section_header(
920 "ON THIS COMPUTER",
921 Some(
922 Button::new("rescan-clis")
923 .link()
924 .label("Scan again")
925 .on_click(move |_, _, cx| {
926 rescan.update(cx, |this, cx| this.rescan(cx))
927 })
928 .into_any_element(),
929 ),
930 ))
931 .child(
932 v_flex()
933 .w_full()
934 .px(px(8.))
935 .children(found_rows)
936 .when(found.is_empty(), |rows| {
937 rows.child(
938 div()
939 .px(px(12.))
940 .py(px(8.))
941 .text_size(px(12.))
942 .text_color(theme::text_muted())
943 .child("No Claude, Copilot, Codex, Cursor or Antigravity CLI is waiting to be added."),
944 )
945 }),
946 )
947 .child(section_header(
948 "AGENTS",
949 Some(link_dropdown("add-agent", "+ Add agent", preset_entries).into_any_element()),
950 ))
951 .child(v_flex().w_full().px(px(8.)).children(agent_rows))
952 .child(section_header(
953 "ACTIONS - IN THIS ORDER IN THE MENU",
954 Some(add_action.into_any_element()),
955 ))
956 .child(v_flex().w_full().px(px(8.)).children(action_rows))
957 .child(
958 v_flex()
959 .w_full()
960 .px(px(PAGE_PADDING))
961 .pt(px(16.))
962 .gap(px(6.))
963 .child(
964 div()
965 .text_size(px(14.))
966 .font_weight(FontWeight::SEMIBOLD)
967 .child("Write with"),
968 )
969 .child(
970 div()
971 .text_size(px(12.))
972 .text_color(theme::text_muted())
973 .child("Rewrite in the composer and the chat assistant island. Microsoft Copilot needs the licence."),
974 )
975 .child(dropdown("write-with", write_label, write_entries)),
976 )
977 .child(resume_toggle(settings.resume_interrupted_runs, this))
978 .child(
979 div()
980 .w_full()
981 .px(px(PAGE_PADDING))
982 .pt(px(16.))
983 .pb(px(16.))
984 .text_size(px(12.))
985 .line_height(relative(1.5))
986 .text_color(theme::text_faint())
987 .child(NOTE),
988 )
989 }
990}
991
992impl Render for AgentsSettings {
993 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
994 match self.page {
995 Page::List => self.list_page(cx).into_any_element(),
996 Page::Agent => self.agent_page(window, cx).into_any_element(),
997 Page::Action => self.action_page(window, cx).into_any_element(),
998 }
999 }
1000}
1001
1002#[cfg(test)]
1003mod tests {
1004 use super::{move_item, unique_id};
1005
1006 #[test]
1007 fn ids_get_a_numeric_suffix_when_taken() {
1008 let taken = ["claude", "claude-2"];
1009 let is_taken = |candidate: &str| taken.contains(&candidate);
1010 assert_eq!(unique_id("copilot", is_taken), "copilot");
1011 assert_eq!(unique_id("claude", is_taken), "claude-3");
1012 }
1013
1014 #[test]
1015 fn moving_swaps_neighbours_and_stops_at_the_ends() {
1016 let mut items = vec!["a", "b", "c"];
1017 assert!(move_item(&mut items, 1, true));
1018 assert_eq!(items, ["b", "a", "c"]);
1019 assert!(move_item(&mut items, 1, false));
1020 assert_eq!(items, ["b", "c", "a"]);
1021 assert!(!move_item(&mut items, 0, true));
1022 assert!(!move_item(&mut items, 2, false));
1023 assert_eq!(items, ["b", "c", "a"]);
1024 }
1025}