1use crate::agent_model_selector::AgentModelSelector;
2use crate::buffer_codegen::BufferCodegen;
3use crate::context::ContextCreasesAddon;
4use crate::context_picker::{ContextPicker, ContextPickerCompletionProvider};
5use crate::context_store::ContextStore;
6use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
7use crate::message_editor::{extract_message_creases, insert_message_creases};
8use crate::terminal_codegen::TerminalCodegen;
9use crate::thread_store::{TextThreadStore, ThreadStore};
10use crate::{CycleNextInlineAssist, CyclePreviousInlineAssist, ModelUsageContext};
11use crate::{RemoveAllContext, ToggleContextPicker};
12use assistant_context_editor::language_model_selector::ToggleModelSelector;
13use client::ErrorExt;
14use collections::VecDeque;
15use db::kvp::Dismissable;
16use editor::actions::Paste;
17use editor::display_map::EditorMargins;
18use editor::{
19 ContextMenuOptions, Editor, EditorElement, EditorEvent, EditorMode, EditorStyle, MultiBuffer,
20 actions::{MoveDown, MoveUp},
21};
22use feature_flags::{FeatureFlagAppExt as _, ZedProFeatureFlag};
23use fs::Fs;
24use gpui::{
25 AnyElement, App, ClickEvent, Context, CursorStyle, Entity, EventEmitter, FocusHandle,
26 Focusable, FontWeight, Subscription, TextStyle, WeakEntity, Window, anchored, deferred, point,
27};
28use language_model::{LanguageModel, LanguageModelRegistry};
29use parking_lot::Mutex;
30use settings::Settings;
31use std::cmp;
32use std::rc::Rc;
33use std::sync::Arc;
34use theme::ThemeSettings;
35use ui::utils::WithRemSize;
36use ui::{
37 CheckboxWithLabel, IconButtonShape, KeyBinding, Popover, PopoverMenuHandle, Tooltip, prelude::*,
38};
39use workspace::Workspace;
40
41pub struct PromptEditor<T> {
42 pub editor: Entity<Editor>,
43 mode: PromptEditorMode,
44 context_store: Entity<ContextStore>,
45 context_strip: Entity<ContextStrip>,
46 context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
47 model_selector: Entity<AgentModelSelector>,
48 edited_since_done: bool,
49 prompt_history: VecDeque<String>,
50 prompt_history_ix: Option<usize>,
51 pending_prompt: String,
52 _codegen_subscription: Subscription,
53 editor_subscriptions: Vec<Subscription>,
54 _context_strip_subscription: Subscription,
55 show_rate_limit_notice: bool,
56 _phantom: std::marker::PhantomData<T>,
57}
58
59impl<T: 'static> EventEmitter<PromptEditorEvent> for PromptEditor<T> {}
60
61impl<T: 'static> Render for PromptEditor<T> {
62 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
63 let ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
64 let mut buttons = Vec::new();
65
66 const RIGHT_PADDING: Pixels = px(9.);
67
68 let (left_gutter_width, right_padding) = match &self.mode {
69 PromptEditorMode::Buffer {
70 id: _,
71 codegen,
72 editor_margins,
73 } => {
74 let codegen = codegen.read(cx);
75
76 if codegen.alternative_count(cx) > 1 {
77 buttons.push(self.render_cycle_controls(&codegen, cx));
78 }
79
80 let editor_margins = editor_margins.lock();
81 let gutter = editor_margins.gutter;
82
83 let left_gutter_width = gutter.full_width() + (gutter.margin / 2.0);
84 let right_padding = editor_margins.right + RIGHT_PADDING;
85
86 (left_gutter_width, right_padding)
87 }
88 PromptEditorMode::Terminal { .. } => {
89 // Give the equivalent of the same left-padding that we're using on the right
90 (Pixels::from(40.0), Pixels::from(24.))
91 }
92 };
93
94 let bottom_padding = match &self.mode {
95 PromptEditorMode::Buffer { .. } => Pixels::from(0.),
96 PromptEditorMode::Terminal { .. } => Pixels::from(8.0),
97 };
98
99 buttons.extend(self.render_buttons(window, cx));
100
101 v_flex()
102 .key_context("PromptEditor")
103 .capture_action(cx.listener(Self::paste))
104 .bg(cx.theme().colors().editor_background)
105 .block_mouse_except_scroll()
106 .gap_0p5()
107 .border_y_1()
108 .border_color(cx.theme().status().info_border)
109 .size_full()
110 .pt_0p5()
111 .pb(bottom_padding)
112 .pr(right_padding)
113 .child(
114 h_flex()
115 .items_start()
116 .cursor(CursorStyle::Arrow)
117 .on_action(cx.listener(Self::toggle_context_picker))
118 .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
119 this.model_selector
120 .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
121 }))
122 .on_action(cx.listener(Self::confirm))
123 .on_action(cx.listener(Self::cancel))
124 .on_action(cx.listener(Self::move_up))
125 .on_action(cx.listener(Self::move_down))
126 .on_action(cx.listener(Self::remove_all_context))
127 .capture_action(cx.listener(Self::cycle_prev))
128 .capture_action(cx.listener(Self::cycle_next))
129 .child(
130 WithRemSize::new(ui_font_size)
131 .flex()
132 .flex_row()
133 .flex_shrink_0()
134 .items_center()
135 .h_full()
136 .w(left_gutter_width)
137 .justify_center()
138 .gap_2()
139 .child(self.render_close_button(cx))
140 .map(|el| {
141 let CodegenStatus::Error(error) = self.codegen_status(cx) else {
142 return el;
143 };
144
145 let error_message = SharedString::from(error.to_string());
146 if error.error_code() == proto::ErrorCode::RateLimitExceeded
147 && cx.has_flag::<ZedProFeatureFlag>()
148 {
149 el.child(
150 v_flex()
151 .child(
152 IconButton::new(
153 "rate-limit-error",
154 IconName::XCircle,
155 )
156 .toggle_state(self.show_rate_limit_notice)
157 .shape(IconButtonShape::Square)
158 .icon_size(IconSize::Small)
159 .on_click(
160 cx.listener(Self::toggle_rate_limit_notice),
161 ),
162 )
163 .children(self.show_rate_limit_notice.then(|| {
164 deferred(
165 anchored()
166 .position_mode(
167 gpui::AnchoredPositionMode::Local,
168 )
169 .position(point(px(0.), px(24.)))
170 .anchor(gpui::Corner::TopLeft)
171 .child(self.render_rate_limit_notice(cx)),
172 )
173 })),
174 )
175 } else {
176 el.child(
177 div()
178 .id("error")
179 .tooltip(Tooltip::text(error_message))
180 .child(
181 Icon::new(IconName::XCircle)
182 .size(IconSize::Small)
183 .color(Color::Error),
184 ),
185 )
186 }
187 }),
188 )
189 .child(
190 h_flex()
191 .w_full()
192 .justify_between()
193 .child(div().flex_1().child(self.render_editor(window, cx)))
194 .child(
195 WithRemSize::new(ui_font_size)
196 .flex()
197 .flex_row()
198 .items_center()
199 .gap_1()
200 .children(buttons),
201 ),
202 ),
203 )
204 .child(
205 WithRemSize::new(ui_font_size)
206 .flex()
207 .flex_row()
208 .items_center()
209 .child(h_flex().flex_shrink_0().w(left_gutter_width))
210 .child(
211 h_flex()
212 .w_full()
213 .pl_1()
214 .items_start()
215 .justify_between()
216 .child(self.context_strip.clone())
217 .child(self.model_selector.clone()),
218 ),
219 )
220 }
221}
222
223impl<T: 'static> Focusable for PromptEditor<T> {
224 fn focus_handle(&self, cx: &App) -> FocusHandle {
225 self.editor.focus_handle(cx)
226 }
227}
228
229impl<T: 'static> PromptEditor<T> {
230 const MAX_LINES: u8 = 8;
231
232 fn codegen_status<'a>(&'a self, cx: &'a App) -> &'a CodegenStatus {
233 match &self.mode {
234 PromptEditorMode::Buffer { codegen, .. } => codegen.read(cx).status(cx),
235 PromptEditorMode::Terminal { codegen, .. } => &codegen.read(cx).status,
236 }
237 }
238
239 fn subscribe_to_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
240 self.editor_subscriptions.clear();
241 self.editor_subscriptions.push(cx.subscribe_in(
242 &self.editor,
243 window,
244 Self::handle_prompt_editor_events,
245 ));
246 }
247
248 pub fn set_show_cursor_when_unfocused(
249 &mut self,
250 show_cursor_when_unfocused: bool,
251 cx: &mut Context<Self>,
252 ) {
253 self.editor.update(cx, |editor, cx| {
254 editor.set_show_cursor_when_unfocused(show_cursor_when_unfocused, cx)
255 });
256 }
257
258 pub fn unlink(&mut self, window: &mut Window, cx: &mut Context<Self>) {
259 let prompt = self.prompt(cx);
260 let existing_creases = self.editor.update(cx, extract_message_creases);
261
262 let focus = self.editor.focus_handle(cx).contains_focused(window, cx);
263 self.editor = cx.new(|cx| {
264 let mut editor = Editor::auto_height(1, Self::MAX_LINES as usize, window, cx);
265 editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
266 editor.set_placeholder_text("Add a prompt…", cx);
267 editor.set_text(prompt, window, cx);
268 insert_message_creases(
269 &mut editor,
270 &existing_creases,
271 &self.context_store,
272 window,
273 cx,
274 );
275
276 if focus {
277 window.focus(&editor.focus_handle(cx));
278 }
279 editor
280 });
281 self.subscribe_to_editor(window, cx);
282 }
283
284 pub fn placeholder_text(mode: &PromptEditorMode, window: &mut Window, cx: &mut App) -> String {
285 let action = match mode {
286 PromptEditorMode::Buffer { codegen, .. } => {
287 if codegen.read(cx).is_insertion {
288 "Generate"
289 } else {
290 "Transform"
291 }
292 }
293 PromptEditorMode::Terminal { .. } => "Generate",
294 };
295
296 let agent_panel_keybinding =
297 ui::text_for_action(&zed_actions::assistant::ToggleFocus, window, cx)
298 .map(|keybinding| format!("{keybinding} to chat ― "))
299 .unwrap_or_default();
300
301 format!("{action}… ({agent_panel_keybinding}↓↑ for history)")
302 }
303
304 pub fn prompt(&self, cx: &App) -> String {
305 self.editor.read(cx).text(cx)
306 }
307
308 fn paste(&mut self, _: &Paste, _window: &mut Window, cx: &mut Context<Self>) {
309 crate::active_thread::attach_pasted_images_as_context(&self.context_store, cx);
310 }
311
312 fn toggle_rate_limit_notice(
313 &mut self,
314 _: &ClickEvent,
315 window: &mut Window,
316 cx: &mut Context<Self>,
317 ) {
318 self.show_rate_limit_notice = !self.show_rate_limit_notice;
319 if self.show_rate_limit_notice {
320 window.focus(&self.editor.focus_handle(cx));
321 }
322 cx.notify();
323 }
324
325 fn handle_prompt_editor_events(
326 &mut self,
327 _: &Entity<Editor>,
328 event: &EditorEvent,
329 window: &mut Window,
330 cx: &mut Context<Self>,
331 ) {
332 match event {
333 EditorEvent::Edited { .. } => {
334 if let Some(workspace) = window.root::<Workspace>().flatten() {
335 workspace.update(cx, |workspace, cx| {
336 let is_via_ssh = workspace.project().read(cx).is_via_ssh();
337
338 workspace
339 .client()
340 .telemetry()
341 .log_edit_event("inline assist", is_via_ssh);
342 });
343 }
344 let prompt = self.editor.read(cx).text(cx);
345 if self
346 .prompt_history_ix
347 .map_or(true, |ix| self.prompt_history[ix] != prompt)
348 {
349 self.prompt_history_ix.take();
350 self.pending_prompt = prompt;
351 }
352
353 self.edited_since_done = true;
354 cx.notify();
355 }
356 EditorEvent::Blurred => {
357 if self.show_rate_limit_notice {
358 self.show_rate_limit_notice = false;
359 cx.notify();
360 }
361 }
362 _ => {}
363 }
364 }
365
366 fn toggle_context_picker(
367 &mut self,
368 _: &ToggleContextPicker,
369 window: &mut Window,
370 cx: &mut Context<Self>,
371 ) {
372 self.context_picker_menu_handle.toggle(window, cx);
373 }
374
375 pub fn remove_all_context(
376 &mut self,
377 _: &RemoveAllContext,
378 _window: &mut Window,
379 cx: &mut Context<Self>,
380 ) {
381 self.context_store.update(cx, |store, cx| store.clear(cx));
382 cx.notify();
383 }
384
385 fn cancel(
386 &mut self,
387 _: &editor::actions::Cancel,
388 _window: &mut Window,
389 cx: &mut Context<Self>,
390 ) {
391 match self.codegen_status(cx) {
392 CodegenStatus::Idle | CodegenStatus::Done | CodegenStatus::Error(_) => {
393 cx.emit(PromptEditorEvent::CancelRequested);
394 }
395 CodegenStatus::Pending => {
396 cx.emit(PromptEditorEvent::StopRequested);
397 }
398 }
399 }
400
401 fn confirm(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
402 match self.codegen_status(cx) {
403 CodegenStatus::Idle => {
404 cx.emit(PromptEditorEvent::StartRequested);
405 }
406 CodegenStatus::Pending => {
407 cx.emit(PromptEditorEvent::DismissRequested);
408 }
409 CodegenStatus::Done => {
410 if self.edited_since_done {
411 cx.emit(PromptEditorEvent::StartRequested);
412 } else {
413 cx.emit(PromptEditorEvent::ConfirmRequested { execute: false });
414 }
415 }
416 CodegenStatus::Error(_) => {
417 cx.emit(PromptEditorEvent::StartRequested);
418 }
419 }
420 }
421
422 fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
423 if let Some(ix) = self.prompt_history_ix {
424 if ix > 0 {
425 self.prompt_history_ix = Some(ix - 1);
426 let prompt = self.prompt_history[ix - 1].as_str();
427 self.editor.update(cx, |editor, cx| {
428 editor.set_text(prompt, window, cx);
429 editor.move_to_beginning(&Default::default(), window, cx);
430 });
431 }
432 } else if !self.prompt_history.is_empty() {
433 self.prompt_history_ix = Some(self.prompt_history.len() - 1);
434 let prompt = self.prompt_history[self.prompt_history.len() - 1].as_str();
435 self.editor.update(cx, |editor, cx| {
436 editor.set_text(prompt, window, cx);
437 editor.move_to_beginning(&Default::default(), window, cx);
438 });
439 }
440 }
441
442 fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
443 if let Some(ix) = self.prompt_history_ix {
444 if ix < self.prompt_history.len() - 1 {
445 self.prompt_history_ix = Some(ix + 1);
446 let prompt = self.prompt_history[ix + 1].as_str();
447 self.editor.update(cx, |editor, cx| {
448 editor.set_text(prompt, window, cx);
449 editor.move_to_end(&Default::default(), window, cx)
450 });
451 } else {
452 self.prompt_history_ix = None;
453 let prompt = self.pending_prompt.as_str();
454 self.editor.update(cx, |editor, cx| {
455 editor.set_text(prompt, window, cx);
456 editor.move_to_end(&Default::default(), window, cx)
457 });
458 }
459 } else if self.context_strip.read(cx).has_context_items(cx) {
460 self.context_strip.focus_handle(cx).focus(window);
461 }
462 }
463
464 fn render_buttons(&self, _window: &mut Window, cx: &mut Context<Self>) -> Vec<AnyElement> {
465 let mode = match &self.mode {
466 PromptEditorMode::Buffer { codegen, .. } => {
467 let codegen = codegen.read(cx);
468 if codegen.is_insertion {
469 GenerationMode::Generate
470 } else {
471 GenerationMode::Transform
472 }
473 }
474 PromptEditorMode::Terminal { .. } => GenerationMode::Generate,
475 };
476
477 let codegen_status = self.codegen_status(cx);
478
479 match codegen_status {
480 CodegenStatus::Idle => {
481 vec![
482 Button::new("start", mode.start_label())
483 .label_size(LabelSize::Small)
484 .icon(IconName::Return)
485 .icon_size(IconSize::XSmall)
486 .icon_color(Color::Muted)
487 .on_click(
488 cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::StartRequested)),
489 )
490 .into_any_element(),
491 ]
492 }
493 CodegenStatus::Pending => vec![
494 IconButton::new("stop", IconName::Stop)
495 .icon_color(Color::Error)
496 .shape(IconButtonShape::Square)
497 .tooltip(move |window, cx| {
498 Tooltip::with_meta(
499 mode.tooltip_interrupt(),
500 Some(&menu::Cancel),
501 "Changes won't be discarded",
502 window,
503 cx,
504 )
505 })
506 .on_click(cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::StopRequested)))
507 .into_any_element(),
508 ],
509 CodegenStatus::Done | CodegenStatus::Error(_) => {
510 let has_error = matches!(codegen_status, CodegenStatus::Error(_));
511 if has_error || self.edited_since_done {
512 vec![
513 IconButton::new("restart", IconName::RotateCw)
514 .icon_color(Color::Info)
515 .shape(IconButtonShape::Square)
516 .tooltip(move |window, cx| {
517 Tooltip::with_meta(
518 mode.tooltip_restart(),
519 Some(&menu::Confirm),
520 "Changes will be discarded",
521 window,
522 cx,
523 )
524 })
525 .on_click(cx.listener(|_, _, _, cx| {
526 cx.emit(PromptEditorEvent::StartRequested);
527 }))
528 .into_any_element(),
529 ]
530 } else {
531 let accept = IconButton::new("accept", IconName::Check)
532 .icon_color(Color::Info)
533 .shape(IconButtonShape::Square)
534 .tooltip(move |window, cx| {
535 Tooltip::for_action(mode.tooltip_accept(), &menu::Confirm, window, cx)
536 })
537 .on_click(cx.listener(|_, _, _, cx| {
538 cx.emit(PromptEditorEvent::ConfirmRequested { execute: false });
539 }))
540 .into_any_element();
541
542 match &self.mode {
543 PromptEditorMode::Terminal { .. } => vec![
544 accept,
545 IconButton::new("confirm", IconName::Play)
546 .icon_color(Color::Info)
547 .shape(IconButtonShape::Square)
548 .tooltip(|window, cx| {
549 Tooltip::for_action(
550 "Execute Generated Command",
551 &menu::SecondaryConfirm,
552 window,
553 cx,
554 )
555 })
556 .on_click(cx.listener(|_, _, _, cx| {
557 cx.emit(PromptEditorEvent::ConfirmRequested { execute: true });
558 }))
559 .into_any_element(),
560 ],
561 PromptEditorMode::Buffer { .. } => vec![accept],
562 }
563 }
564 }
565 }
566 }
567
568 fn cycle_prev(
569 &mut self,
570 _: &CyclePreviousInlineAssist,
571 _: &mut Window,
572 cx: &mut Context<Self>,
573 ) {
574 match &self.mode {
575 PromptEditorMode::Buffer { codegen, .. } => {
576 codegen.update(cx, |codegen, cx| codegen.cycle_prev(cx));
577 }
578 PromptEditorMode::Terminal { .. } => {
579 // no cycle buttons in terminal mode
580 }
581 }
582 }
583
584 fn cycle_next(&mut self, _: &CycleNextInlineAssist, _: &mut Window, cx: &mut Context<Self>) {
585 match &self.mode {
586 PromptEditorMode::Buffer { codegen, .. } => {
587 codegen.update(cx, |codegen, cx| codegen.cycle_next(cx));
588 }
589 PromptEditorMode::Terminal { .. } => {
590 // no cycle buttons in terminal mode
591 }
592 }
593 }
594
595 fn render_close_button(&self, cx: &mut Context<Self>) -> AnyElement {
596 IconButton::new("cancel", IconName::Close)
597 .icon_color(Color::Muted)
598 .shape(IconButtonShape::Square)
599 .tooltip(Tooltip::text("Close Assistant"))
600 .on_click(cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::CancelRequested)))
601 .into_any_element()
602 }
603
604 fn render_cycle_controls(&self, codegen: &BufferCodegen, cx: &Context<Self>) -> AnyElement {
605 let disabled = matches!(codegen.status(cx), CodegenStatus::Idle);
606
607 let model_registry = LanguageModelRegistry::read_global(cx);
608 let default_model = model_registry.default_model().map(|default| default.model);
609 let alternative_models = model_registry.inline_alternative_models();
610
611 let get_model_name = |index: usize| -> String {
612 let name = |model: &Arc<dyn LanguageModel>| model.name().0.to_string();
613
614 match index {
615 0 => default_model.as_ref().map_or_else(String::new, name),
616 index if index <= alternative_models.len() => alternative_models
617 .get(index - 1)
618 .map_or_else(String::new, name),
619 _ => String::new(),
620 }
621 };
622
623 let total_models = alternative_models.len() + 1;
624
625 if total_models <= 1 {
626 return div().into_any_element();
627 }
628
629 let current_index = codegen.active_alternative;
630 let prev_index = (current_index + total_models - 1) % total_models;
631 let next_index = (current_index + 1) % total_models;
632
633 let prev_model_name = get_model_name(prev_index);
634 let next_model_name = get_model_name(next_index);
635
636 h_flex()
637 .child(
638 IconButton::new("previous", IconName::ChevronLeft)
639 .icon_color(Color::Muted)
640 .disabled(disabled || current_index == 0)
641 .shape(IconButtonShape::Square)
642 .tooltip({
643 let focus_handle = self.editor.focus_handle(cx);
644 move |window, cx| {
645 cx.new(|cx| {
646 let mut tooltip = Tooltip::new("Previous Alternative").key_binding(
647 KeyBinding::for_action_in(
648 &CyclePreviousInlineAssist,
649 &focus_handle,
650 window,
651 cx,
652 ),
653 );
654 if !disabled && current_index != 0 {
655 tooltip = tooltip.meta(prev_model_name.clone());
656 }
657 tooltip
658 })
659 .into()
660 }
661 })
662 .on_click(cx.listener(|this, _, window, cx| {
663 this.cycle_prev(&CyclePreviousInlineAssist, window, cx);
664 })),
665 )
666 .child(
667 Label::new(format!(
668 "{}/{}",
669 codegen.active_alternative + 1,
670 codegen.alternative_count(cx)
671 ))
672 .size(LabelSize::Small)
673 .color(if disabled {
674 Color::Disabled
675 } else {
676 Color::Muted
677 }),
678 )
679 .child(
680 IconButton::new("next", IconName::ChevronRight)
681 .icon_color(Color::Muted)
682 .disabled(disabled || current_index == total_models - 1)
683 .shape(IconButtonShape::Square)
684 .tooltip({
685 let focus_handle = self.editor.focus_handle(cx);
686 move |window, cx| {
687 cx.new(|cx| {
688 let mut tooltip = Tooltip::new("Next Alternative").key_binding(
689 KeyBinding::for_action_in(
690 &CycleNextInlineAssist,
691 &focus_handle,
692 window,
693 cx,
694 ),
695 );
696 if !disabled && current_index != total_models - 1 {
697 tooltip = tooltip.meta(next_model_name.clone());
698 }
699 tooltip
700 })
701 .into()
702 }
703 })
704 .on_click(cx.listener(|this, _, window, cx| {
705 this.cycle_next(&CycleNextInlineAssist, window, cx)
706 })),
707 )
708 .into_any_element()
709 }
710
711 fn render_rate_limit_notice(&self, cx: &mut Context<Self>) -> impl IntoElement {
712 Popover::new().child(
713 v_flex()
714 .occlude()
715 .p_2()
716 .child(
717 Label::new("Out of Tokens")
718 .size(LabelSize::Small)
719 .weight(FontWeight::BOLD),
720 )
721 .child(Label::new(
722 "Try Zed Pro for higher limits, a wider range of models, and more.",
723 ))
724 .child(
725 h_flex()
726 .justify_between()
727 .child(CheckboxWithLabel::new(
728 "dont-show-again",
729 Label::new("Don't show again"),
730 if RateLimitNotice::dismissed() {
731 ui::ToggleState::Selected
732 } else {
733 ui::ToggleState::Unselected
734 },
735 |selection, _, cx| {
736 let is_dismissed = match selection {
737 ui::ToggleState::Unselected => false,
738 ui::ToggleState::Indeterminate => return,
739 ui::ToggleState::Selected => true,
740 };
741
742 RateLimitNotice::set_dismissed(is_dismissed, cx);
743 },
744 ))
745 .child(
746 h_flex()
747 .gap_2()
748 .child(
749 Button::new("dismiss", "Dismiss")
750 .style(ButtonStyle::Transparent)
751 .on_click(cx.listener(Self::toggle_rate_limit_notice)),
752 )
753 .child(Button::new("more-info", "More Info").on_click(
754 |_event, window, cx| {
755 window.dispatch_action(
756 Box::new(zed_actions::OpenAccountSettings),
757 cx,
758 )
759 },
760 )),
761 ),
762 ),
763 )
764 }
765
766 fn render_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
767 let font_size = TextSize::Default.rems(cx);
768 let line_height = font_size.to_pixels(window.rem_size()) * 1.3;
769
770 div()
771 .key_context("InlineAssistEditor")
772 .size_full()
773 .p_2()
774 .pl_1()
775 .bg(cx.theme().colors().editor_background)
776 .child({
777 let settings = ThemeSettings::get_global(cx);
778 let text_style = TextStyle {
779 color: cx.theme().colors().editor_foreground,
780 font_family: settings.buffer_font.family.clone(),
781 font_features: settings.buffer_font.features.clone(),
782 font_size: font_size.into(),
783 line_height: line_height.into(),
784 ..Default::default()
785 };
786
787 EditorElement::new(
788 &self.editor,
789 EditorStyle {
790 background: cx.theme().colors().editor_background,
791 local_player: cx.theme().players().local(),
792 text: text_style,
793 ..Default::default()
794 },
795 )
796 })
797 .into_any_element()
798 }
799
800 fn handle_context_strip_event(
801 &mut self,
802 _context_strip: &Entity<ContextStrip>,
803 event: &ContextStripEvent,
804 window: &mut Window,
805 cx: &mut Context<Self>,
806 ) {
807 match event {
808 ContextStripEvent::PickerDismissed
809 | ContextStripEvent::BlurredEmpty
810 | ContextStripEvent::BlurredUp => self.editor.focus_handle(cx).focus(window),
811 ContextStripEvent::BlurredDown => {}
812 }
813 }
814}
815
816pub enum PromptEditorMode {
817 Buffer {
818 id: InlineAssistId,
819 codegen: Entity<BufferCodegen>,
820 editor_margins: Arc<Mutex<EditorMargins>>,
821 },
822 Terminal {
823 id: TerminalInlineAssistId,
824 codegen: Entity<TerminalCodegen>,
825 height_in_lines: u8,
826 },
827}
828
829pub enum PromptEditorEvent {
830 StartRequested,
831 StopRequested,
832 ConfirmRequested { execute: bool },
833 CancelRequested,
834 DismissRequested,
835 Resized { height_in_lines: u8 },
836}
837
838#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
839pub struct InlineAssistId(pub usize);
840
841impl InlineAssistId {
842 pub fn post_inc(&mut self) -> InlineAssistId {
843 let id = *self;
844 self.0 += 1;
845 id
846 }
847}
848
849impl PromptEditor<BufferCodegen> {
850 pub fn new_buffer(
851 id: InlineAssistId,
852 editor_margins: Arc<Mutex<EditorMargins>>,
853 prompt_history: VecDeque<String>,
854 prompt_buffer: Entity<MultiBuffer>,
855 codegen: Entity<BufferCodegen>,
856 fs: Arc<dyn Fs>,
857 context_store: Entity<ContextStore>,
858 workspace: WeakEntity<Workspace>,
859 thread_store: Option<WeakEntity<ThreadStore>>,
860 text_thread_store: Option<WeakEntity<TextThreadStore>>,
861 window: &mut Window,
862 cx: &mut Context<PromptEditor<BufferCodegen>>,
863 ) -> PromptEditor<BufferCodegen> {
864 let codegen_subscription = cx.observe(&codegen, Self::handle_codegen_changed);
865 let codegen_buffer = codegen.read(cx).buffer(cx).read(cx).as_singleton();
866 let mode = PromptEditorMode::Buffer {
867 id,
868 codegen,
869 editor_margins,
870 };
871
872 let prompt_editor = cx.new(|cx| {
873 let mut editor = Editor::new(
874 EditorMode::AutoHeight {
875 min_lines: 1,
876 max_lines: Self::MAX_LINES as usize,
877 },
878 prompt_buffer,
879 None,
880 window,
881 cx,
882 );
883 editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
884 // Since the prompt editors for all inline assistants are linked,
885 // always show the cursor (even when it isn't focused) because
886 // typing in one will make what you typed appear in all of them.
887 editor.set_show_cursor_when_unfocused(true, cx);
888 editor.set_placeholder_text(Self::placeholder_text(&mode, window, cx), cx);
889 editor.register_addon(ContextCreasesAddon::new());
890 editor.set_context_menu_options(ContextMenuOptions {
891 min_entries_visible: 12,
892 max_entries_visible: 12,
893 placement: None,
894 });
895
896 editor
897 });
898
899 let prompt_editor_entity = prompt_editor.downgrade();
900 prompt_editor.update(cx, |editor, _| {
901 editor.set_completion_provider(Some(Rc::new(ContextPickerCompletionProvider::new(
902 workspace.clone(),
903 context_store.downgrade(),
904 thread_store.clone(),
905 text_thread_store.clone(),
906 prompt_editor_entity,
907 codegen_buffer.as_ref().map(Entity::downgrade),
908 ))));
909 });
910
911 let context_picker_menu_handle = PopoverMenuHandle::default();
912 let model_selector_menu_handle = PopoverMenuHandle::default();
913
914 let context_strip = cx.new(|cx| {
915 ContextStrip::new(
916 context_store.clone(),
917 workspace.clone(),
918 thread_store.clone(),
919 text_thread_store.clone(),
920 context_picker_menu_handle.clone(),
921 SuggestContextKind::Thread,
922 ModelUsageContext::InlineAssistant,
923 window,
924 cx,
925 )
926 });
927
928 let context_strip_subscription =
929 cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event);
930
931 let mut this: PromptEditor<BufferCodegen> = PromptEditor {
932 editor: prompt_editor.clone(),
933 context_store,
934 context_strip,
935 context_picker_menu_handle,
936 model_selector: cx.new(|cx| {
937 AgentModelSelector::new(
938 fs,
939 model_selector_menu_handle,
940 prompt_editor.focus_handle(cx),
941 ModelUsageContext::InlineAssistant,
942 window,
943 cx,
944 )
945 }),
946 edited_since_done: false,
947 prompt_history,
948 prompt_history_ix: None,
949 pending_prompt: String::new(),
950 _codegen_subscription: codegen_subscription,
951 editor_subscriptions: Vec::new(),
952 _context_strip_subscription: context_strip_subscription,
953 show_rate_limit_notice: false,
954 mode,
955 _phantom: Default::default(),
956 };
957
958 this.subscribe_to_editor(window, cx);
959 this
960 }
961
962 fn handle_codegen_changed(
963 &mut self,
964 _: Entity<BufferCodegen>,
965 cx: &mut Context<PromptEditor<BufferCodegen>>,
966 ) {
967 match self.codegen_status(cx) {
968 CodegenStatus::Idle => {
969 self.editor
970 .update(cx, |editor, _| editor.set_read_only(false));
971 }
972 CodegenStatus::Pending => {
973 self.editor
974 .update(cx, |editor, _| editor.set_read_only(true));
975 }
976 CodegenStatus::Done => {
977 self.edited_since_done = false;
978 self.editor
979 .update(cx, |editor, _| editor.set_read_only(false));
980 }
981 CodegenStatus::Error(error) => {
982 if cx.has_flag::<ZedProFeatureFlag>()
983 && error.error_code() == proto::ErrorCode::RateLimitExceeded
984 && !RateLimitNotice::dismissed()
985 {
986 self.show_rate_limit_notice = true;
987 cx.notify();
988 }
989
990 self.edited_since_done = false;
991 self.editor
992 .update(cx, |editor, _| editor.set_read_only(false));
993 }
994 }
995 }
996
997 pub fn id(&self) -> InlineAssistId {
998 match &self.mode {
999 PromptEditorMode::Buffer { id, .. } => *id,
1000 PromptEditorMode::Terminal { .. } => unreachable!(),
1001 }
1002 }
1003
1004 pub fn codegen(&self) -> &Entity<BufferCodegen> {
1005 match &self.mode {
1006 PromptEditorMode::Buffer { codegen, .. } => codegen,
1007 PromptEditorMode::Terminal { .. } => unreachable!(),
1008 }
1009 }
1010
1011 pub fn editor_margins(&self) -> &Arc<Mutex<EditorMargins>> {
1012 match &self.mode {
1013 PromptEditorMode::Buffer { editor_margins, .. } => editor_margins,
1014 PromptEditorMode::Terminal { .. } => unreachable!(),
1015 }
1016 }
1017}
1018
1019#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1020pub struct TerminalInlineAssistId(pub usize);
1021
1022impl TerminalInlineAssistId {
1023 pub fn post_inc(&mut self) -> TerminalInlineAssistId {
1024 let id = *self;
1025 self.0 += 1;
1026 id
1027 }
1028}
1029
1030impl PromptEditor<TerminalCodegen> {
1031 pub fn new_terminal(
1032 id: TerminalInlineAssistId,
1033 prompt_history: VecDeque<String>,
1034 prompt_buffer: Entity<MultiBuffer>,
1035 codegen: Entity<TerminalCodegen>,
1036 fs: Arc<dyn Fs>,
1037 context_store: Entity<ContextStore>,
1038 workspace: WeakEntity<Workspace>,
1039 thread_store: Option<WeakEntity<ThreadStore>>,
1040 text_thread_store: Option<WeakEntity<TextThreadStore>>,
1041 window: &mut Window,
1042 cx: &mut Context<Self>,
1043 ) -> Self {
1044 let codegen_subscription = cx.observe(&codegen, Self::handle_codegen_changed);
1045 let mode = PromptEditorMode::Terminal {
1046 id,
1047 codegen,
1048 height_in_lines: 1,
1049 };
1050
1051 let prompt_editor = cx.new(|cx| {
1052 let mut editor = Editor::new(
1053 EditorMode::AutoHeight {
1054 min_lines: 1,
1055 max_lines: Self::MAX_LINES as usize,
1056 },
1057 prompt_buffer,
1058 None,
1059 window,
1060 cx,
1061 );
1062 editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
1063 editor.set_placeholder_text(Self::placeholder_text(&mode, window, cx), cx);
1064 editor.set_context_menu_options(ContextMenuOptions {
1065 min_entries_visible: 12,
1066 max_entries_visible: 12,
1067 placement: None,
1068 });
1069 editor
1070 });
1071
1072 let prompt_editor_entity = prompt_editor.downgrade();
1073 prompt_editor.update(cx, |editor, _| {
1074 editor.set_completion_provider(Some(Rc::new(ContextPickerCompletionProvider::new(
1075 workspace.clone(),
1076 context_store.downgrade(),
1077 thread_store.clone(),
1078 text_thread_store.clone(),
1079 prompt_editor_entity,
1080 None,
1081 ))));
1082 });
1083
1084 let context_picker_menu_handle = PopoverMenuHandle::default();
1085 let model_selector_menu_handle = PopoverMenuHandle::default();
1086
1087 let context_strip = cx.new(|cx| {
1088 ContextStrip::new(
1089 context_store.clone(),
1090 workspace.clone(),
1091 thread_store.clone(),
1092 text_thread_store.clone(),
1093 context_picker_menu_handle.clone(),
1094 SuggestContextKind::Thread,
1095 ModelUsageContext::InlineAssistant,
1096 window,
1097 cx,
1098 )
1099 });
1100
1101 let context_strip_subscription =
1102 cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event);
1103
1104 let mut this = Self {
1105 editor: prompt_editor.clone(),
1106 context_store,
1107 context_strip,
1108 context_picker_menu_handle,
1109 model_selector: cx.new(|cx| {
1110 AgentModelSelector::new(
1111 fs,
1112 model_selector_menu_handle.clone(),
1113 prompt_editor.focus_handle(cx),
1114 ModelUsageContext::InlineAssistant,
1115 window,
1116 cx,
1117 )
1118 }),
1119 edited_since_done: false,
1120 prompt_history,
1121 prompt_history_ix: None,
1122 pending_prompt: String::new(),
1123 _codegen_subscription: codegen_subscription,
1124 editor_subscriptions: Vec::new(),
1125 _context_strip_subscription: context_strip_subscription,
1126 mode,
1127 show_rate_limit_notice: false,
1128 _phantom: Default::default(),
1129 };
1130 this.count_lines(cx);
1131 this.subscribe_to_editor(window, cx);
1132 this
1133 }
1134
1135 fn count_lines(&mut self, cx: &mut Context<Self>) {
1136 let height_in_lines = cmp::max(
1137 2, // Make the editor at least two lines tall, to account for padding and buttons.
1138 cmp::min(
1139 self.editor
1140 .update(cx, |editor, cx| editor.max_point(cx).row().0 + 1),
1141 Self::MAX_LINES as u32,
1142 ),
1143 ) as u8;
1144
1145 match &mut self.mode {
1146 PromptEditorMode::Terminal {
1147 height_in_lines: current_height,
1148 ..
1149 } => {
1150 if height_in_lines != *current_height {
1151 *current_height = height_in_lines;
1152 cx.emit(PromptEditorEvent::Resized { height_in_lines });
1153 }
1154 }
1155 PromptEditorMode::Buffer { .. } => unreachable!(),
1156 }
1157 }
1158
1159 fn handle_codegen_changed(&mut self, _: Entity<TerminalCodegen>, cx: &mut Context<Self>) {
1160 match &self.codegen().read(cx).status {
1161 CodegenStatus::Idle => {
1162 self.editor
1163 .update(cx, |editor, _| editor.set_read_only(false));
1164 }
1165 CodegenStatus::Pending => {
1166 self.editor
1167 .update(cx, |editor, _| editor.set_read_only(true));
1168 }
1169 CodegenStatus::Done | CodegenStatus::Error(_) => {
1170 self.edited_since_done = false;
1171 self.editor
1172 .update(cx, |editor, _| editor.set_read_only(false));
1173 }
1174 }
1175 }
1176
1177 pub fn codegen(&self) -> &Entity<TerminalCodegen> {
1178 match &self.mode {
1179 PromptEditorMode::Buffer { .. } => unreachable!(),
1180 PromptEditorMode::Terminal { codegen, .. } => codegen,
1181 }
1182 }
1183
1184 pub fn id(&self) -> TerminalInlineAssistId {
1185 match &self.mode {
1186 PromptEditorMode::Buffer { .. } => unreachable!(),
1187 PromptEditorMode::Terminal { id, .. } => *id,
1188 }
1189 }
1190}
1191
1192struct RateLimitNotice;
1193
1194impl Dismissable for RateLimitNotice {
1195 const KEY: &'static str = "dismissed-rate-limit-notice";
1196}
1197
1198pub enum CodegenStatus {
1199 Idle,
1200 Pending,
1201 Done,
1202 Error(anyhow::Error),
1203}
1204
1205/// This is just CodegenStatus without the anyhow::Error, which causes a lifetime issue for rendering the Cancel button.
1206#[derive(Copy, Clone)]
1207pub enum CancelButtonState {
1208 Idle,
1209 Pending,
1210 Done,
1211 Error,
1212}
1213
1214impl Into<CancelButtonState> for &CodegenStatus {
1215 fn into(self) -> CancelButtonState {
1216 match self {
1217 CodegenStatus::Idle => CancelButtonState::Idle,
1218 CodegenStatus::Pending => CancelButtonState::Pending,
1219 CodegenStatus::Done => CancelButtonState::Done,
1220 CodegenStatus::Error(_) => CancelButtonState::Error,
1221 }
1222 }
1223}
1224
1225#[derive(Copy, Clone)]
1226pub enum GenerationMode {
1227 Generate,
1228 Transform,
1229}
1230
1231impl GenerationMode {
1232 fn start_label(self) -> &'static str {
1233 match self {
1234 GenerationMode::Generate { .. } => "Generate",
1235 GenerationMode::Transform => "Transform",
1236 }
1237 }
1238 fn tooltip_interrupt(self) -> &'static str {
1239 match self {
1240 GenerationMode::Generate { .. } => "Interrupt Generation",
1241 GenerationMode::Transform => "Interrupt Transform",
1242 }
1243 }
1244
1245 fn tooltip_restart(self) -> &'static str {
1246 match self {
1247 GenerationMode::Generate { .. } => "Restart Generation",
1248 GenerationMode::Transform => "Restart Transform",
1249 }
1250 }
1251
1252 fn tooltip_accept(self) -> &'static str {
1253 match self {
1254 GenerationMode::Generate { .. } => "Accept Generation",
1255 GenerationMode::Transform => "Accept Transform",
1256 }
1257 }
1258}