BlueGit

ict rusty-teams

Files

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

start_dialog.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
start_dialog.rs 23.8 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 .text_ellipsis()
366 .child(StyledText::new(text).with_highlights([(sender_range, sender_style)]))
367 }
368
369 fn session_parts(&self, dialog: &Entity<Self>) -> Vec<MenuPart> {
370 let row = |session: &SessionOption| {
371 let dialog = dialog.clone();
372 let chosen = session.clone();
373 MenuPart::Row(MenuRow {
374 label: session.label.clone(),
375 meta: Some(session.meta.clone()),
376 running: session.running,
377 selected: self
378 .selected_session
379 .as_ref()
380 .is_some_and(|selected| selected.session_id == session.session_id),
381 choose: Rc::new(move |window, cx| {
382 let chosen = chosen.clone();
383 dialog.update(cx, |dialog, cx| {
384 dialog.choose_session(Some(chosen), window, cx)
385 });
386 }),
387 })
388 };
389 let new_dialog = dialog.clone();
390 let mut parts = vec![MenuPart::Row(MenuRow {
391 label: "New session".to_owned(),
392 meta: None,
393 running: false,
394 selected: self.selected_session.is_none(),
395 choose: Rc::new(move |window, cx| {
396 new_dialog.update(cx, |dialog, cx| dialog.choose_session(None, window, cx));
397 }),
398 })];
399 if !self.run_sessions.is_empty() {
400 parts.push(MenuPart::Separator);
401 parts.push(MenuPart::Header("Recent sessions".to_owned()));
402 parts.extend(self.run_sessions.iter().map(row));
403 }
404 if !self.external_sessions.is_empty() {
405 parts.push(MenuPart::Separator);
406 parts.push(MenuPart::Header("Other sessions".to_owned()));
407 parts.extend(self.external_sessions.iter().map(row));
408 }
409 parts
410 }
411
412 fn working_dir_parts(&self, dialog: &Entity<Self>) -> Vec<MenuPart> {
413 let row = |working_dir: &str, meta: Option<&str>| {
414 let dialog = dialog.clone();
415 let chosen = working_dir.to_owned();
416 MenuPart::Row(MenuRow {
417 label: working_dir.to_owned(),
418 meta: meta.map(str::to_owned),
419 running: false,
420 selected: self.working_dir == working_dir,
421 choose: Rc::new(move |_, cx| {
422 let chosen = chosen.clone();
423 dialog.update(cx, |dialog, cx| dialog.choose_working_dir(chosen, cx));
424 }),
425 })
426 };
427 let browse_dialog = dialog.clone();
428 let mut parts = vec![
429 MenuPart::Header("Recent".to_owned()),
430 row(&self.default_working_dir, Some("action default")),
431 ];
432 parts.extend(
433 self.recent_working_dirs
434 .iter()
435 .filter(|working_dir| **working_dir != self.default_working_dir)
436 .map(|working_dir| row(working_dir, None)),
437 );
438 parts.push(MenuPart::Separator);
439 parts.push(MenuPart::Row(MenuRow {
440 label: "Browse...".to_owned(),
441 meta: None,
442 running: false,
443 selected: false,
444 choose: Rc::new(move |_, cx| {
445 browse_dialog.update(cx, |dialog, cx| dialog.browse(cx));
446 }),
447 }));
448 parts
449 }
450
451 fn pickers(&self, cx: &mut Context<Self>) -> Div {
452 let dialog = cx.entity();
453 let session_row = self.offers_sessions.then(|| {
454 let (value, meta, running) = match &self.selected_session {
455 Some(session) => (
456 session.label.clone(),
457 Some(session.meta.clone()),
458 session.running,
459 ),
460 None => ("New session".to_owned(), None, false),
461 };
462 picker_row(
463 "Session",
464 select(
465 "agent-dialog-session",
466 value,
467 meta,
468 running,
469 self.session_parts(&dialog),
470 ),
471 )
472 });
473 let working_dir_control = match &self.selected_session {
474 Some(session) => {
475 locked_select(session.working_dir.clone(), "from session").into_any_element()
476 }
477 None => select(
478 "agent-dialog-working-dir",
479 self.working_dir.clone(),
480 None,
481 false,
482 self.working_dir_parts(&dialog),
483 )
484 .into_any_element(),
485 };
486 v_flex()
487 .w_full()
488 .gap(px(8.))
489 .children(session_row)
490 .child(picker_row("Working dir", working_dir_control))
491 }
492
493 fn field(&self, window: &Window, cx: &App) -> Div {
494 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
495 v_flex()
496 .w_full()
497 .gap(px(6.))
498 .child(
499 div()
500 .text_size(px(11.))
501 .font_weight(FontWeight::SEMIBOLD)
502 .text_color(theme::text_faint())
503 .child(if self.selected_session.is_some() {
504 "Message to the session"
505 } else {
506 "Extra instructions (optional)"
507 }),
508 )
509 .child(
510 div()
511 .w_full()
512 .px(px(12.))
513 .py(px(8.))
514 .rounded(px(8.))
515 .bg(theme::surface_raised())
516 .border_1()
517 .border_color(if focused {
518 theme::accent()
519 } else {
520 theme::surface_raised()
521 })
522 .child(Textarea::new(&self.input).appearance(false).bordered(false)),
523 )
524 }
525
526 fn prompt_toggle(&self, cx: &mut Context<Self>) -> Stateful<Div> {
527 h_flex()
528 .id("agent-dialog-prompt-toggle")
529 .gap(px(4.))
530 .items_center()
531 .cursor_pointer()
532 .text_size(px(12.))
533 .text_color(theme::text_muted())
534 .hover(|toggle| toggle.text_color(theme::text_soft()))
535 .child(icon(
536 if self.show_prompt {
537 IconName::ChevronDown
538 } else {
539 IconName::ChevronRight
540 },
541 12.,
542 theme::text_muted(),
543 ))
544 .child("Show prompt")
545 .on_click(cx.listener(|this, _, _, cx| {
546 this.show_prompt = !this.show_prompt;
547 cx.notify();
548 }))
549 }
550
551 fn prompt_box(&self, cx: &mut Context<Self>) -> Div {
552 let extra = self.input.read(cx).value().trim().to_owned();
553 let prompt = if self.selected_session.is_some() {
554 extra
555 } else {
556 message_context::preview_prompt(
557 self.app.read(cx),
558 &self.action,
559 &self.request.conversation_id,
560 &self.request.message_id,
561 &extra,
562 )
563 .unwrap_or_default()
564 };
565 div()
566 .w_full()
567 .max_h(px(160.))
568 .px(px(12.))
569 .py(px(8.))
570 .rounded(px(8.))
571 .bg(theme::reply_surface())
572 .overflow_hidden()
573 .font_family(cx.theme().mono_font_family.clone())
574 .text_size(px(PROMPT_SIZE))
575 .line_height(relative(1.5))
576 .text_color(theme::text_muted())
577 .child(prompt)
578 }
579
580 fn buttons(&self, cx: &mut Context<Self>) -> Div {
581 let blocked =
582 self.selected_session.is_some() && self.input.read(cx).value().trim().is_empty();
583 let start_label = if self.selected_session.is_some() {
584 "Send"
585 } else if self.needs_allow {
586 "Allow and start"
587 } else {
588 "Start"
589 };
590 h_flex()
591 .w_full()
592 .items_center()
593 .gap(px(8.))
594 .child(self.prompt_toggle(cx))
595 .child(div().flex_1())
596 .child(
597 h_flex()
598 .id("agent-dialog-cancel")
599 .h(px(BUTTON_HEIGHT))
600 .px(px(12.))
601 .items_center()
602 .rounded(px(8.))
603 .cursor_pointer()
604 .bg(theme::surface_raised())
605 .hover(|button| button.bg(theme::popup_hover()))
606 .text_size(px(13.))
607 .child("Cancel")
608 .on_click(cx.listener(|_, _, _, cx| cx.emit(StartDialogEvent::Close))),
609 )
610 .child(
611 h_flex()
612 .id("agent-dialog-start")
613 .h(px(BUTTON_HEIGHT))
614 .px(px(12.))
615 .items_center()
616 .rounded(px(8.))
617 .bg(theme::accent())
618 .text_color(theme::on_accent())
619 .text_size(px(13.))
620 .font_weight(FontWeight::SEMIBOLD)
621 .child(start_label)
622 .when(blocked, |button| button.opacity(DISABLED_OPACITY))
623 .when(!blocked, |button| {
624 button
625 .cursor_pointer()
626 .hover(|button| button.bg(theme::accent_text()))
627 .on_click(cx.listener(|this, _, _, cx| this.start(cx)))
628 }),
629 )
630 }
631}
632
633impl Render for StartDialog {
634 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
635 div()
636 .id("agent-dialog-layer")
637 .absolute()
638 .top_0()
639 .left_0()
640 .size_full()
641 .flex()
642 .items_center()
643 .justify_center()
644 .child(
645 div()
646 .id("agent-dialog-backdrop")
647 .absolute()
648 .top_0()
649 .left_0()
650 .size_full()
651 .bg(black().opacity(BACKDROP_OPACITY))
652 .occlude()
653 .on_click(cx.listener(|_, _, _, cx| cx.emit(StartDialogEvent::Close))),
654 )
655 .child(
656 v_flex()
657 .id("agent-dialog-card")
658 .w(px(CARD_WIDTH))
659 .max_w(relative(1.))
660 .max_h(relative(1.))
661 .m(px(CARD_MARGIN))
662 .p(px(CARD_PADDING))
663 .gap(px(SECTION_GAP))
664 .rounded(px(CARD_RADIUS))
665 .dialog_surface()
666 .text_color(theme::text())
667 .occlude()
668 .capture_key_down(cx.listener(Self::on_key_down))
669 .child(self.header(cx))
670 .child(self.quote())
671 .when(self.needs_allow, |card| {
672 card.child(
673 div()
674 .text_size(px(12.))
675 .text_color(theme::text_soft())
676 .child("Agents can't see this chat yet."),
677 )
678 })
679 .child(self.pickers(cx))
680 .child(self.field(window, cx))
681 .when(self.show_prompt, |card| card.child(self.prompt_box(cx)))
682 .child(self.buttons(cx)),
683 )
684 }
685}