BlueGit

ict rusty-teams

Files

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

start_dialog.rs

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