BlueGit

ict rusty-teams

Files

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

start_dialog.rs

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