BlueGit

ict rusty-teams

Files

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

start_dialog.rs

start_dialog.rs 24.9 KiB Download Raw
1use std::rc::Rc;
2
3use agents::{AgentAction, Environment};
4use chrono::Utc;
5use gpui_kit::assets::IconName;
6use gpui_kit::component::{
7 ActiveTheme as _, h_flex,
8 input::{InputEvent, Textarea, TextareaState},
9 v_flex,
10};
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
13
14use super::runs::{SessionTarget, StartOptions};
15use super::session_options::{
16 SessionOption, default_wsl_distro, external_options, load_external, mark_live_runs, run_options,
17};
18use super::start_dialog_pickers::{MenuPart, MenuRow, locked_select, picker_row, select};
19use super::{
20 mcp_bridge, message_context, raise_notice, runs_handle, start_run, start_run_when_mcp_ready,
21};
22use crate::app_state::AppState;
23use crate::theme;
24use crate::views::widgets::{icon, symbol};
25
26const CARD_WIDTH: f32 = 520.;
27const CARD_RADIUS: f32 = 10.;
28const CARD_PADDING: f32 = 16.;
29const CARD_MARGIN: f32 = 32.;
30const SECTION_GAP: f32 = 12.;
31const BACKDROP_OPACITY: f32 = 0.55;
32const CLOSE_SIZE: f32 = 28.;
33const BUTTON_HEIGHT: f32 = 32.;
34const QUOTE_LINES: usize = 3;
35const FIELD_MIN_ROWS: usize = 3;
36const FIELD_MAX_ROWS: usize = 6;
37const PROMPT_SIZE: f32 = 12.;
38const DISABLED_OPACITY: f32 = 0.5;
39const DEFAULT_PLACEHOLDER: &str = "e.g. only the backend, open a PR when done";
40const SESSION_PLACEHOLDER: &str = "Type the message to send";
41
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub struct StartRequest {
44 pub action_id: String,
45 pub conversation_id: String,
46 pub message_id: String,
47}
48
49pub enum StartDialogEvent {
50 Close,
51}
52
53pub struct StartDialog {
54 app: Entity<AppState>,
55 request: StartRequest,
56 action: AgentAction,
57 subtitle: String,
58 sender: String,
59 quote: String,
60 needs_allow: bool,
61 input: Entity<TextareaState>,
62 show_prompt: bool,
63 environment: Environment,
64 default_working_dir: String,
65 working_dir: String,
66 recent_working_dirs: Vec<String>,
67 offers_sessions: bool,
68 scans_external: bool,
69 run_sessions: Vec<SessionOption>,
70 external_sessions: Vec<SessionOption>,
71 selected_session: Option<SessionOption>,
72 external_generation: u64,
73}
74
75impl EventEmitter<StartDialogEvent> for StartDialog {}
76
77pub fn needs_dialog(action: &AgentAction, chat_allowed: bool) -> bool {
78 action.ask_extra_instructions || !chat_allowed
79}
80
81impl StartDialog {
82 pub fn new(
83 app: Entity<AppState>,
84 request: StartRequest,
85 action: AgentAction,
86 agent_name: &str,
87 window: &mut Window,
88 cx: &mut Context<Self>,
89 ) -> Self {
90 let context =
91 message_context::build(app.read(cx), &request.conversation_id, &request.message_id);
92 let (sender, quote) = context
93 .map(|context| (context.sender, context.message))
94 .unwrap_or_default();
95 let input = cx.new(|cx| {
96 TextareaState::new(window, cx)
97 .auto_grow(FIELD_MIN_ROWS, FIELD_MAX_ROWS)
98 .placeholder(DEFAULT_PLACEHOLDER)
99 });
100 input.update(cx, |input, cx| input.focus(window, cx));
101 cx.subscribe(&input, |_, _, event: &InputEvent, cx| {
102 if matches!(event, InputEvent::Change) {
103 cx.notify();
104 }
105 })
106 .detach();
107 let runs = runs_handle(cx).map(|runs| runs.read(cx));
108 let profile = runs.and_then(|runs| {
109 runs.settings()
110 .agents
111 .iter()
112 .find(|profile| profile.id == action.agent_id)
113 .cloned()
114 });
115 let recent_working_dirs = runs
116 .map(|runs| {
117 runs.settings()
118 .recent_working_dirs_of(&action.agent_id)
119 .to_vec()
120 })
121 .unwrap_or_default();
122 let offers_sessions = profile.as_ref().is_some_and(agents::supports_resume);
123 let run_sessions = match runs {
124 Some(runs) if offers_sessions => {
125 run_options(&runs.for_agent(&action.agent_id), app.read(cx), Utc::now())
126 }
127 _ => Vec::new(),
128 };
129 let mut dialog = StartDialog {
130 app,
131 subtitle: agent_name.to_owned(),
132 needs_allow: !mcp_bridge::chat_allowed(&request.conversation_id, cx),
133 request,
134 sender,
135 quote,
136 input,
137 show_prompt: false,
138 environment: profile
139 .as_ref()
140 .map(|profile| profile.environment.clone())
141 .unwrap_or_default(),
142 default_working_dir: action.working_dir.clone(),
143 working_dir: action.working_dir.clone(),
144 recent_working_dirs,
145 offers_sessions,
146 scans_external: profile
147 .is_some_and(|profile| profile.output == agents::OutputFormat::ClaudeStreamJson)
148 && offers_sessions,
149 run_sessions,
150 external_sessions: Vec::new(),
151 selected_session: None,
152 external_generation: 0,
153 action,
154 };
155 dialog.reload_external(cx);
156 dialog
157 }
158
159 fn reload_external(&mut self, cx: &mut Context<Self>) {
160 self.external_sessions.clear();
161 if !self.scans_external {
162 return;
163 }
164 self.external_generation += 1;
165 let generation = self.external_generation;
166 let environment = self.environment.clone();
167 let working_dir = self.working_dir.clone();
168 let known_session_ids = runs_handle(cx)
169 .map(|runs| runs.read(cx).session_ids())
170 .unwrap_or_default();
171 let demo = crate::agent_api::is_demo(cx);
172 cx.spawn(async move |this, cx| {
173 let scanned_dir = working_dir.clone();
174 let loaded = cx
175 .background_executor()
176 .spawn(async move {
177 load_external(&environment, &scanned_dir, &known_session_ids, demo)
178 })
179 .await;
180 this.update(cx, |this, cx| {
181 if this.external_generation == generation {
182 this.external_sessions =
183 external_options(&loaded.sessions, &working_dir, Utc::now());
184 mark_live_runs(&mut this.run_sessions, &loaded.live_session_ids);
185 cx.notify();
186 }
187 })
188 .ok();
189 })
190 .detach();
191 }
192
193 fn choose_session(
194 &mut self,
195 session: Option<SessionOption>,
196 window: &mut Window,
197 cx: &mut Context<Self>,
198 ) {
199 let placeholder = if session.is_some() {
200 SESSION_PLACEHOLDER
201 } else {
202 DEFAULT_PLACEHOLDER
203 };
204 self.input.update(cx, |input, cx| {
205 input.set_placeholder(placeholder, window, cx)
206 });
207 self.selected_session = session;
208 cx.notify();
209 }
210
211 fn choose_working_dir(&mut self, working_dir: String, cx: &mut Context<Self>) {
212 if self.working_dir != working_dir {
213 self.working_dir = working_dir;
214 self.reload_external(cx);
215 }
216 cx.notify();
217 }
218
219 fn browse(&mut self, cx: &mut Context<Self>) {
220 let receiver = cx.prompt_for_paths(PathPromptOptions {
221 files: false,
222 directories: true,
223 multiple: false,
224 prompt: None,
225 });
226 let environment = self.environment.clone();
227 cx.spawn(async move |this, cx| {
228 let Ok(Ok(Some(paths))) = receiver.await else {
229 return;
230 };
231 let Some(path) = paths.into_iter().next() else {
232 return;
233 };
234 let text = path.to_string_lossy().into_owned();
235 let working_dir = match &environment {
236 Environment::Host => text,
237 Environment::Wsl { distro } => {
238 let chosen = agents::wsl_unc_distro(&text).map(str::to_owned);
239 let wanted = match (&chosen, distro) {
240 (_, Some(distro)) => Some(distro.clone()),
241 (Some(_), None) => {
242 let demo = cx.update(|cx| crate::agent_api::is_demo(cx));
243 cx.background_executor()
244 .spawn(async move { default_wsl_distro(demo) })
245 .await
246 }
247 (None, None) => None,
248 };
249 if chosen.is_some() && wanted.is_some() && chosen != wanted {
250 cx.update(|cx| {
251 raise_notice(
252 "That folder is in a different WSL distro than the agent"
253 .to_owned(),
254 cx,
255 )
256 });
257 return;
258 }
259 agents::linux_path(&text)
260 }
261 };
262 this.update(cx, |this, cx| this.choose_working_dir(working_dir, cx))
263 .ok();
264 })
265 .detach();
266 }
267
268 fn start_options(&self) -> StartOptions {
269 match &self.selected_session {
270 Some(session) => StartOptions {
271 working_dir: None,
272 remember_working_dir: false,
273 session: Some(SessionTarget {
274 session_id: session.session_id.clone(),
275 working_dir: session.working_dir.clone(),
276 fork: session.fork,
277 }),
278 },
279 None => StartOptions {
280 working_dir: (self.working_dir != self.default_working_dir)
281 .then(|| self.working_dir.clone()),
282 remember_working_dir: true,
283 session: None,
284 },
285 }
286 }
287
288 fn start(&mut self, cx: &mut Context<Self>) {
289 let extra = self.input.read(cx).value().trim().to_owned();
290 if self.selected_session.is_some() && extra.is_empty() {
291 return;
292 }
293 let options = self.start_options();
294 if self.needs_allow {
295 mcp_bridge::allow_chat(&self.request.conversation_id, cx);
296 }
297 if self.needs_allow && mcp_bridge::endpoint(cx).is_none() {
298 start_run_when_mcp_ready(
299 self.request.action_id.clone(),
300 self.request.conversation_id.clone(),
301 self.request.message_id.clone(),
302 extra,
303 options,
304 cx,
305 );
306 } else {
307 start_run(
308 &self.request.action_id,
309 &self.request.conversation_id,
310 &self.request.message_id,
311 &extra,
312 options,
313 cx,
314 );
315 }
316 cx.emit(StartDialogEvent::Close);
317 }
318
319 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
320 match event.keystroke.key.as_str() {
321 "escape" => cx.emit(StartDialogEvent::Close),
322 "enter" if event.keystroke.modifiers.control => self.start(cx),
323 _ => return,
324 }
325 cx.stop_propagation();
326 }
327
328 fn header(&self, cx: &mut Context<Self>) -> Div {
329 h_flex()
330 .w_full()
331 .items_start()
332 .gap(px(SECTION_GAP))
333 .child(
334 v_flex()
335 .flex_1()
336 .min_w(px(0.))
337 .child(
338 div()
339 .text_size(px(15.))
340 .font_weight(FontWeight::BOLD)
341 .child(self.action.label.clone()),
342 )
343 .child(
344 div()
345 .truncate()
346 .text_size(px(12.))
347 .text_color(theme::text_muted())
348 .child(self.subtitle.clone()),
349 ),
350 )
351 .child(
352 div()
353 .id("agent-dialog-close")
354 .size(px(CLOSE_SIZE))
355 .flex_none()
356 .flex()
357 .items_center()
358 .justify_center()
359 .rounded_full()
360 .cursor_pointer()
361 .hover(|button| button.bg(theme::popup_hover()))
362 .on_click(cx.listener(|_, _, _, cx| cx.emit(StartDialogEvent::Close)))
363 .child(symbol("close", 16., theme::text_muted())),
364 )
365 }
366
367 fn quote(&self) -> impl IntoElement {
368 let text = format!("{} - {}", self.sender, self.quote);
369 let sender_style = HighlightStyle {
370 color: Some(theme::text()),
371 font_weight: Some(FontWeight::BOLD),
372 ..Default::default()
373 };
374 let sender_range = 0..self.sender.len();
375 div()
376 .w_full()
377 .px(px(12.))
378 .py(px(8.))
379 .rounded(px(8.))
380 .bg(theme::reply_surface())
381 .text_size(px(12.))
382 .line_height(relative(1.4))
383 .text_color(theme::text_soft())
384 .line_clamp(QUOTE_LINES)
385 .child(StyledText::new(text).with_highlights([(sender_range, sender_style)]))
386 }
387
388 fn session_parts(&self, dialog: &Entity<Self>) -> Vec<MenuPart> {
389 let row = |session: &SessionOption| {
390 let dialog = dialog.clone();
391 let chosen = session.clone();
392 MenuPart::Row(MenuRow {
393 label: session.label.clone(),
394 meta: Some(session.meta.clone()),
395 running: session.running,
396 selected: self
397 .selected_session
398 .as_ref()
399 .is_some_and(|selected| selected.session_id == session.session_id),
400 choose: Rc::new(move |window, cx| {
401 let chosen = chosen.clone();
402 dialog.update(cx, |dialog, cx| {
403 dialog.choose_session(Some(chosen), window, cx)
404 });
405 }),
406 })
407 };
408 let new_dialog = dialog.clone();
409 let mut parts = vec![MenuPart::Row(MenuRow {
410 label: "New session".to_owned(),
411 meta: None,
412 running: false,
413 selected: self.selected_session.is_none(),
414 choose: Rc::new(move |window, cx| {
415 new_dialog.update(cx, |dialog, cx| dialog.choose_session(None, window, cx));
416 }),
417 })];
418 if !self.run_sessions.is_empty() {
419 parts.push(MenuPart::Separator);
420 parts.push(MenuPart::Header("Recent sessions".to_owned()));
421 parts.extend(self.run_sessions.iter().map(row));
422 }
423 if !self.external_sessions.is_empty() {
424 parts.push(MenuPart::Separator);
425 parts.push(MenuPart::Header(format!(
426 "Other sessions in {}",
427 self.working_dir
428 )));
429 parts.extend(self.external_sessions.iter().map(row));
430 }
431 parts
432 }
433
434 fn working_dir_parts(&self, dialog: &Entity<Self>) -> Vec<MenuPart> {
435 let row = |working_dir: &str, meta: Option<&str>| {
436 let dialog = dialog.clone();
437 let chosen = working_dir.to_owned();
438 MenuPart::Row(MenuRow {
439 label: working_dir.to_owned(),
440 meta: meta.map(str::to_owned),
441 running: false,
442 selected: self.working_dir == working_dir,
443 choose: Rc::new(move |_, cx| {
444 let chosen = chosen.clone();
445 dialog.update(cx, |dialog, cx| dialog.choose_working_dir(chosen, cx));
446 }),
447 })
448 };
449 let browse_dialog = dialog.clone();
450 let mut parts = vec![
451 MenuPart::Header("Recent".to_owned()),
452 row(&self.default_working_dir, Some("action default")),
453 ];
454 parts.extend(
455 self.recent_working_dirs
456 .iter()
457 .filter(|working_dir| **working_dir != self.default_working_dir)
458 .map(|working_dir| row(working_dir, None)),
459 );
460 parts.push(MenuPart::Separator);
461 parts.push(MenuPart::Row(MenuRow {
462 label: "Browse...".to_owned(),
463 meta: None,
464 running: false,
465 selected: false,
466 choose: Rc::new(move |_, cx| {
467 browse_dialog.update(cx, |dialog, cx| dialog.browse(cx));
468 }),
469 }));
470 parts
471 }
472
473 fn pickers(&self, cx: &mut Context<Self>) -> Div {
474 let dialog = cx.entity();
475 let session_row = self.offers_sessions.then(|| {
476 let (value, meta, running) = match &self.selected_session {
477 Some(session) => (
478 session.label.clone(),
479 Some(session.meta.clone()),
480 session.running,
481 ),
482 None => ("New session".to_owned(), None, false),
483 };
484 picker_row(
485 "Session",
486 select(
487 "agent-dialog-session",
488 value,
489 meta,
490 running,
491 self.session_parts(&dialog),
492 ),
493 )
494 });
495 let working_dir_control = match &self.selected_session {
496 Some(session) => {
497 locked_select(session.working_dir.clone(), "from session").into_any_element()
498 }
499 None => select(
500 "agent-dialog-working-dir",
501 self.working_dir.clone(),
502 None,
503 false,
504 self.working_dir_parts(&dialog),
505 )
506 .into_any_element(),
507 };
508 v_flex()
509 .w_full()
510 .gap(px(8.))
511 .children(session_row)
512 .child(picker_row("Working dir", working_dir_control))
513 }
514
515 fn field(&self, window: &Window, cx: &App) -> Div {
516 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
517 v_flex()
518 .w_full()
519 .gap(px(6.))
520 .child(
521 div()
522 .text_size(px(11.))
523 .font_weight(FontWeight::SEMIBOLD)
524 .text_color(theme::text_faint())
525 .child(if self.selected_session.is_some() {
526 "Message to the session"
527 } else {
528 "Extra instructions (optional)"
529 }),
530 )
531 .child(
532 div()
533 .w_full()
534 .px(px(12.))
535 .py(px(8.))
536 .rounded(px(8.))
537 .bg(theme::surface_raised())
538 .border_1()
539 .border_color(if focused {
540 theme::accent()
541 } else {
542 theme::surface_raised()
543 })
544 .child(Textarea::new(&self.input).appearance(false).bordered(false)),
545 )
546 }
547
548 fn prompt_toggle(&self, cx: &mut Context<Self>) -> Stateful<Div> {
549 h_flex()
550 .id("agent-dialog-prompt-toggle")
551 .gap(px(4.))
552 .items_center()
553 .cursor_pointer()
554 .text_size(px(12.))
555 .text_color(theme::text_muted())
556 .hover(|toggle| toggle.text_color(theme::text_soft()))
557 .child(icon(
558 if self.show_prompt {
559 IconName::ChevronDown
560 } else {
561 IconName::ChevronRight
562 },
563 12.,
564 theme::text_muted(),
565 ))
566 .child("Show prompt")
567 .on_click(cx.listener(|this, _, _, cx| {
568 this.show_prompt = !this.show_prompt;
569 cx.notify();
570 }))
571 }
572
573 fn prompt_box(&self, cx: &mut Context<Self>) -> Div {
574 let extra = self.input.read(cx).value().trim().to_owned();
575 let prompt = if self.selected_session.is_some() {
576 extra
577 } else {
578 message_context::preview_prompt(
579 self.app.read(cx),
580 &self.action,
581 &self.request.conversation_id,
582 &self.request.message_id,
583 &extra,
584 )
585 .unwrap_or_default()
586 };
587 div()
588 .w_full()
589 .max_h(px(160.))
590 .px(px(12.))
591 .py(px(8.))
592 .rounded(px(8.))
593 .bg(theme::reply_surface())
594 .overflow_hidden()
595 .font_family(cx.theme().mono_font_family.clone())
596 .text_size(px(PROMPT_SIZE))
597 .line_height(relative(1.5))
598 .text_color(theme::text_muted())
599 .child(prompt)
600 }
601
602 fn buttons(&self, cx: &mut Context<Self>) -> Div {
603 let blocked =
604 self.selected_session.is_some() && self.input.read(cx).value().trim().is_empty();
605 let start_label = if self.selected_session.is_some() {
606 "Send"
607 } else if self.needs_allow {
608 "Allow and start"
609 } else {
610 "Start"
611 };
612 h_flex()
613 .w_full()
614 .items_center()
615 .gap(px(8.))
616 .child(self.prompt_toggle(cx))
617 .child(div().flex_1())
618 .child(
619 h_flex()
620 .id("agent-dialog-cancel")
621 .h(px(BUTTON_HEIGHT))
622 .px(px(12.))
623 .items_center()
624 .rounded(px(8.))
625 .cursor_pointer()
626 .bg(theme::surface_raised())
627 .hover(|button| button.bg(theme::popup_hover()))
628 .text_size(px(13.))
629 .child("Cancel")
630 .on_click(cx.listener(|_, _, _, cx| cx.emit(StartDialogEvent::Close))),
631 )
632 .child(
633 h_flex()
634 .id("agent-dialog-start")
635 .h(px(BUTTON_HEIGHT))
636 .px(px(12.))
637 .items_center()
638 .rounded(px(8.))
639 .bg(theme::accent())
640 .text_color(theme::on_accent())
641 .text_size(px(13.))
642 .font_weight(FontWeight::SEMIBOLD)
643 .child(start_label)
644 .when(blocked, |button| button.opacity(DISABLED_OPACITY))
645 .when(!blocked, |button| {
646 button
647 .cursor_pointer()
648 .hover(|button| button.bg(theme::accent_text()))
649 .on_click(cx.listener(|this, _, _, cx| this.start(cx)))
650 }),
651 )
652 }
653}
654
655impl Render for StartDialog {
656 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
657 div()
658 .id("agent-dialog-layer")
659 .absolute()
660 .top_0()
661 .left_0()
662 .size_full()
663 .flex()
664 .items_center()
665 .justify_center()
666 .child(
667 div()
668 .id("agent-dialog-backdrop")
669 .absolute()
670 .top_0()
671 .left_0()
672 .size_full()
673 .bg(black().opacity(BACKDROP_OPACITY))
674 .occlude()
675 .on_click(cx.listener(|_, _, _, cx| cx.emit(StartDialogEvent::Close))),
676 )
677 .child(
678 v_flex()
679 .id("agent-dialog-card")
680 .w(px(CARD_WIDTH))
681 .max_w(relative(1.))
682 .max_h(relative(1.))
683 .m(px(CARD_MARGIN))
684 .p(px(CARD_PADDING))
685 .gap(px(SECTION_GAP))
686 .rounded(px(CARD_RADIUS))
687 .bg(theme::popup())
688 .text_color(theme::text())
689 .occlude()
690 .capture_key_down(cx.listener(Self::on_key_down))
691 .child(self.header(cx))
692 .child(self.quote())
693 .when(self.needs_allow, |card| {
694 card.child(
695 div()
696 .text_size(px(12.))
697 .text_color(theme::text_soft())
698 .child("Agents can't see this chat yet."),
699 )
700 })
701 .child(self.pickers(cx))
702 .child(self.field(window, cx))
703 .when(self.show_prompt, |card| card.child(self.prompt_box(cx)))
704 .child(self.buttons(cx)),
705 )
706 }
707}
708
709#[cfg(test)]
710mod tests {
711 use agents::AgentAction;
712
713 use super::needs_dialog;
714
715 #[test]
716 fn the_dialog_shows_for_extra_instructions_or_a_chat_agents_cannot_see() {
717 let quiet = AgentAction::answer_this("claude");
718 let asking = AgentAction::build_this("claude");
719 assert!(!needs_dialog(&quiet, true));
720 assert!(needs_dialog(&quiet, false));
721 assert!(needs_dialog(&asking, true));
722 }
723}