BlueGit

ict rusty-teams

Files

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

settings_section.rs

settings_section.rs 23.5 KiB Download Raw
1use agents::{AgentAction, 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::{Choice, MenuEntry, PAGE_PADDING, link_dropdown, section_header};
15use crate::runtime;
16use crate::theme;
17use crate::views::widgets::icon;
18
19const NOTE: &str = "Agents get the message, its sender and up to 20 earlier messages. Nothing is sent to Teams without you.";
20const DEFAULT_DISTRO: &str = "Ubuntu";
21const PROMPT_MIN_ROWS: usize = 4;
22const PROMPT_MAX_ROWS: usize = 8;
23
24#[derive(Clone, Copy, PartialEq, Eq)]
25pub(super) enum Page {
26 List,
27 Agent,
28 Action,
29}
30
31#[derive(Clone, PartialEq, Eq)]
32pub(super) enum Probe {
33 Idle,
34 Running,
35 Found(String),
36 Missing(String),
37}
38
39pub(super) struct AgentForm {
40 pub id: String,
41 pub name: Entity<InputState>,
42 pub distro: Entity<InputState>,
43 pub command: Entity<InputState>,
44 pub open_session: Entity<InputState>,
45 pub mcp_flag: Entity<InputState>,
46}
47
48pub(super) struct ActionForm {
49 pub id: String,
50 pub label: Entity<InputState>,
51 pub working_dir: Entity<InputState>,
52 pub prompt: Entity<TextareaState>,
53 pub extra_args: Entity<InputState>,
54}
55
56pub struct AgentsSettings {
57 pub(super) runs: Entity<AgentRuns>,
58 pub(super) page: Page,
59 pub(super) agent_form: Option<AgentForm>,
60 pub(super) action_form: Option<ActionForm>,
61 pub(super) probe: Probe,
62 form_subscriptions: Vec<Subscription>,
63 _runs_subscription: Subscription,
64}
65
66pub fn unique_id(base: &str, taken: impl Fn(&str) -> bool) -> String {
67 if !taken(base) {
68 return base.to_owned();
69 }
70 (2..)
71 .map(|suffix| format!("{base}-{suffix}"))
72 .find(|candidate| !taken(candidate))
73 .unwrap_or_else(|| base.to_owned())
74}
75
76pub fn move_item<T>(items: &mut [T], index: usize, up: bool) -> bool {
77 let target = if up {
78 index.checked_sub(1)
79 } else {
80 Some(index + 1).filter(|target| *target < items.len())
81 };
82 match target {
83 Some(target) if index < items.len() => {
84 items.swap(index, target);
85 true
86 }
87 _ => false,
88 }
89}
90
91impl AgentsSettings {
92 pub fn new(runs: Entity<AgentRuns>, cx: &mut Context<Self>) -> Self {
93 let subscription = cx.observe(&runs, |_, _, cx| cx.notify());
94 AgentsSettings {
95 runs,
96 page: Page::List,
97 agent_form: None,
98 action_form: None,
99 probe: Probe::Idle,
100 form_subscriptions: Vec::new(),
101 _runs_subscription: subscription,
102 }
103 }
104
105 pub(super) fn go_back(&mut self, cx: &mut Context<Self>) {
106 self.page = Page::List;
107 self.agent_form = None;
108 self.action_form = None;
109 self.form_subscriptions.clear();
110 self.probe = Probe::Idle;
111 cx.notify();
112 }
113
114 fn line_input(
115 &mut self,
116 value: &str,
117 window: &mut Window,
118 cx: &mut Context<Self>,
119 on_change: fn(&mut Self, &mut Context<Self>),
120 ) -> Entity<InputState> {
121 let value = value.to_owned();
122 let input = cx.new(|cx| InputState::new(window, cx).default_value(value));
123 self.form_subscriptions.push(cx.subscribe(
124 &input,
125 move |this, _, event: &InputEvent, cx| {
126 if matches!(event, InputEvent::Change) {
127 on_change(this, cx);
128 }
129 },
130 ));
131 input
132 }
133
134 fn open_agent(&mut self, agent_id: &str, window: &mut Window, cx: &mut Context<Self>) {
135 let Some(profile) = self
136 .runs
137 .read(cx)
138 .settings()
139 .agents
140 .iter()
141 .find(|profile| profile.id == agent_id)
142 .cloned()
143 else {
144 return;
145 };
146 self.go_back(cx);
147 let distro = match &profile.environment {
148 Environment::Wsl {
149 distro: Some(distro),
150 } => distro.clone(),
151 _ => String::new(),
152 };
153 self.agent_form = Some(AgentForm {
154 id: profile.id.clone(),
155 name: self.line_input(&profile.name, window, cx, Self::commit_agent),
156 distro: self.line_input(&distro, window, cx, Self::commit_agent),
157 command: self.line_input(&profile.command, window, cx, Self::commit_agent),
158 open_session: self.line_input(
159 &profile.open_session_command,
160 window,
161 cx,
162 Self::commit_agent,
163 ),
164 mcp_flag: self.line_input(&profile.mcp_config_flag, window, cx, Self::commit_agent),
165 });
166 self.page = Page::Agent;
167 cx.notify();
168 }
169
170 fn open_action(&mut self, action_id: &str, window: &mut Window, cx: &mut Context<Self>) {
171 let Some(action) = self
172 .runs
173 .read(cx)
174 .settings()
175 .actions
176 .iter()
177 .find(|action| action.id == action_id)
178 .cloned()
179 else {
180 return;
181 };
182 self.go_back(cx);
183 let prompt = cx.new(|cx| {
184 TextareaState::new(window, cx)
185 .auto_grow(PROMPT_MIN_ROWS, PROMPT_MAX_ROWS)
186 .default_value(action.prompt_template.clone())
187 });
188 self.form_subscriptions
189 .push(cx.subscribe(&prompt, |this, _, event: &InputEvent, cx| {
190 if matches!(event, InputEvent::Change) {
191 this.commit_action(cx);
192 }
193 }));
194 self.action_form = Some(ActionForm {
195 id: action.id.clone(),
196 label: self.line_input(&action.label, window, cx, Self::commit_action),
197 working_dir: self.line_input(&action.working_dir, window, cx, Self::commit_action),
198 prompt,
199 extra_args: self.line_input(&action.extra_args, window, cx, Self::commit_action),
200 });
201 self.page = Page::Action;
202 cx.notify();
203 }
204
205 pub(super) fn commit_agent(&mut self, cx: &mut Context<Self>) {
206 let Some(form) = &self.agent_form else {
207 return;
208 };
209 let id = form.id.clone();
210 let name = form.name.read(cx).value().to_string();
211 let distro = form.distro.read(cx).value().trim().to_owned();
212 let command = form.command.read(cx).value().to_string();
213 let open_session = form.open_session.read(cx).value().to_string();
214 let mcp_flag = form.mcp_flag.read(cx).value().trim().to_owned();
215 self.runs.update(cx, |runs, cx| {
216 runs.update_settings(
217 |settings| {
218 let Some(agent) = settings.agents.iter_mut().find(|agent| agent.id == id)
219 else {
220 return;
221 };
222 agent.name = name;
223 agent.command = command;
224 agent.open_session_command = open_session;
225 agent.mcp_config_flag = mcp_flag;
226 if let Environment::Wsl {
227 distro: Some(current),
228 } = &mut agent.environment
229 {
230 *current = distro;
231 }
232 },
233 cx,
234 )
235 });
236 self.probe = Probe::Idle;
237 }
238
239 pub(super) fn commit_action(&mut self, cx: &mut Context<Self>) {
240 let Some(form) = &self.action_form else {
241 return;
242 };
243 let id = form.id.clone();
244 let label = form.label.read(cx).value().to_string();
245 let working_dir = form.working_dir.read(cx).value().trim().to_owned();
246 let prompt = form.prompt.read(cx).value().to_string();
247 let extra_args = form.extra_args.read(cx).value().to_string();
248 self.runs.update(cx, |runs, cx| {
249 runs.update_settings(
250 |settings| {
251 let Some(action) = settings.actions.iter_mut().find(|action| action.id == id)
252 else {
253 return;
254 };
255 action.label = label;
256 action.working_dir = working_dir;
257 action.prompt_template = prompt;
258 action.extra_args = extra_args;
259 },
260 cx,
261 )
262 });
263 }
264
265 pub(super) fn set_environment(
266 &mut self,
267 environment: Environment,
268 window: &mut Window,
269 cx: &mut Context<Self>,
270 ) {
271 let Some(form) = &self.agent_form else {
272 return;
273 };
274 let id = form.id.clone();
275 if matches!(environment, Environment::Wsl { distro: Some(_) })
276 && form.distro.read(cx).value().trim().is_empty()
277 {
278 form.distro
279 .update(cx, |input, cx| input.set_value(DEFAULT_DISTRO, window, cx));
280 }
281 let distro = form.distro.read(cx).value().trim().to_owned();
282 let environment = match environment {
283 Environment::Wsl { distro: Some(_) } => Environment::Wsl {
284 distro: Some(distro),
285 },
286 other => other,
287 };
288 self.runs.update(cx, |runs, cx| {
289 runs.update_settings(
290 |settings| {
291 if let Some(agent) = settings.agents.iter_mut().find(|agent| agent.id == id) {
292 agent.environment = environment;
293 }
294 },
295 cx,
296 )
297 });
298 self.probe = Probe::Idle;
299 }
300
301 pub(super) fn set_output(&mut self, output: OutputFormat, cx: &mut Context<Self>) {
302 let Some(id) = self.agent_form.as_ref().map(|form| form.id.clone()) else {
303 return;
304 };
305 self.runs.update(cx, |runs, cx| {
306 runs.update_settings(
307 |settings| {
308 if let Some(agent) = settings.agents.iter_mut().find(|agent| agent.id == id) {
309 agent.output = output;
310 }
311 },
312 cx,
313 )
314 });
315 }
316
317 pub(super) fn set_action_agent(&mut self, agent_id: String, cx: &mut Context<Self>) {
318 self.update_action(cx, move |action| action.agent_id = agent_id);
319 }
320
321 pub(super) fn set_ask_extra(&mut self, ask: bool, cx: &mut Context<Self>) {
322 self.update_action(cx, move |action| action.ask_extra_instructions = ask);
323 }
324
325 fn update_action(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut AgentAction)) {
326 let Some(id) = self.action_form.as_ref().map(|form| form.id.clone()) else {
327 return;
328 };
329 self.runs.update(cx, |runs, cx| {
330 runs.update_settings(
331 |settings| {
332 if let Some(action) = settings.actions.iter_mut().find(|action| action.id == id)
333 {
334 change(action);
335 }
336 },
337 cx,
338 )
339 });
340 }
341
342 pub(super) fn insert_placeholder(
343 &mut self,
344 placeholder: &str,
345 window: &mut Window,
346 cx: &mut Context<Self>,
347 ) {
348 let Some(prompt) = self.action_form.as_ref().map(|form| form.prompt.clone()) else {
349 return;
350 };
351 let text = format!("{{{placeholder}}}");
352 prompt.update(cx, |prompt, cx| {
353 prompt.insert(text, window, cx);
354 prompt.focus(window, cx);
355 });
356 self.commit_action(cx);
357 }
358
359 pub(super) fn delete_agent(&mut self, cx: &mut Context<Self>) {
360 let Some(id) = self.agent_form.as_ref().map(|form| form.id.clone()) else {
361 return;
362 };
363 self.go_back(cx);
364 self.runs.update(cx, |runs, cx| {
365 runs.update_settings(
366 |settings| settings.agents.retain(|agent| agent.id != id),
367 cx,
368 )
369 });
370 }
371
372 pub(super) fn delete_action(&mut self, cx: &mut Context<Self>) {
373 let Some(id) = self.action_form.as_ref().map(|form| form.id.clone()) else {
374 return;
375 };
376 self.go_back(cx);
377 self.runs.update(cx, |runs, cx| {
378 runs.update_settings(
379 |settings| settings.actions.retain(|action| action.id != id),
380 cx,
381 )
382 });
383 }
384
385 pub(super) fn test_agent(&mut self, cx: &mut Context<Self>) {
386 let Some(profile) = self.current_agent(cx) else {
387 return;
388 };
389 if profile.command.trim().is_empty() {
390 self.probe = Probe::Missing("The command is empty".to_owned());
391 cx.notify();
392 return;
393 }
394 self.probe = Probe::Running;
395 cx.notify();
396 let invocation = agents::version_check_invocation(&profile);
397 let receiver = runtime::spawn(async move { agents::probe(&invocation).await });
398 cx.spawn(async move |this, cx| {
399 let result = receiver
400 .await
401 .unwrap_or_else(|_| Err("cancelled".to_owned()));
402 this.update(cx, |this, cx| {
403 this.probe = match result {
404 Ok(line) => Probe::Found(line),
405 Err(error) => Probe::Missing(error),
406 };
407 cx.notify();
408 })
409 .ok();
410 })
411 .detach();
412 }
413
414 pub(super) fn current_agent(&self, cx: &App) -> Option<AgentProfile> {
415 let id = &self.agent_form.as_ref()?.id;
416 self.runs
417 .read(cx)
418 .settings()
419 .agents
420 .iter()
421 .find(|agent| &agent.id == id)
422 .cloned()
423 }
424
425 fn add_agent(&mut self, preset: AgentProfile, window: &mut Window, cx: &mut Context<Self>) {
426 let mut profile = preset;
427 let existing: Vec<String> = self
428 .runs
429 .read(cx)
430 .settings()
431 .agents
432 .iter()
433 .map(|agent| agent.id.clone())
434 .collect();
435 profile.id = unique_id(&profile.id, |candidate| {
436 existing.iter().any(|id| id == candidate)
437 });
438 let id = profile.id.clone();
439 self.runs.update(cx, |runs, cx| {
440 runs.update_settings(|settings| settings.agents.push(profile), cx)
441 });
442 self.open_agent(&id, window, cx);
443 }
444
445 fn add_action(&mut self, window: &mut Window, cx: &mut Context<Self>) {
446 let settings = self.runs.read(cx).settings();
447 let agent_id = settings
448 .agents
449 .first()
450 .map(|agent| agent.id.clone())
451 .unwrap_or_default();
452 let mut action = AgentAction::answer_this(&agent_id);
453 action.label = "New action".to_owned();
454 action.id = unique_id("action", |candidate| {
455 settings.actions.iter().any(|action| action.id == candidate)
456 });
457 let id = action.id.clone();
458 self.runs.update(cx, |runs, cx| {
459 runs.update_settings(|settings| settings.actions.push(action), cx)
460 });
461 self.open_action(&id, window, cx);
462 }
463
464 fn move_action(&mut self, index: usize, up: bool, cx: &mut Context<Self>) {
465 self.runs.update(cx, |runs, cx| {
466 runs.update_settings(
467 |settings| {
468 move_item(&mut settings.actions, index, up);
469 },
470 cx,
471 )
472 });
473 }
474}
475
476type Preset = (&'static str, fn() -> AgentProfile);
477
478fn agent_presets() -> [Preset; 4] {
479 fn custom() -> AgentProfile {
480 AgentProfile {
481 id: "custom".to_owned(),
482 name: "Custom agent".to_owned(),
483 environment: Environment::Host,
484 command: String::new(),
485 output: OutputFormat::Text,
486 open_session_command: String::new(),
487 mcp_config_flag: String::new(),
488 }
489 }
490 [
491 ("Claude Code (WSL)", AgentProfile::claude_wsl),
492 ("Claude Code (Windows)", AgentProfile::claude_host),
493 ("Copilot CLI (WSL)", AgentProfile::copilot_wsl),
494 ("Custom", custom),
495 ]
496}
497
498fn list_row(
499 id: (&'static str, usize),
500 leading: Option<AnyElement>,
501 title: String,
502 detail: String,
503 mono: Option<String>,
504) -> Stateful<Div> {
505 h_flex()
506 .id(id)
507 .w_full()
508 .px(px(12.))
509 .py(px(8.))
510 .gap(px(12.))
511 .items_center()
512 .rounded(px(8.))
513 .cursor_pointer()
514 .hover(|row| row.bg(theme::row_hover()))
515 .children(leading)
516 .child(
517 v_flex()
518 .flex_1()
519 .min_w(px(0.))
520 .gap(px(2.))
521 .child(
522 div()
523 .text_size(px(14.))
524 .font_weight(FontWeight::SEMIBOLD)
525 .child(title),
526 )
527 .child(
528 div()
529 .truncate()
530 .text_size(px(12.))
531 .text_color(theme::text_muted())
532 .child(detail),
533 )
534 .children(mono.map(|command| {
535 div()
536 .truncate()
537 .text_size(px(11.))
538 .text_color(theme::text_faint())
539 .child(command)
540 })),
541 )
542}
543
544fn small_button(id: (&'static str, usize), name: IconName, enabled: bool) -> Stateful<Div> {
545 div()
546 .id(id)
547 .size(px(28.))
548 .flex()
549 .flex_none()
550 .items_center()
551 .justify_center()
552 .rounded(px(7.))
553 .when(enabled, |button| {
554 button
555 .cursor_pointer()
556 .hover(|button| button.bg(theme::surface_raised()))
557 })
558 .when(!enabled, |button| button.opacity(0.4))
559 .child(icon(name, 14., theme::text_muted()))
560}
561
562impl AgentsSettings {
563 fn list_page(&mut self, cx: &mut Context<Self>) -> Div {
564 let settings = self.runs.read(cx).settings().clone();
565 let this = cx.entity();
566 let preset_entries: Vec<MenuEntry> = agent_presets()
567 .into_iter()
568 .map(|(label, build)| {
569 let this = this.clone();
570 let choose: Choice = std::rc::Rc::new(move |window, cx| {
571 this.update(cx, |this, cx| this.add_agent(build(), window, cx))
572 });
573 MenuEntry {
574 label: label.to_owned(),
575 selected: false,
576 choose,
577 }
578 })
579 .collect();
580 let add_action = {
581 let this = this.clone();
582 Button::new("add-action")
583 .link()
584 .label("+ Add action")
585 .on_click(move |_, window, cx| {
586 this.update(cx, |this, cx| this.add_action(window, cx))
587 })
588 };
589 let action_count = settings.actions.len();
590 let agent_rows = settings.agents.iter().enumerate().map(|(index, agent)| {
591 let (open, id) = (cx.entity(), agent.id.clone());
592 list_row(
593 ("agent-row", index),
594 Some(
595 div()
596 .size(px(28.))
597 .flex()
598 .flex_none()
599 .items_center()
600 .justify_center()
601 .rounded(px(7.))
602 .bg(theme::surface_raised())
603 .child(icon(IconName::Bot, 14., theme::accent_text()))
604 .into_any_element(),
605 ),
606 agent.name.clone(),
607 environment_label(&agent.environment),
608 Some(agent.command.clone()),
609 )
610 .on_click(move |_, window, cx| {
611 open.update(cx, |this, cx| this.open_agent(&id, window, cx))
612 })
613 });
614 let action_rows = settings.actions.iter().enumerate().map(|(index, action)| {
615 let (open, id) = (cx.entity(), action.id.clone());
616 let (up, down) = (cx.entity(), cx.entity());
617 let agent_name = settings
618 .agents
619 .iter()
620 .find(|agent| agent.id == action.agent_id)
621 .map_or("Unknown agent", |agent| agent.name.as_str());
622 list_row(
623 ("action-row", index),
624 None,
625 action.label.clone(),
626 format!("{agent_name} - {}", action.working_dir),
627 None,
628 )
629 .on_click(move |_, window, cx| {
630 open.update(cx, |this, cx| this.open_action(&id, window, cx))
631 })
632 .child(
633 h_flex()
634 .flex_none()
635 .child(
636 small_button(("action-up", index), IconName::ArrowUp, index > 0).on_click(
637 move |_, _, cx| {
638 cx.stop_propagation();
639 up.update(cx, |this, cx| this.move_action(index, true, cx))
640 },
641 ),
642 )
643 .child(
644 small_button(
645 ("action-down", index),
646 IconName::ArrowDown,
647 index + 1 < action_count,
648 )
649 .on_click(move |_, _, cx| {
650 cx.stop_propagation();
651 down.update(cx, |this, cx| this.move_action(index, false, cx))
652 }),
653 ),
654 )
655 });
656 v_flex()
657 .w_full()
658 .child(section_header(
659 "AGENTS",
660 Some(link_dropdown("add-agent", "+ Add agent", preset_entries).into_any_element()),
661 ))
662 .child(v_flex().w_full().px(px(8.)).children(agent_rows))
663 .child(section_header(
664 "ACTIONS - IN THIS ORDER IN THE MENU",
665 Some(add_action.into_any_element()),
666 ))
667 .child(v_flex().w_full().px(px(8.)).children(action_rows))
668 .child(
669 div()
670 .w_full()
671 .px(px(PAGE_PADDING))
672 .pt(px(16.))
673 .pb(px(16.))
674 .text_size(px(12.))
675 .line_height(relative(1.5))
676 .text_color(theme::text_faint())
677 .child(NOTE),
678 )
679 }
680}
681
682impl Render for AgentsSettings {
683 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
684 match self.page {
685 Page::List => self.list_page(cx).into_any_element(),
686 Page::Agent => self.agent_page(window, cx).into_any_element(),
687 Page::Action => self.action_page(window, cx).into_any_element(),
688 }
689 }
690}
691
692#[cfg(test)]
693mod tests {
694 use super::{move_item, unique_id};
695
696 #[test]
697 fn ids_get_a_numeric_suffix_when_taken() {
698 let taken = ["claude", "claude-2"];
699 let is_taken = |candidate: &str| taken.contains(&candidate);
700 assert_eq!(unique_id("copilot", is_taken), "copilot");
701 assert_eq!(unique_id("claude", is_taken), "claude-3");
702 }
703
704 #[test]
705 fn moving_swaps_neighbours_and_stops_at_the_ends() {
706 let mut items = vec!["a", "b", "c"];
707 assert!(move_item(&mut items, 1, true));
708 assert_eq!(items, ["b", "a", "c"]);
709 assert!(move_item(&mut items, 1, false));
710 assert_eq!(items, ["b", "c", "a"]);
711 assert!(!move_item(&mut items, 0, true));
712 assert!(!move_item(&mut items, 2, false));
713 assert_eq!(items, ["b", "c", "a"]);
714 }
715}