BlueGit

ict rusty-teams

Files

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

settings_section.rs

settings_section.rs 34.7 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::i18n::{tr, tr_args};
19use crate::runtime;
20use crate::theme;
21use crate::views::widgets::icon;
22
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 let mut args = std::collections::HashMap::new();
591 args.insert("name".to_owned(), profile.name.clone());
592 action.label = tr_args("agents.settings.answer_with", &args);
593 action.id = unique_id(&format!("answer-{id}"), |candidate| {
594 self.runs
595 .read(cx)
596 .settings()
597 .actions
598 .iter()
599 .any(|action| action.id == candidate)
600 });
601 self.runs.update(cx, |runs, cx| {
602 runs.update_settings(
603 |settings| {
604 settings.agents.push(profile);
605 if chat {
606 settings.actions.push(action);
607 }
608 },
609 cx,
610 )
611 });
612 self.open_agent(&id, window, cx);
613 }
614
615 fn add_action(&mut self, window: &mut Window, cx: &mut Context<Self>) {
616 let settings = self.runs.read(cx).settings();
617 let agent_id = settings
618 .agents
619 .first()
620 .map(|agent| agent.id.clone())
621 .unwrap_or_default();
622 let mut action = AgentAction::answer_this(&agent_id);
623 action.label = tr("agents.settings.new_action");
624 action.id = unique_id("action", |candidate| {
625 settings.actions.iter().any(|action| action.id == candidate)
626 });
627 let id = action.id.clone();
628 self.runs.update(cx, |runs, cx| {
629 runs.update_settings(|settings| settings.actions.push(action), cx)
630 });
631 self.open_action(&id, window, cx);
632 }
633
634 fn move_action(&mut self, index: usize, up: bool, cx: &mut Context<Self>) {
635 self.runs.update(cx, |runs, cx| {
636 runs.update_settings(
637 |settings| {
638 move_item(&mut settings.actions, index, up);
639 },
640 cx,
641 )
642 });
643 }
644}
645
646type Preset = (&'static str, fn() -> AgentProfile);
647
648fn agent_presets() -> [Preset; 9] {
649 fn custom() -> AgentProfile {
650 AgentProfile {
651 id: "custom".to_owned(),
652 name: tr("agents.settings.custom_agent"),
653 environment: Environment::Host,
654 output: OutputFormat::Text,
655 ..AgentProfile::default()
656 }
657 }
658 [
659 (
660 "Claude Code (WSL)",
661 AgentProfile::claude_wsl as fn() -> AgentProfile,
662 ),
663 ("Claude Code (Windows)", AgentProfile::claude_host),
664 ("Copilot CLI (WSL)", AgentProfile::copilot_wsl),
665 ("Ollama", AgentProfile::ollama),
666 ("OpenAI", AgentProfile::openai),
667 ("OpenRouter", AgentProfile::openrouter),
668 ("Anthropic", AgentProfile::anthropic),
669 ("OpenAI-compatible", AgentProfile::openai_compatible),
670 ("Custom", custom),
671 ]
672}
673
674fn write_with_label(settings: &agents::AgentSettings) -> String {
675 if settings.write_with.is_empty() {
676 return "Microsoft Copilot".to_owned();
677 }
678 settings
679 .agents
680 .iter()
681 .find(|agent| agent.id == settings.write_with && agent.is_chat())
682 .map(|agent| agent.name.clone())
683 .unwrap_or_else(|| "Microsoft Copilot".to_owned())
684}
685
686fn write_with_entries(
687 settings: &agents::AgentSettings,
688 this: &Entity<AgentsSettings>,
689) -> Vec<MenuEntry> {
690 let mut entries = vec![write_with_entry(
691 this,
692 "Microsoft Copilot",
693 "",
694 settings.write_with.is_empty(),
695 )];
696 for agent in settings.agents.iter().filter(|agent| agent.is_chat()) {
697 entries.push(write_with_entry(
698 this,
699 &agent.name,
700 &agent.id,
701 settings.write_with == agent.id,
702 ));
703 }
704 entries
705}
706
707fn write_with_entry(
708 this: &Entity<AgentsSettings>,
709 label: &str,
710 agent_id: &str,
711 selected: bool,
712) -> MenuEntry {
713 let (this, agent_id) = (this.clone(), agent_id.to_owned());
714 let choose: Choice = std::rc::Rc::new(move |_, cx| {
715 let agent_id = agent_id.clone();
716 this.update(cx, |this, cx| this.set_write_with(agent_id, cx))
717 });
718 MenuEntry {
719 label: label.to_owned(),
720 selected,
721 choose,
722 }
723}
724
725fn list_row(
726 id: (&'static str, usize),
727 leading: Option<AnyElement>,
728 title: String,
729 detail: String,
730 mono: Option<String>,
731) -> Stateful<Div> {
732 h_flex()
733 .id(id)
734 .w_full()
735 .px(px(12.))
736 .py(px(8.))
737 .gap(px(12.))
738 .items_center()
739 .rounded(px(8.))
740 .cursor_pointer()
741 .hover(|row| row.bg(theme::popup_hover()))
742 .children(leading)
743 .child(
744 v_flex()
745 .flex_1()
746 .min_w(px(0.))
747 .gap(px(2.))
748 .child(
749 div()
750 .text_size(px(14.))
751 .font_weight(FontWeight::SEMIBOLD)
752 .child(title),
753 )
754 .child(
755 div()
756 .truncate()
757 .text_size(px(12.))
758 .text_color(theme::text_muted())
759 .child(detail),
760 )
761 .children(mono.map(|command| {
762 div()
763 .truncate()
764 .text_size(px(11.))
765 .text_color(theme::text_faint())
766 .child(command)
767 })),
768 )
769}
770
771fn small_button(id: (&'static str, usize), name: IconName, enabled: bool) -> Stateful<Div> {
772 div()
773 .id(id)
774 .size(px(28.))
775 .flex()
776 .flex_none()
777 .items_center()
778 .justify_center()
779 .rounded(px(7.))
780 .when(enabled, |button| {
781 button
782 .cursor_pointer()
783 .hover(|button| button.bg(theme::surface_raised()))
784 })
785 .when(!enabled, |button| button.opacity(0.4))
786 .child(icon(name, 14., theme::text_muted()))
787}
788
789impl AgentsSettings {
790 fn list_page(&mut self, cx: &mut Context<Self>) -> Div {
791 if !self.scanned {
792 self.found = agents::scan_clis();
793 self.scanned = true;
794 }
795 let settings = self.runs.read(cx).settings().clone();
796 let found: Vec<agents::CliHit> = self
797 .found
798 .iter()
799 .filter(|hit| !agents::already_installed(&settings.agents, &hit.profile))
800 .cloned()
801 .collect();
802 let this = cx.entity();
803 let preset_entries: Vec<MenuEntry> = agent_presets()
804 .into_iter()
805 .map(|(label, build)| {
806 let this = this.clone();
807 let choose: Choice = std::rc::Rc::new(move |window, cx| {
808 this.update(cx, |this, cx| this.add_agent(build(), window, cx))
809 });
810 MenuEntry {
811 label: label.to_owned(),
812 selected: false,
813 choose,
814 }
815 })
816 .collect();
817 let add_action = {
818 let this = this.clone();
819 Button::new("add-action")
820 .link()
821 .label("+ Add action")
822 .on_click(move |_, window, cx| {
823 this.update(cx, |this, cx| this.add_action(window, cx))
824 })
825 };
826 let action_count = settings.actions.len();
827 let agent_rows = settings.agents.iter().enumerate().map(|(index, agent)| {
828 let (open, id) = (cx.entity(), agent.id.clone());
829 list_row(
830 ("agent-row", index),
831 Some(
832 div()
833 .size(px(28.))
834 .flex()
835 .flex_none()
836 .items_center()
837 .justify_center()
838 .rounded(px(7.))
839 .bg(theme::surface_raised())
840 .child(icon(IconName::Bot, 14., theme::accent_text()))
841 .into_any_element(),
842 ),
843 agent.name.clone(),
844 if agent.is_chat() {
845 agent.backend_label()
846 } else {
847 environment_label(&agent.environment)
848 },
849 agent.is_command().then(|| agent.command.clone()),
850 )
851 .on_click(move |_, window, cx| {
852 open.update(cx, |this, cx| this.open_agent(&id, window, cx))
853 })
854 });
855 let action_rows = settings.actions.iter().enumerate().map(|(index, action)| {
856 let (open, id) = (cx.entity(), action.id.clone());
857 let (up, down) = (cx.entity(), cx.entity());
858 let agent_name = settings
859 .agents
860 .iter()
861 .find(|agent| agent.id == action.agent_id)
862 .map(|agent| agent.name.clone())
863 .unwrap_or_else(|| tr("agents.settings.unknown_agent"));
864 list_row(
865 ("action-row", index),
866 None,
867 action.label.clone(),
868 format!("{agent_name} - {}", action.working_dir),
869 None,
870 )
871 .on_click(move |_, window, cx| {
872 open.update(cx, |this, cx| this.open_action(&id, window, cx))
873 })
874 .child(
875 h_flex()
876 .flex_none()
877 .child(
878 small_button(("action-up", index), IconName::ArrowUp, index > 0).on_click(
879 move |_, _, cx| {
880 cx.stop_propagation();
881 up.update(cx, |this, cx| this.move_action(index, true, cx))
882 },
883 ),
884 )
885 .child(
886 small_button(
887 ("action-down", index),
888 IconName::ArrowDown,
889 index + 1 < action_count,
890 )
891 .on_click(move |_, _, cx| {
892 cx.stop_propagation();
893 down.update(cx, |this, cx| this.move_action(index, false, cx))
894 }),
895 ),
896 )
897 });
898 let write_entries = write_with_entries(&settings, &this);
899 let write_label = write_with_label(&settings);
900 let rescan = this.clone();
901 let found_rows = found.iter().enumerate().map(|(index, hit)| {
902 let (this, profile) = (this.clone(), hit.profile.clone());
903 list_row(
904 ("found-cli", index),
905 None,
906 hit.profile.name.clone(),
907 hit.binary.display().to_string(),
908 Some(hit.profile.command.clone()),
909 )
910 .child(
911 Button::new(("add-found", index))
912 .link()
913 .label(tr("common.add"))
914 .on_click(move |_, window, cx| {
915 let profile = profile.clone();
916 this.update(cx, |this, cx| this.add_agent(profile, window, cx))
917 }),
918 )
919 });
920 let on_computer = tr("agents.settings.on_this_computer");
921 let agents_header = tr("agents.settings.agents_header");
922 let actions_header = tr("agents.settings.actions_header");
923 v_flex()
924 .w_full()
925 .child(section_header(
926 on_computer.clone(),
927 Some(
928 Button::new("rescan-clis")
929 .link()
930 .label(tr("agents.settings.scan_again"))
931 .on_click(move |_, _, cx| rescan.update(cx, |this, cx| this.rescan(cx)))
932 .into_any_element(),
933 ),
934 ))
935 .child(v_flex().w_full().px(px(8.)).children(found_rows).when(
936 found.is_empty(),
937 |rows| {
938 rows.child(
939 div()
940 .px(px(12.))
941 .py(px(8.))
942 .text_size(px(12.))
943 .text_color(theme::text_muted())
944 .child(tr("agents.settings.no_cli_found")),
945 )
946 },
947 ))
948 .child(section_header(
949 agents_header.clone(),
950 Some(link_dropdown("add-agent", "+ Add agent", preset_entries).into_any_element()),
951 ))
952 .child(v_flex().w_full().px(px(8.)).children(agent_rows))
953 .child(section_header(
954 actions_header,
955 Some(add_action.into_any_element()),
956 ))
957 .child(v_flex().w_full().px(px(8.)).children(action_rows))
958 .child(
959 v_flex()
960 .w_full()
961 .px(px(PAGE_PADDING))
962 .pt(px(16.))
963 .gap(px(6.))
964 .child(
965 div()
966 .text_size(px(14.))
967 .font_weight(FontWeight::SEMIBOLD)
968 .child(tr("agents.settings.write_with")),
969 )
970 .child(
971 div()
972 .text_size(px(12.))
973 .text_color(theme::text_muted())
974 .child(tr("agents.settings.rewrite_hint")),
975 )
976 .child(dropdown("write-with", write_label, write_entries)),
977 )
978 .child(resume_toggle(settings.resume_interrupted_runs, this))
979 .child(
980 div()
981 .w_full()
982 .px(px(PAGE_PADDING))
983 .pt(px(16.))
984 .pb(px(16.))
985 .text_size(px(12.))
986 .line_height(relative(1.5))
987 .text_color(theme::text_faint())
988 .child(tr("agents.settings.note")),
989 )
990 }
991}
992
993impl Render for AgentsSettings {
994 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
995 match self.page {
996 Page::List => self.list_page(cx).into_any_element(),
997 Page::Agent => self.agent_page(window, cx).into_any_element(),
998 Page::Action => self.action_page(window, cx).into_any_element(),
999 }
1000 }
1001}
1002
1003#[cfg(test)]
1004mod tests {
1005 use super::{move_item, unique_id};
1006
1007 #[test]
1008 fn ids_get_a_numeric_suffix_when_taken() {
1009 let taken = ["claude", "claude-2"];
1010 let is_taken = |candidate: &str| taken.contains(&candidate);
1011 assert_eq!(unique_id("copilot", is_taken), "copilot");
1012 assert_eq!(unique_id("claude", is_taken), "claude-3");
1013 }
1014
1015 #[test]
1016 fn moving_swaps_neighbours_and_stops_at_the_ends() {
1017 let mut items = vec!["a", "b", "c"];
1018 assert!(move_item(&mut items, 1, true));
1019 assert_eq!(items, ["b", "a", "c"]);
1020 assert!(move_item(&mut items, 1, false));
1021 assert_eq!(items, ["b", "c", "a"]);
1022 assert!(!move_item(&mut items, 0, true));
1023 assert!(!move_item(&mut items, 2, false));
1024 assert_eq!(items, ["b", "c", "a"]);
1025 }
1026}