1use anyhow::Result;
2use assistant_settings::AssistantSettings;
3use assistant_slash_command::{SlashCommand, SlashCommandOutputSection, SlashCommandWorkingSet};
4use assistant_slash_commands::{
5 selections_creases, DefaultSlashCommand, DocsSlashCommand, DocsSlashCommandArgs,
6 FileSlashCommand,
7};
8use client::{proto, zed_urls};
9use collections::{hash_map, BTreeSet, HashMap, HashSet};
10use editor::{
11 actions::{FoldAt, MoveToEndOfLine, Newline, ShowCompletions, UnfoldAt},
12 display_map::{
13 BlockContext, BlockId, BlockPlacement, BlockProperties, BlockStyle, Crease, CreaseMetadata,
14 CustomBlockId, FoldId, RenderBlock, ToDisplayPoint,
15 },
16 scroll::{Autoscroll, AutoscrollStrategy},
17 Anchor, Editor, EditorEvent, MenuInlineCompletionsPolicy, ProposedChangeLocation,
18 ProposedChangesEditor, RowExt, ToOffset as _, ToPoint,
19};
20use editor::{display_map::CreaseId, FoldPlaceholder};
21use fs::Fs;
22use futures::FutureExt;
23use gpui::{
24 actions, div, img, impl_internal_actions, percentage, point, prelude::*, pulsating_between,
25 size, Animation, AnimationExt, AnyElement, AnyView, App, AsyncWindowContext, ClipboardEntry,
26 ClipboardItem, CursorStyle, Empty, Entity, EventEmitter, FocusHandle, Focusable, FontWeight,
27 Global, InteractiveElement, IntoElement, ParentElement, Pixels, Render, RenderImage,
28 SharedString, Size, StatefulInteractiveElement, Styled, Subscription, Task, Transformation,
29 WeakEntity,
30};
31use indexed_docs::IndexedDocsStore;
32use language::{language_settings::SoftWrap, BufferSnapshot, LspAdapterDelegate, ToOffset};
33use language_model::{
34 LanguageModelImage, LanguageModelProvider, LanguageModelProviderTosView, LanguageModelRegistry,
35 Role,
36};
37use language_model_selector::{LanguageModelSelector, LanguageModelSelectorPopoverMenu};
38use multi_buffer::MultiBufferRow;
39use picker::Picker;
40use project::lsp_store::LocalLspAdapterDelegate;
41use project::{Project, Worktree};
42use rope::Point;
43use serde::{Deserialize, Serialize};
44use settings::{update_settings_file, Settings};
45use std::{any::TypeId, borrow::Cow, cmp, ops::Range, path::PathBuf, sync::Arc, time::Duration};
46use text::SelectionGoal;
47use ui::{
48 prelude::*, ButtonLike, Disclosure, ElevationIndex, KeyBinding, PopoverMenuHandle, TintColor,
49 Tooltip,
50};
51use util::{maybe, ResultExt};
52use workspace::searchable::SearchableItemHandle;
53use workspace::{
54 item::{self, FollowableItem, Item, ItemHandle},
55 notifications::NotificationId,
56 pane::{self, SaveIntent},
57 searchable::{SearchEvent, SearchableItem},
58 Save, ShowConfiguration, Toast, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView,
59 Workspace,
60};
61
62use crate::{slash_command::SlashCommandCompletionProvider, slash_command_picker};
63use crate::{
64 AssistantContext, AssistantPatch, AssistantPatchStatus, CacheStatus, Content, ContextEvent,
65 ContextId, InvokedSlashCommandId, InvokedSlashCommandStatus, Message, MessageId,
66 MessageMetadata, MessageStatus, ParsedSlashCommand, PendingSlashCommandStatus, RequestType,
67};
68
69actions!(
70 assistant,
71 [
72 Assist,
73 ConfirmCommand,
74 CopyCode,
75 CycleMessageRole,
76 Edit,
77 InsertIntoEditor,
78 QuoteSelection,
79 Split,
80 ToggleModelSelector,
81 ]
82);
83
84#[derive(PartialEq, Clone)]
85pub enum InsertDraggedFiles {
86 ProjectPaths(Vec<PathBuf>),
87 ExternalFiles(Vec<PathBuf>),
88}
89
90impl_internal_actions!(assistant, [InsertDraggedFiles]);
91
92#[derive(Copy, Clone, Debug, PartialEq)]
93struct ScrollPosition {
94 offset_before_cursor: gpui::Point<f32>,
95 cursor: Anchor,
96}
97
98struct PatchViewState {
99 crease_id: CreaseId,
100 editor: Option<PatchEditorState>,
101 update_task: Option<Task<()>>,
102}
103
104struct PatchEditorState {
105 editor: WeakEntity<ProposedChangesEditor>,
106 opened_patch: AssistantPatch,
107}
108
109type MessageHeader = MessageMetadata;
110
111#[derive(Clone)]
112enum AssistError {
113 FileRequired,
114 PaymentRequired,
115 MaxMonthlySpendReached,
116 Message(SharedString),
117}
118
119pub trait AssistantPanelDelegate {
120 fn active_context_editor(
121 &self,
122 workspace: &mut Workspace,
123 window: &mut Window,
124 cx: &mut Context<Workspace>,
125 ) -> Option<Entity<ContextEditor>>;
126
127 fn open_saved_context(
128 &self,
129 workspace: &mut Workspace,
130 path: PathBuf,
131 window: &mut Window,
132 cx: &mut Context<Workspace>,
133 ) -> Task<Result<()>>;
134
135 fn open_remote_context(
136 &self,
137 workspace: &mut Workspace,
138 context_id: ContextId,
139 window: &mut Window,
140 cx: &mut Context<Workspace>,
141 ) -> Task<Result<Entity<ContextEditor>>>;
142
143 fn quote_selection(
144 &self,
145 workspace: &mut Workspace,
146 creases: Vec<(String, String)>,
147 window: &mut Window,
148 cx: &mut Context<Workspace>,
149 );
150}
151
152impl dyn AssistantPanelDelegate {
153 /// Returns the global [`AssistantPanelDelegate`], if it exists.
154 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
155 cx.try_global::<GlobalAssistantPanelDelegate>()
156 .map(|global| global.0.clone())
157 }
158
159 /// Sets the global [`AssistantPanelDelegate`].
160 pub fn set_global(delegate: Arc<Self>, cx: &mut App) {
161 cx.set_global(GlobalAssistantPanelDelegate(delegate));
162 }
163}
164
165struct GlobalAssistantPanelDelegate(Arc<dyn AssistantPanelDelegate>);
166
167impl Global for GlobalAssistantPanelDelegate {}
168
169pub struct ContextEditor {
170 context: Entity<AssistantContext>,
171 fs: Arc<dyn Fs>,
172 slash_commands: Arc<SlashCommandWorkingSet>,
173 workspace: WeakEntity<Workspace>,
174 project: Entity<Project>,
175 lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
176 editor: Entity<Editor>,
177 blocks: HashMap<MessageId, (MessageHeader, CustomBlockId)>,
178 image_blocks: HashSet<CustomBlockId>,
179 scroll_position: Option<ScrollPosition>,
180 remote_id: Option<workspace::ViewId>,
181 pending_slash_command_creases: HashMap<Range<language::Anchor>, CreaseId>,
182 invoked_slash_command_creases: HashMap<InvokedSlashCommandId, CreaseId>,
183 _subscriptions: Vec<Subscription>,
184 patches: HashMap<Range<language::Anchor>, PatchViewState>,
185 active_patch: Option<Range<language::Anchor>>,
186 last_error: Option<AssistError>,
187 show_accept_terms: bool,
188 pub(crate) slash_menu_handle:
189 PopoverMenuHandle<Picker<slash_command_picker::SlashCommandDelegate>>,
190 // dragged_file_worktrees is used to keep references to worktrees that were added
191 // when the user drag/dropped an external file onto the context editor. Since
192 // the worktree is not part of the project panel, it would be dropped as soon as
193 // the file is opened. In order to keep the worktree alive for the duration of the
194 // context editor, we keep a reference here.
195 dragged_file_worktrees: Vec<Entity<Worktree>>,
196 language_model_selector: Entity<LanguageModelSelector>,
197 language_model_selector_menu_handle: PopoverMenuHandle<LanguageModelSelector>,
198}
199
200pub const DEFAULT_TAB_TITLE: &str = "New Chat";
201const MAX_TAB_TITLE_LEN: usize = 16;
202
203impl ContextEditor {
204 pub fn for_context(
205 context: Entity<AssistantContext>,
206 fs: Arc<dyn Fs>,
207 workspace: WeakEntity<Workspace>,
208 project: Entity<Project>,
209 lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
210 window: &mut Window,
211 cx: &mut Context<Self>,
212 ) -> Self {
213 let completion_provider = SlashCommandCompletionProvider::new(
214 context.read(cx).slash_commands().clone(),
215 Some(cx.entity().downgrade()),
216 Some(workspace.clone()),
217 );
218
219 let editor = cx.new(|cx| {
220 let mut editor =
221 Editor::for_buffer(context.read(cx).buffer().clone(), None, window, cx);
222 editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
223 editor.set_show_line_numbers(false, cx);
224 editor.set_show_scrollbars(false, cx);
225 editor.set_show_git_diff_gutter(false, cx);
226 editor.set_show_code_actions(false, cx);
227 editor.set_show_runnables(false, cx);
228 editor.set_show_wrap_guides(false, cx);
229 editor.set_show_indent_guides(false, cx);
230 editor.set_completion_provider(Some(Box::new(completion_provider)));
231 editor.set_menu_inline_completions_policy(MenuInlineCompletionsPolicy::Never);
232 editor.set_collaboration_hub(Box::new(project.clone()));
233 editor
234 });
235
236 let _subscriptions = vec![
237 cx.observe(&context, |_, _, cx| cx.notify()),
238 cx.subscribe_in(&context, window, Self::handle_context_event),
239 cx.subscribe_in(&editor, window, Self::handle_editor_event),
240 cx.subscribe_in(&editor, window, Self::handle_editor_search_event),
241 ];
242
243 let fs_clone = fs.clone();
244 let language_model_selector = cx.new(|cx| {
245 LanguageModelSelector::new(
246 move |model, cx| {
247 update_settings_file::<AssistantSettings>(
248 fs_clone.clone(),
249 cx,
250 move |settings, _| settings.set_model(model.clone()),
251 );
252 },
253 window,
254 cx,
255 )
256 });
257
258 let language_model_selector_menu_handle = PopoverMenuHandle::default();
259 let sections = context.read(cx).slash_command_output_sections().to_vec();
260 let patch_ranges = context.read(cx).patch_ranges().collect::<Vec<_>>();
261 let slash_commands = context.read(cx).slash_commands().clone();
262 let mut this = Self {
263 context,
264 slash_commands,
265 editor,
266 lsp_adapter_delegate,
267 blocks: Default::default(),
268 image_blocks: Default::default(),
269 scroll_position: None,
270 remote_id: None,
271 fs,
272 workspace,
273 project,
274 pending_slash_command_creases: HashMap::default(),
275 invoked_slash_command_creases: HashMap::default(),
276 _subscriptions,
277 patches: HashMap::default(),
278 active_patch: None,
279 last_error: None,
280 show_accept_terms: false,
281 slash_menu_handle: Default::default(),
282 dragged_file_worktrees: Vec::new(),
283 language_model_selector,
284 language_model_selector_menu_handle,
285 };
286 this.update_message_headers(cx);
287 this.update_image_blocks(cx);
288 this.insert_slash_command_output_sections(sections, false, window, cx);
289 this.patches_updated(&Vec::new(), &patch_ranges, window, cx);
290 this
291 }
292
293 pub fn context(&self) -> &Entity<AssistantContext> {
294 &self.context
295 }
296
297 pub fn editor(&self) -> &Entity<Editor> {
298 &self.editor
299 }
300
301 pub fn insert_default_prompt(&mut self, window: &mut Window, cx: &mut Context<Self>) {
302 let command_name = DefaultSlashCommand.name();
303 self.editor.update(cx, |editor, cx| {
304 editor.insert(&format!("/{command_name}\n\n"), window, cx)
305 });
306 let command = self.context.update(cx, |context, cx| {
307 context.reparse(cx);
308 context.parsed_slash_commands()[0].clone()
309 });
310 self.run_command(
311 command.source_range,
312 &command.name,
313 &command.arguments,
314 false,
315 self.workspace.clone(),
316 window,
317 cx,
318 );
319 }
320
321 fn assist(&mut self, _: &Assist, window: &mut Window, cx: &mut Context<Self>) {
322 self.send_to_model(RequestType::Chat, window, cx);
323 }
324
325 fn edit(&mut self, _: &Edit, window: &mut Window, cx: &mut Context<Self>) {
326 self.send_to_model(RequestType::SuggestEdits, window, cx);
327 }
328
329 fn focus_active_patch(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
330 if let Some((_range, patch)) = self.active_patch() {
331 if let Some(editor) = patch
332 .editor
333 .as_ref()
334 .and_then(|state| state.editor.upgrade())
335 {
336 editor.focus_handle(cx).focus(window);
337 return true;
338 }
339 }
340
341 false
342 }
343
344 fn send_to_model(
345 &mut self,
346 request_type: RequestType,
347 window: &mut Window,
348 cx: &mut Context<Self>,
349 ) {
350 let provider = LanguageModelRegistry::read_global(cx).active_provider();
351 if provider
352 .as_ref()
353 .map_or(false, |provider| provider.must_accept_terms(cx))
354 {
355 self.show_accept_terms = true;
356 cx.notify();
357 return;
358 }
359
360 if self.focus_active_patch(window, cx) {
361 return;
362 }
363
364 self.last_error = None;
365
366 if request_type == RequestType::SuggestEdits && !self.context.read(cx).contains_files(cx) {
367 self.last_error = Some(AssistError::FileRequired);
368 cx.notify();
369 } else if let Some(user_message) = self
370 .context
371 .update(cx, |context, cx| context.assist(request_type, cx))
372 {
373 let new_selection = {
374 let cursor = user_message
375 .start
376 .to_offset(self.context.read(cx).buffer().read(cx));
377 cursor..cursor
378 };
379 self.editor.update(cx, |editor, cx| {
380 editor.change_selections(
381 Some(Autoscroll::Strategy(AutoscrollStrategy::Fit)),
382 window,
383 cx,
384 |selections| selections.select_ranges([new_selection]),
385 );
386 });
387 // Avoid scrolling to the new cursor position so the assistant's output is stable.
388 cx.defer_in(window, |this, _, _| this.scroll_position = None);
389 }
390
391 cx.notify();
392 }
393
394 fn cancel(
395 &mut self,
396 _: &editor::actions::Cancel,
397 _window: &mut Window,
398 cx: &mut Context<Self>,
399 ) {
400 self.last_error = None;
401
402 if self
403 .context
404 .update(cx, |context, cx| context.cancel_last_assist(cx))
405 {
406 return;
407 }
408
409 cx.propagate();
410 }
411
412 fn cycle_message_role(
413 &mut self,
414 _: &CycleMessageRole,
415 _window: &mut Window,
416 cx: &mut Context<Self>,
417 ) {
418 let cursors = self.cursors(cx);
419 self.context.update(cx, |context, cx| {
420 let messages = context
421 .messages_for_offsets(cursors, cx)
422 .into_iter()
423 .map(|message| message.id)
424 .collect();
425 context.cycle_message_roles(messages, cx)
426 });
427 }
428
429 fn cursors(&self, cx: &mut App) -> Vec<usize> {
430 let selections = self
431 .editor
432 .update(cx, |editor, cx| editor.selections.all::<usize>(cx));
433 selections
434 .into_iter()
435 .map(|selection| selection.head())
436 .collect()
437 }
438
439 pub fn insert_command(&mut self, name: &str, window: &mut Window, cx: &mut Context<Self>) {
440 if let Some(command) = self.slash_commands.command(name, cx) {
441 self.editor.update(cx, |editor, cx| {
442 editor.transact(window, cx, |editor, window, cx| {
443 editor
444 .change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel());
445 let snapshot = editor.buffer().read(cx).snapshot(cx);
446 let newest_cursor = editor.selections.newest::<Point>(cx).head();
447 if newest_cursor.column > 0
448 || snapshot
449 .chars_at(newest_cursor)
450 .next()
451 .map_or(false, |ch| ch != '\n')
452 {
453 editor.move_to_end_of_line(
454 &MoveToEndOfLine {
455 stop_at_soft_wraps: false,
456 },
457 window,
458 cx,
459 );
460 editor.newline(&Newline, window, cx);
461 }
462
463 editor.insert(&format!("/{name}"), window, cx);
464 if command.accepts_arguments() {
465 editor.insert(" ", window, cx);
466 editor.show_completions(&ShowCompletions::default(), window, cx);
467 }
468 });
469 });
470 if !command.requires_argument() {
471 self.confirm_command(&ConfirmCommand, window, cx);
472 }
473 }
474 }
475
476 pub fn confirm_command(
477 &mut self,
478 _: &ConfirmCommand,
479 window: &mut Window,
480 cx: &mut Context<Self>,
481 ) {
482 if self.editor.read(cx).has_visible_completions_menu() {
483 return;
484 }
485
486 let selections = self.editor.read(cx).selections.disjoint_anchors();
487 let mut commands_by_range = HashMap::default();
488 let workspace = self.workspace.clone();
489 self.context.update(cx, |context, cx| {
490 context.reparse(cx);
491 for selection in selections.iter() {
492 if let Some(command) =
493 context.pending_command_for_position(selection.head().text_anchor, cx)
494 {
495 commands_by_range
496 .entry(command.source_range.clone())
497 .or_insert_with(|| command.clone());
498 }
499 }
500 });
501
502 if commands_by_range.is_empty() {
503 cx.propagate();
504 } else {
505 for command in commands_by_range.into_values() {
506 self.run_command(
507 command.source_range,
508 &command.name,
509 &command.arguments,
510 true,
511 workspace.clone(),
512 window,
513 cx,
514 );
515 }
516 cx.stop_propagation();
517 }
518 }
519
520 #[allow(clippy::too_many_arguments)]
521 pub fn run_command(
522 &mut self,
523 command_range: Range<language::Anchor>,
524 name: &str,
525 arguments: &[String],
526 ensure_trailing_newline: bool,
527 workspace: WeakEntity<Workspace>,
528 window: &mut Window,
529 cx: &mut Context<Self>,
530 ) {
531 if let Some(command) = self.slash_commands.command(name, cx) {
532 let context = self.context.read(cx);
533 let sections = context
534 .slash_command_output_sections()
535 .into_iter()
536 .filter(|section| section.is_valid(context.buffer().read(cx)))
537 .cloned()
538 .collect::<Vec<_>>();
539 let snapshot = context.buffer().read(cx).snapshot();
540 let output = command.run(
541 arguments,
542 §ions,
543 snapshot,
544 workspace,
545 self.lsp_adapter_delegate.clone(),
546 window,
547 cx,
548 );
549 self.context.update(cx, |context, cx| {
550 context.insert_command_output(
551 command_range,
552 name,
553 output,
554 ensure_trailing_newline,
555 cx,
556 )
557 });
558 }
559 }
560
561 fn handle_context_event(
562 &mut self,
563 _: &Entity<AssistantContext>,
564 event: &ContextEvent,
565 window: &mut Window,
566 cx: &mut Context<Self>,
567 ) {
568 let context_editor = cx.entity().downgrade();
569
570 match event {
571 ContextEvent::MessagesEdited => {
572 self.update_message_headers(cx);
573 self.update_image_blocks(cx);
574 self.context.update(cx, |context, cx| {
575 context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
576 });
577 }
578 ContextEvent::SummaryChanged => {
579 cx.emit(EditorEvent::TitleChanged);
580 self.context.update(cx, |context, cx| {
581 context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
582 });
583 }
584 ContextEvent::StreamedCompletion => {
585 self.editor.update(cx, |editor, cx| {
586 if let Some(scroll_position) = self.scroll_position {
587 let snapshot = editor.snapshot(window, cx);
588 let cursor_point = scroll_position.cursor.to_display_point(&snapshot);
589 let scroll_top =
590 cursor_point.row().as_f32() - scroll_position.offset_before_cursor.y;
591 editor.set_scroll_position(
592 point(scroll_position.offset_before_cursor.x, scroll_top),
593 window,
594 cx,
595 );
596 }
597 });
598 }
599 ContextEvent::PatchesUpdated { removed, updated } => {
600 self.patches_updated(removed, updated, window, cx);
601 }
602 ContextEvent::ParsedSlashCommandsUpdated { removed, updated } => {
603 self.editor.update(cx, |editor, cx| {
604 let buffer = editor.buffer().read(cx).snapshot(cx);
605 let (&excerpt_id, _, _) = buffer.as_singleton().unwrap();
606
607 editor.remove_creases(
608 removed
609 .iter()
610 .filter_map(|range| self.pending_slash_command_creases.remove(range)),
611 cx,
612 );
613
614 let crease_ids = editor.insert_creases(
615 updated.iter().map(|command| {
616 let workspace = self.workspace.clone();
617 let confirm_command = Arc::new({
618 let context_editor = context_editor.clone();
619 let command = command.clone();
620 move |window: &mut Window, cx: &mut App| {
621 context_editor
622 .update(cx, |context_editor, cx| {
623 context_editor.run_command(
624 command.source_range.clone(),
625 &command.name,
626 &command.arguments,
627 false,
628 workspace.clone(),
629 window,
630 cx,
631 );
632 })
633 .ok();
634 }
635 });
636 let placeholder = FoldPlaceholder {
637 render: Arc::new(move |_, _, _| Empty.into_any()),
638 ..Default::default()
639 };
640 let render_toggle = {
641 let confirm_command = confirm_command.clone();
642 let command = command.clone();
643 move |row, _, _, _window: &mut Window, _cx: &mut App| {
644 render_pending_slash_command_gutter_decoration(
645 row,
646 &command.status,
647 confirm_command.clone(),
648 )
649 }
650 };
651 let render_trailer = {
652 let command = command.clone();
653 move |row, _unfold, _window: &mut Window, cx: &mut App| {
654 // TODO: In the future we should investigate how we can expose
655 // this as a hook on the `SlashCommand` trait so that we don't
656 // need to special-case it here.
657 if command.name == DocsSlashCommand::NAME {
658 return render_docs_slash_command_trailer(
659 row,
660 command.clone(),
661 cx,
662 );
663 }
664
665 Empty.into_any()
666 }
667 };
668
669 let start = buffer
670 .anchor_in_excerpt(excerpt_id, command.source_range.start)
671 .unwrap();
672 let end = buffer
673 .anchor_in_excerpt(excerpt_id, command.source_range.end)
674 .unwrap();
675 Crease::inline(start..end, placeholder, render_toggle, render_trailer)
676 }),
677 cx,
678 );
679
680 self.pending_slash_command_creases.extend(
681 updated
682 .iter()
683 .map(|command| command.source_range.clone())
684 .zip(crease_ids),
685 );
686 })
687 }
688 ContextEvent::InvokedSlashCommandChanged { command_id } => {
689 self.update_invoked_slash_command(*command_id, window, cx);
690 }
691 ContextEvent::SlashCommandOutputSectionAdded { section } => {
692 self.insert_slash_command_output_sections([section.clone()], false, window, cx);
693 }
694 ContextEvent::Operation(_) => {}
695 ContextEvent::ShowAssistError(error_message) => {
696 self.last_error = Some(AssistError::Message(error_message.clone()));
697 }
698 ContextEvent::ShowPaymentRequiredError => {
699 self.last_error = Some(AssistError::PaymentRequired);
700 }
701 ContextEvent::ShowMaxMonthlySpendReachedError => {
702 self.last_error = Some(AssistError::MaxMonthlySpendReached);
703 }
704 }
705 }
706
707 fn update_invoked_slash_command(
708 &mut self,
709 command_id: InvokedSlashCommandId,
710 window: &mut Window,
711 cx: &mut Context<Self>,
712 ) {
713 if let Some(invoked_slash_command) =
714 self.context.read(cx).invoked_slash_command(&command_id)
715 {
716 if let InvokedSlashCommandStatus::Finished = invoked_slash_command.status {
717 let run_commands_in_ranges = invoked_slash_command
718 .run_commands_in_ranges
719 .iter()
720 .cloned()
721 .collect::<Vec<_>>();
722 for range in run_commands_in_ranges {
723 let commands = self.context.update(cx, |context, cx| {
724 context.reparse(cx);
725 context
726 .pending_commands_for_range(range.clone(), cx)
727 .to_vec()
728 });
729
730 for command in commands {
731 self.run_command(
732 command.source_range,
733 &command.name,
734 &command.arguments,
735 false,
736 self.workspace.clone(),
737 window,
738 cx,
739 );
740 }
741 }
742 }
743 }
744
745 self.editor.update(cx, |editor, cx| {
746 if let Some(invoked_slash_command) =
747 self.context.read(cx).invoked_slash_command(&command_id)
748 {
749 if let InvokedSlashCommandStatus::Finished = invoked_slash_command.status {
750 let buffer = editor.buffer().read(cx).snapshot(cx);
751 let (&excerpt_id, _buffer_id, _buffer_snapshot) =
752 buffer.as_singleton().unwrap();
753
754 let start = buffer
755 .anchor_in_excerpt(excerpt_id, invoked_slash_command.range.start)
756 .unwrap();
757 let end = buffer
758 .anchor_in_excerpt(excerpt_id, invoked_slash_command.range.end)
759 .unwrap();
760 editor.remove_folds_with_type(
761 &[start..end],
762 TypeId::of::<PendingSlashCommand>(),
763 false,
764 cx,
765 );
766
767 editor.remove_creases(
768 HashSet::from_iter(self.invoked_slash_command_creases.remove(&command_id)),
769 cx,
770 );
771 } else if let hash_map::Entry::Vacant(entry) =
772 self.invoked_slash_command_creases.entry(command_id)
773 {
774 let buffer = editor.buffer().read(cx).snapshot(cx);
775 let (&excerpt_id, _buffer_id, _buffer_snapshot) =
776 buffer.as_singleton().unwrap();
777 let context = self.context.downgrade();
778 let crease_start = buffer
779 .anchor_in_excerpt(excerpt_id, invoked_slash_command.range.start)
780 .unwrap();
781 let crease_end = buffer
782 .anchor_in_excerpt(excerpt_id, invoked_slash_command.range.end)
783 .unwrap();
784 let crease = Crease::inline(
785 crease_start..crease_end,
786 invoked_slash_command_fold_placeholder(command_id, context),
787 fold_toggle("invoked-slash-command"),
788 |_row, _folded, _window, _cx| Empty.into_any(),
789 );
790 let crease_ids = editor.insert_creases([crease.clone()], cx);
791 editor.fold_creases(vec![crease], false, window, cx);
792 entry.insert(crease_ids[0]);
793 } else {
794 cx.notify()
795 }
796 } else {
797 editor.remove_creases(
798 HashSet::from_iter(self.invoked_slash_command_creases.remove(&command_id)),
799 cx,
800 );
801 cx.notify();
802 };
803 });
804 }
805
806 fn patches_updated(
807 &mut self,
808 removed: &Vec<Range<text::Anchor>>,
809 updated: &Vec<Range<text::Anchor>>,
810 window: &mut Window,
811 cx: &mut Context<ContextEditor>,
812 ) {
813 let this = cx.entity().downgrade();
814 let mut editors_to_close = Vec::new();
815
816 self.editor.update(cx, |editor, cx| {
817 let snapshot = editor.snapshot(window, cx);
818 let multibuffer = &snapshot.buffer_snapshot;
819 let (&excerpt_id, _, _) = multibuffer.as_singleton().unwrap();
820
821 let mut removed_crease_ids = Vec::new();
822 let mut ranges_to_unfold: Vec<Range<Anchor>> = Vec::new();
823 for range in removed {
824 if let Some(state) = self.patches.remove(range) {
825 let patch_start = multibuffer
826 .anchor_in_excerpt(excerpt_id, range.start)
827 .unwrap();
828 let patch_end = multibuffer
829 .anchor_in_excerpt(excerpt_id, range.end)
830 .unwrap();
831
832 editors_to_close.extend(state.editor.and_then(|state| state.editor.upgrade()));
833 ranges_to_unfold.push(patch_start..patch_end);
834 removed_crease_ids.push(state.crease_id);
835 }
836 }
837 editor.unfold_ranges(&ranges_to_unfold, true, false, cx);
838 editor.remove_creases(removed_crease_ids, cx);
839
840 for range in updated {
841 let Some(patch) = self.context.read(cx).patch_for_range(&range, cx).cloned() else {
842 continue;
843 };
844
845 let path_count = patch.path_count();
846 let patch_start = multibuffer
847 .anchor_in_excerpt(excerpt_id, patch.range.start)
848 .unwrap();
849 let patch_end = multibuffer
850 .anchor_in_excerpt(excerpt_id, patch.range.end)
851 .unwrap();
852 let render_block: RenderBlock = Arc::new({
853 let this = this.clone();
854 let patch_range = range.clone();
855 move |cx: &mut BlockContext| {
856 let max_width = cx.max_width;
857 let gutter_width = cx.gutter_dimensions.full_width();
858 let block_id = cx.block_id;
859 let selected = cx.selected;
860 let window = &mut cx.window;
861 this.update(cx.app, |this, cx| {
862 this.render_patch_block(
863 patch_range.clone(),
864 max_width,
865 gutter_width,
866 block_id,
867 selected,
868 window,
869 cx,
870 )
871 })
872 .ok()
873 .flatten()
874 .unwrap_or_else(|| Empty.into_any())
875 }
876 });
877
878 let height = path_count as u32 + 1;
879 let crease = Crease::block(
880 patch_start..patch_end,
881 height,
882 BlockStyle::Flex,
883 render_block.clone(),
884 );
885
886 let should_refold;
887 if let Some(state) = self.patches.get_mut(&range) {
888 if let Some(editor_state) = &state.editor {
889 if editor_state.opened_patch != patch {
890 state.update_task = Some({
891 let this = this.clone();
892 cx.spawn_in(window, |_, cx| async move {
893 Self::update_patch_editor(this.clone(), patch, cx)
894 .await
895 .log_err();
896 })
897 });
898 }
899 }
900
901 should_refold =
902 snapshot.intersects_fold(patch_start.to_offset(&snapshot.buffer_snapshot));
903 } else {
904 let crease_id = editor.insert_creases([crease.clone()], cx)[0];
905 self.patches.insert(
906 range.clone(),
907 PatchViewState {
908 crease_id,
909 editor: None,
910 update_task: None,
911 },
912 );
913
914 should_refold = true;
915 }
916
917 if should_refold {
918 editor.unfold_ranges(&[patch_start..patch_end], true, false, cx);
919 editor.fold_creases(vec![crease], false, window, cx);
920 }
921 }
922 });
923
924 for editor in editors_to_close {
925 self.close_patch_editor(editor, window, cx);
926 }
927
928 self.update_active_patch(window, cx);
929 }
930
931 fn insert_slash_command_output_sections(
932 &mut self,
933 sections: impl IntoIterator<Item = SlashCommandOutputSection<language::Anchor>>,
934 expand_result: bool,
935 window: &mut Window,
936 cx: &mut Context<Self>,
937 ) {
938 self.editor.update(cx, |editor, cx| {
939 let buffer = editor.buffer().read(cx).snapshot(cx);
940 let excerpt_id = *buffer.as_singleton().unwrap().0;
941 let mut buffer_rows_to_fold = BTreeSet::new();
942 let mut creases = Vec::new();
943 for section in sections {
944 let start = buffer
945 .anchor_in_excerpt(excerpt_id, section.range.start)
946 .unwrap();
947 let end = buffer
948 .anchor_in_excerpt(excerpt_id, section.range.end)
949 .unwrap();
950 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
951 buffer_rows_to_fold.insert(buffer_row);
952 creases.push(
953 Crease::inline(
954 start..end,
955 FoldPlaceholder {
956 render: render_fold_icon_button(
957 cx.entity().downgrade(),
958 section.icon,
959 section.label.clone(),
960 ),
961 merge_adjacent: false,
962 ..Default::default()
963 },
964 render_slash_command_output_toggle,
965 |_, _, _, _| Empty.into_any_element(),
966 )
967 .with_metadata(CreaseMetadata {
968 icon: section.icon,
969 label: section.label,
970 }),
971 );
972 }
973
974 editor.insert_creases(creases, cx);
975
976 if expand_result {
977 buffer_rows_to_fold.clear();
978 }
979 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
980 editor.fold_at(&FoldAt { buffer_row }, window, cx);
981 }
982 });
983 }
984
985 fn handle_editor_event(
986 &mut self,
987 _: &Entity<Editor>,
988 event: &EditorEvent,
989 window: &mut Window,
990 cx: &mut Context<Self>,
991 ) {
992 match event {
993 EditorEvent::ScrollPositionChanged { autoscroll, .. } => {
994 let cursor_scroll_position = self.cursor_scroll_position(window, cx);
995 if *autoscroll {
996 self.scroll_position = cursor_scroll_position;
997 } else if self.scroll_position != cursor_scroll_position {
998 self.scroll_position = None;
999 }
1000 }
1001 EditorEvent::SelectionsChanged { .. } => {
1002 self.scroll_position = self.cursor_scroll_position(window, cx);
1003 self.update_active_patch(window, cx);
1004 }
1005 _ => {}
1006 }
1007 cx.emit(event.clone());
1008 }
1009
1010 fn active_patch(&self) -> Option<(Range<text::Anchor>, &PatchViewState)> {
1011 let patch = self.active_patch.as_ref()?;
1012 Some((patch.clone(), self.patches.get(&patch)?))
1013 }
1014
1015 fn update_active_patch(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1016 let newest_cursor = self.editor.update(cx, |editor, cx| {
1017 editor.selections.newest::<Point>(cx).head()
1018 });
1019 let context = self.context.read(cx);
1020
1021 let new_patch = context.patch_containing(newest_cursor, cx).cloned();
1022
1023 if new_patch.as_ref().map(|p| &p.range) == self.active_patch.as_ref() {
1024 return;
1025 }
1026
1027 if let Some(old_patch_range) = self.active_patch.take() {
1028 if let Some(patch_state) = self.patches.get_mut(&old_patch_range) {
1029 if let Some(state) = patch_state.editor.take() {
1030 if let Some(editor) = state.editor.upgrade() {
1031 self.close_patch_editor(editor, window, cx);
1032 }
1033 }
1034 }
1035 }
1036
1037 if let Some(new_patch) = new_patch {
1038 self.active_patch = Some(new_patch.range.clone());
1039
1040 if let Some(patch_state) = self.patches.get_mut(&new_patch.range) {
1041 let mut editor = None;
1042 if let Some(state) = &patch_state.editor {
1043 if let Some(opened_editor) = state.editor.upgrade() {
1044 editor = Some(opened_editor);
1045 }
1046 }
1047
1048 if let Some(editor) = editor {
1049 self.workspace
1050 .update(cx, |workspace, cx| {
1051 workspace.activate_item(&editor, true, false, window, cx);
1052 })
1053 .ok();
1054 } else {
1055 patch_state.update_task =
1056 Some(cx.spawn_in(window, move |this, cx| async move {
1057 Self::open_patch_editor(this, new_patch, cx).await.log_err();
1058 }));
1059 }
1060 }
1061 }
1062 }
1063
1064 fn close_patch_editor(
1065 &mut self,
1066 editor: Entity<ProposedChangesEditor>,
1067 window: &mut Window,
1068 cx: &mut Context<ContextEditor>,
1069 ) {
1070 self.workspace
1071 .update(cx, |workspace, cx| {
1072 if let Some(pane) = workspace.pane_for(&editor) {
1073 pane.update(cx, |pane, cx| {
1074 let item_id = editor.entity_id();
1075 if !editor.read(cx).focus_handle(cx).is_focused(window) {
1076 pane.close_item_by_id(item_id, SaveIntent::Skip, window, cx)
1077 .detach_and_log_err(cx);
1078 }
1079 });
1080 }
1081 })
1082 .ok();
1083 }
1084
1085 async fn open_patch_editor(
1086 this: WeakEntity<Self>,
1087 patch: AssistantPatch,
1088 mut cx: AsyncWindowContext,
1089 ) -> Result<()> {
1090 let project = this.update(&mut cx, |this, _| this.project.clone())?;
1091 let resolved_patch = patch.resolve(project.clone(), &mut cx).await;
1092
1093 let editor = cx.new_window_entity(|window, cx| {
1094 let editor = ProposedChangesEditor::new(
1095 patch.title.clone(),
1096 resolved_patch
1097 .edit_groups
1098 .iter()
1099 .map(|(buffer, groups)| ProposedChangeLocation {
1100 buffer: buffer.clone(),
1101 ranges: groups
1102 .iter()
1103 .map(|group| group.context_range.clone())
1104 .collect(),
1105 })
1106 .collect(),
1107 Some(project.clone()),
1108 window,
1109 cx,
1110 );
1111 resolved_patch.apply(&editor, cx);
1112 editor
1113 })?;
1114
1115 this.update_in(&mut cx, |this, window, cx| {
1116 if let Some(patch_state) = this.patches.get_mut(&patch.range) {
1117 patch_state.editor = Some(PatchEditorState {
1118 editor: editor.downgrade(),
1119 opened_patch: patch,
1120 });
1121 patch_state.update_task.take();
1122 }
1123
1124 this.workspace
1125 .update(cx, |workspace, cx| {
1126 workspace.add_item_to_active_pane(
1127 Box::new(editor.clone()),
1128 None,
1129 false,
1130 window,
1131 cx,
1132 )
1133 })
1134 .log_err();
1135 })?;
1136
1137 Ok(())
1138 }
1139
1140 async fn update_patch_editor(
1141 this: WeakEntity<Self>,
1142 patch: AssistantPatch,
1143 mut cx: AsyncWindowContext,
1144 ) -> Result<()> {
1145 let project = this.update(&mut cx, |this, _| this.project.clone())?;
1146 let resolved_patch = patch.resolve(project.clone(), &mut cx).await;
1147 this.update_in(&mut cx, |this, window, cx| {
1148 let patch_state = this.patches.get_mut(&patch.range)?;
1149
1150 let locations = resolved_patch
1151 .edit_groups
1152 .iter()
1153 .map(|(buffer, groups)| ProposedChangeLocation {
1154 buffer: buffer.clone(),
1155 ranges: groups
1156 .iter()
1157 .map(|group| group.context_range.clone())
1158 .collect(),
1159 })
1160 .collect();
1161
1162 if let Some(state) = &mut patch_state.editor {
1163 if let Some(editor) = state.editor.upgrade() {
1164 editor.update(cx, |editor, cx| {
1165 editor.set_title(patch.title.clone(), cx);
1166 editor.reset_locations(locations, window, cx);
1167 resolved_patch.apply(editor, cx);
1168 });
1169
1170 state.opened_patch = patch;
1171 } else {
1172 patch_state.editor.take();
1173 }
1174 }
1175 patch_state.update_task.take();
1176
1177 Some(())
1178 })?;
1179 Ok(())
1180 }
1181
1182 fn handle_editor_search_event(
1183 &mut self,
1184 _: &Entity<Editor>,
1185 event: &SearchEvent,
1186 _window: &mut Window,
1187 cx: &mut Context<Self>,
1188 ) {
1189 cx.emit(event.clone());
1190 }
1191
1192 fn cursor_scroll_position(
1193 &self,
1194 window: &mut Window,
1195 cx: &mut Context<Self>,
1196 ) -> Option<ScrollPosition> {
1197 self.editor.update(cx, |editor, cx| {
1198 let snapshot = editor.snapshot(window, cx);
1199 let cursor = editor.selections.newest_anchor().head();
1200 let cursor_row = cursor
1201 .to_display_point(&snapshot.display_snapshot)
1202 .row()
1203 .as_f32();
1204 let scroll_position = editor
1205 .scroll_manager
1206 .anchor()
1207 .scroll_position(&snapshot.display_snapshot);
1208
1209 let scroll_bottom = scroll_position.y + editor.visible_line_count().unwrap_or(0.);
1210 if (scroll_position.y..scroll_bottom).contains(&cursor_row) {
1211 Some(ScrollPosition {
1212 cursor,
1213 offset_before_cursor: point(scroll_position.x, cursor_row - scroll_position.y),
1214 })
1215 } else {
1216 None
1217 }
1218 })
1219 }
1220
1221 fn esc_kbd(cx: &App) -> Div {
1222 let colors = cx.theme().colors().clone();
1223
1224 h_flex()
1225 .items_center()
1226 .gap_1()
1227 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
1228 .text_size(TextSize::XSmall.rems(cx))
1229 .text_color(colors.text_muted)
1230 .child("Press")
1231 .child(
1232 h_flex()
1233 .rounded_md()
1234 .px_1()
1235 .mr_0p5()
1236 .border_1()
1237 .border_color(theme::color_alpha(colors.border_variant, 0.6))
1238 .bg(theme::color_alpha(colors.element_background, 0.6))
1239 .child("esc"),
1240 )
1241 .child("to cancel")
1242 }
1243
1244 fn update_message_headers(&mut self, cx: &mut Context<Self>) {
1245 self.editor.update(cx, |editor, cx| {
1246 let buffer = editor.buffer().read(cx).snapshot(cx);
1247
1248 let excerpt_id = *buffer.as_singleton().unwrap().0;
1249 let mut old_blocks = std::mem::take(&mut self.blocks);
1250 let mut blocks_to_remove: HashMap<_, _> = old_blocks
1251 .iter()
1252 .map(|(message_id, (_, block_id))| (*message_id, *block_id))
1253 .collect();
1254 let mut blocks_to_replace: HashMap<_, RenderBlock> = Default::default();
1255
1256 let render_block = |message: MessageMetadata| -> RenderBlock {
1257 Arc::new({
1258 let context = self.context.clone();
1259
1260 move |cx| {
1261 let message_id = MessageId(message.timestamp);
1262 let llm_loading = message.role == Role::Assistant
1263 && message.status == MessageStatus::Pending;
1264
1265 let (label, spinner, note) = match message.role {
1266 Role::User => (
1267 Label::new("You").color(Color::Default).into_any_element(),
1268 None,
1269 None,
1270 ),
1271 Role::Assistant => {
1272 let base_label = Label::new("Assistant").color(Color::Info);
1273 let mut spinner = None;
1274 let mut note = None;
1275 let animated_label = if llm_loading {
1276 base_label
1277 .with_animation(
1278 "pulsating-label",
1279 Animation::new(Duration::from_secs(2))
1280 .repeat()
1281 .with_easing(pulsating_between(0.4, 0.8)),
1282 |label, delta| label.alpha(delta),
1283 )
1284 .into_any_element()
1285 } else {
1286 base_label.into_any_element()
1287 };
1288 if llm_loading {
1289 spinner = Some(
1290 Icon::new(IconName::ArrowCircle)
1291 .size(IconSize::XSmall)
1292 .color(Color::Info)
1293 .with_animation(
1294 "arrow-circle",
1295 Animation::new(Duration::from_secs(2)).repeat(),
1296 |icon, delta| {
1297 icon.transform(Transformation::rotate(
1298 percentage(delta),
1299 ))
1300 },
1301 )
1302 .into_any_element(),
1303 );
1304 note = Some(Self::esc_kbd(cx).into_any_element());
1305 }
1306 (animated_label, spinner, note)
1307 }
1308 Role::System => (
1309 Label::new("System")
1310 .color(Color::Warning)
1311 .into_any_element(),
1312 None,
1313 None,
1314 ),
1315 };
1316
1317 let sender = h_flex()
1318 .items_center()
1319 .gap_2p5()
1320 .child(
1321 ButtonLike::new("role")
1322 .style(ButtonStyle::Filled)
1323 .child(
1324 h_flex()
1325 .items_center()
1326 .gap_1p5()
1327 .child(label)
1328 .children(spinner),
1329 )
1330 .tooltip(|window, cx| {
1331 Tooltip::with_meta(
1332 "Toggle message role",
1333 None,
1334 "Available roles: You (User), Assistant, System",
1335 window,
1336 cx,
1337 )
1338 })
1339 .on_click({
1340 let context = context.clone();
1341 move |_, _window, cx| {
1342 context.update(cx, |context, cx| {
1343 context.cycle_message_roles(
1344 HashSet::from_iter(Some(message_id)),
1345 cx,
1346 )
1347 })
1348 }
1349 }),
1350 )
1351 .children(note);
1352
1353 h_flex()
1354 .id(("message_header", message_id.as_u64()))
1355 .pl(cx.gutter_dimensions.full_width())
1356 .h_11()
1357 .w_full()
1358 .relative()
1359 .gap_1p5()
1360 .child(sender)
1361 .children(match &message.cache {
1362 Some(cache) if cache.is_final_anchor => match cache.status {
1363 CacheStatus::Cached => Some(
1364 div()
1365 .id("cached")
1366 .child(
1367 Icon::new(IconName::DatabaseZap)
1368 .size(IconSize::XSmall)
1369 .color(Color::Hint),
1370 )
1371 .tooltip(|window, cx| {
1372 Tooltip::with_meta(
1373 "Context Cached",
1374 None,
1375 "Large messages cached to optimize performance",
1376 window,
1377 cx,
1378 )
1379 })
1380 .into_any_element(),
1381 ),
1382 CacheStatus::Pending => Some(
1383 div()
1384 .child(
1385 Icon::new(IconName::Ellipsis)
1386 .size(IconSize::XSmall)
1387 .color(Color::Hint),
1388 )
1389 .into_any_element(),
1390 ),
1391 },
1392 _ => None,
1393 })
1394 .children(match &message.status {
1395 MessageStatus::Error(error) => Some(
1396 Button::new("show-error", "Error")
1397 .color(Color::Error)
1398 .selected_label_color(Color::Error)
1399 .selected_icon_color(Color::Error)
1400 .icon(IconName::XCircle)
1401 .icon_color(Color::Error)
1402 .icon_size(IconSize::XSmall)
1403 .icon_position(IconPosition::Start)
1404 .tooltip(Tooltip::text("View Details"))
1405 .on_click({
1406 let context = context.clone();
1407 let error = error.clone();
1408 move |_, _window, cx| {
1409 context.update(cx, |_, cx| {
1410 cx.emit(ContextEvent::ShowAssistError(
1411 error.clone(),
1412 ));
1413 });
1414 }
1415 })
1416 .into_any_element(),
1417 ),
1418 MessageStatus::Canceled => Some(
1419 h_flex()
1420 .gap_1()
1421 .items_center()
1422 .child(
1423 Icon::new(IconName::XCircle)
1424 .color(Color::Disabled)
1425 .size(IconSize::XSmall),
1426 )
1427 .child(
1428 Label::new("Canceled")
1429 .size(LabelSize::Small)
1430 .color(Color::Disabled),
1431 )
1432 .into_any_element(),
1433 ),
1434 _ => None,
1435 })
1436 .into_any_element()
1437 }
1438 })
1439 };
1440 let create_block_properties = |message: &Message| BlockProperties {
1441 height: 2,
1442 style: BlockStyle::Sticky,
1443 placement: BlockPlacement::Above(
1444 buffer
1445 .anchor_in_excerpt(excerpt_id, message.anchor_range.start)
1446 .unwrap(),
1447 ),
1448 priority: usize::MAX,
1449 render: render_block(MessageMetadata::from(message)),
1450 };
1451 let mut new_blocks = vec![];
1452 let mut block_index_to_message = vec![];
1453 for message in self.context.read(cx).messages(cx) {
1454 if let Some(_) = blocks_to_remove.remove(&message.id) {
1455 // This is an old message that we might modify.
1456 let Some((meta, block_id)) = old_blocks.get_mut(&message.id) else {
1457 debug_assert!(
1458 false,
1459 "old_blocks should contain a message_id we've just removed."
1460 );
1461 continue;
1462 };
1463 // Should we modify it?
1464 let message_meta = MessageMetadata::from(&message);
1465 if meta != &message_meta {
1466 blocks_to_replace.insert(*block_id, render_block(message_meta.clone()));
1467 *meta = message_meta;
1468 }
1469 } else {
1470 // This is a new message.
1471 new_blocks.push(create_block_properties(&message));
1472 block_index_to_message.push((message.id, MessageMetadata::from(&message)));
1473 }
1474 }
1475 editor.replace_blocks(blocks_to_replace, None, cx);
1476 editor.remove_blocks(blocks_to_remove.into_values().collect(), None, cx);
1477
1478 let ids = editor.insert_blocks(new_blocks, None, cx);
1479 old_blocks.extend(ids.into_iter().zip(block_index_to_message).map(
1480 |(block_id, (message_id, message_meta))| (message_id, (message_meta, block_id)),
1481 ));
1482 self.blocks = old_blocks;
1483 });
1484 }
1485
1486 /// Returns either the selected text, or the content of the Markdown code
1487 /// block surrounding the cursor.
1488 fn get_selection_or_code_block(
1489 context_editor_view: &Entity<ContextEditor>,
1490 cx: &mut Context<Workspace>,
1491 ) -> Option<(String, bool)> {
1492 const CODE_FENCE_DELIMITER: &'static str = "```";
1493
1494 let context_editor = context_editor_view.read(cx).editor.clone();
1495 context_editor.update(cx, |context_editor, cx| {
1496 if context_editor.selections.newest::<Point>(cx).is_empty() {
1497 let snapshot = context_editor.buffer().read(cx).snapshot(cx);
1498 let (_, _, snapshot) = snapshot.as_singleton()?;
1499
1500 let head = context_editor.selections.newest::<Point>(cx).head();
1501 let offset = snapshot.point_to_offset(head);
1502
1503 let surrounding_code_block_range = find_surrounding_code_block(snapshot, offset)?;
1504 let mut text = snapshot
1505 .text_for_range(surrounding_code_block_range)
1506 .collect::<String>();
1507
1508 // If there is no newline trailing the closing three-backticks, then
1509 // tree-sitter-md extends the range of the content node to include
1510 // the backticks.
1511 if text.ends_with(CODE_FENCE_DELIMITER) {
1512 text.drain((text.len() - CODE_FENCE_DELIMITER.len())..);
1513 }
1514
1515 (!text.is_empty()).then_some((text, true))
1516 } else {
1517 let anchor = context_editor.selections.newest_anchor();
1518 let text = context_editor
1519 .buffer()
1520 .read(cx)
1521 .read(cx)
1522 .text_for_range(anchor.range())
1523 .collect::<String>();
1524
1525 (!text.is_empty()).then_some((text, false))
1526 }
1527 })
1528 }
1529
1530 pub fn insert_selection(
1531 workspace: &mut Workspace,
1532 _: &InsertIntoEditor,
1533 window: &mut Window,
1534 cx: &mut Context<Workspace>,
1535 ) {
1536 let Some(assistant_panel_delegate) = <dyn AssistantPanelDelegate>::try_global(cx) else {
1537 return;
1538 };
1539 let Some(context_editor_view) =
1540 assistant_panel_delegate.active_context_editor(workspace, window, cx)
1541 else {
1542 return;
1543 };
1544 let Some(active_editor_view) = workspace
1545 .active_item(cx)
1546 .and_then(|item| item.act_as::<Editor>(cx))
1547 else {
1548 return;
1549 };
1550
1551 if let Some((text, _)) = Self::get_selection_or_code_block(&context_editor_view, cx) {
1552 active_editor_view.update(cx, |editor, cx| {
1553 editor.insert(&text, window, cx);
1554 editor.focus_handle(cx).focus(window);
1555 })
1556 }
1557 }
1558
1559 pub fn copy_code(
1560 workspace: &mut Workspace,
1561 _: &CopyCode,
1562 window: &mut Window,
1563 cx: &mut Context<Workspace>,
1564 ) {
1565 let result = maybe!({
1566 let assistant_panel_delegate = <dyn AssistantPanelDelegate>::try_global(cx)?;
1567 let context_editor_view =
1568 assistant_panel_delegate.active_context_editor(workspace, window, cx)?;
1569 Self::get_selection_or_code_block(&context_editor_view, cx)
1570 });
1571 let Some((text, is_code_block)) = result else {
1572 return;
1573 };
1574
1575 cx.write_to_clipboard(ClipboardItem::new_string(text));
1576
1577 struct CopyToClipboardToast;
1578 workspace.show_toast(
1579 Toast::new(
1580 NotificationId::unique::<CopyToClipboardToast>(),
1581 format!(
1582 "{} copied to clipboard.",
1583 if is_code_block {
1584 "Code block"
1585 } else {
1586 "Selection"
1587 }
1588 ),
1589 )
1590 .autohide(),
1591 cx,
1592 );
1593 }
1594
1595 pub fn insert_dragged_files(
1596 workspace: &mut Workspace,
1597 action: &InsertDraggedFiles,
1598 window: &mut Window,
1599 cx: &mut Context<Workspace>,
1600 ) {
1601 let Some(assistant_panel_delegate) = <dyn AssistantPanelDelegate>::try_global(cx) else {
1602 return;
1603 };
1604 let Some(context_editor_view) =
1605 assistant_panel_delegate.active_context_editor(workspace, window, cx)
1606 else {
1607 return;
1608 };
1609
1610 let project = workspace.project().clone();
1611
1612 let paths = match action {
1613 InsertDraggedFiles::ProjectPaths(paths) => Task::ready((paths.clone(), vec![])),
1614 InsertDraggedFiles::ExternalFiles(paths) => {
1615 let tasks = paths
1616 .clone()
1617 .into_iter()
1618 .map(|path| Workspace::project_path_for_path(project.clone(), &path, false, cx))
1619 .collect::<Vec<_>>();
1620
1621 cx.spawn(move |_, cx| async move {
1622 let mut paths = vec![];
1623 let mut worktrees = vec![];
1624
1625 let opened_paths = futures::future::join_all(tasks).await;
1626 for (worktree, project_path) in opened_paths.into_iter().flatten() {
1627 let Ok(worktree_root_name) =
1628 worktree.read_with(&cx, |worktree, _| worktree.root_name().to_string())
1629 else {
1630 continue;
1631 };
1632
1633 let mut full_path = PathBuf::from(worktree_root_name.clone());
1634 full_path.push(&project_path.path);
1635 paths.push(full_path);
1636 worktrees.push(worktree);
1637 }
1638
1639 (paths, worktrees)
1640 })
1641 }
1642 };
1643
1644 window
1645 .spawn(cx, |mut cx| async move {
1646 let (paths, dragged_file_worktrees) = paths.await;
1647 let cmd_name = FileSlashCommand.name();
1648
1649 context_editor_view
1650 .update_in(&mut cx, |context_editor, window, cx| {
1651 let file_argument = paths
1652 .into_iter()
1653 .map(|path| path.to_string_lossy().to_string())
1654 .collect::<Vec<_>>()
1655 .join(" ");
1656
1657 context_editor.editor.update(cx, |editor, cx| {
1658 editor.insert("\n", window, cx);
1659 editor.insert(&format!("/{} {}", cmd_name, file_argument), window, cx);
1660 });
1661
1662 context_editor.confirm_command(&ConfirmCommand, window, cx);
1663
1664 context_editor
1665 .dragged_file_worktrees
1666 .extend(dragged_file_worktrees);
1667 })
1668 .log_err();
1669 })
1670 .detach();
1671 }
1672
1673 pub fn quote_selection(
1674 workspace: &mut Workspace,
1675 _: &QuoteSelection,
1676 window: &mut Window,
1677 cx: &mut Context<Workspace>,
1678 ) {
1679 let Some(assistant_panel_delegate) = <dyn AssistantPanelDelegate>::try_global(cx) else {
1680 return;
1681 };
1682
1683 let Some(creases) = selections_creases(workspace, cx) else {
1684 return;
1685 };
1686
1687 if creases.is_empty() {
1688 return;
1689 }
1690
1691 assistant_panel_delegate.quote_selection(workspace, creases, window, cx);
1692 }
1693
1694 pub fn quote_creases(
1695 &mut self,
1696 creases: Vec<(String, String)>,
1697 window: &mut Window,
1698 cx: &mut Context<Self>,
1699 ) {
1700 self.editor.update(cx, |editor, cx| {
1701 editor.insert("\n", window, cx);
1702 for (text, crease_title) in creases {
1703 let point = editor.selections.newest::<Point>(cx).head();
1704 let start_row = MultiBufferRow(point.row);
1705
1706 editor.insert(&text, window, cx);
1707
1708 let snapshot = editor.buffer().read(cx).snapshot(cx);
1709 let anchor_before = snapshot.anchor_after(point);
1710 let anchor_after = editor
1711 .selections
1712 .newest_anchor()
1713 .head()
1714 .bias_left(&snapshot);
1715
1716 editor.insert("\n", window, cx);
1717
1718 let fold_placeholder =
1719 quote_selection_fold_placeholder(crease_title, cx.entity().downgrade());
1720 let crease = Crease::inline(
1721 anchor_before..anchor_after,
1722 fold_placeholder,
1723 render_quote_selection_output_toggle,
1724 |_, _, _, _| Empty.into_any(),
1725 );
1726 editor.insert_creases(vec![crease], cx);
1727 editor.fold_at(
1728 &FoldAt {
1729 buffer_row: start_row,
1730 },
1731 window,
1732 cx,
1733 );
1734 }
1735 })
1736 }
1737
1738 fn copy(&mut self, _: &editor::actions::Copy, _window: &mut Window, cx: &mut Context<Self>) {
1739 if self.editor.read(cx).selections.count() == 1 {
1740 let (copied_text, metadata, _) = self.get_clipboard_contents(cx);
1741 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1742 copied_text,
1743 metadata,
1744 ));
1745 cx.stop_propagation();
1746 return;
1747 }
1748
1749 cx.propagate();
1750 }
1751
1752 fn cut(&mut self, _: &editor::actions::Cut, window: &mut Window, cx: &mut Context<Self>) {
1753 if self.editor.read(cx).selections.count() == 1 {
1754 let (copied_text, metadata, selections) = self.get_clipboard_contents(cx);
1755
1756 self.editor.update(cx, |editor, cx| {
1757 editor.transact(window, cx, |this, window, cx| {
1758 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
1759 s.select(selections);
1760 });
1761 this.insert("", window, cx);
1762 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1763 copied_text,
1764 metadata,
1765 ));
1766 });
1767 });
1768
1769 cx.stop_propagation();
1770 return;
1771 }
1772
1773 cx.propagate();
1774 }
1775
1776 fn get_clipboard_contents(
1777 &mut self,
1778 cx: &mut Context<Self>,
1779 ) -> (String, CopyMetadata, Vec<text::Selection<usize>>) {
1780 let (snapshot, selection, creases) = self.editor.update(cx, |editor, cx| {
1781 let mut selection = editor.selections.newest::<Point>(cx);
1782 let snapshot = editor.buffer().read(cx).snapshot(cx);
1783
1784 let is_entire_line = selection.is_empty() || editor.selections.line_mode;
1785 if is_entire_line {
1786 selection.start = Point::new(selection.start.row, 0);
1787 selection.end =
1788 cmp::min(snapshot.max_point(), Point::new(selection.start.row + 1, 0));
1789 selection.goal = SelectionGoal::None;
1790 }
1791
1792 let selection_start = snapshot.point_to_offset(selection.start);
1793
1794 (
1795 snapshot.clone(),
1796 selection.clone(),
1797 editor.display_map.update(cx, |display_map, cx| {
1798 display_map
1799 .snapshot(cx)
1800 .crease_snapshot
1801 .creases_in_range(
1802 MultiBufferRow(selection.start.row)
1803 ..MultiBufferRow(selection.end.row + 1),
1804 &snapshot,
1805 )
1806 .filter_map(|crease| {
1807 if let Crease::Inline {
1808 range, metadata, ..
1809 } = &crease
1810 {
1811 let metadata = metadata.as_ref()?;
1812 let start = range
1813 .start
1814 .to_offset(&snapshot)
1815 .saturating_sub(selection_start);
1816 let end = range
1817 .end
1818 .to_offset(&snapshot)
1819 .saturating_sub(selection_start);
1820
1821 let range_relative_to_selection = start..end;
1822 if !range_relative_to_selection.is_empty() {
1823 return Some(SelectedCreaseMetadata {
1824 range_relative_to_selection,
1825 crease: metadata.clone(),
1826 });
1827 }
1828 }
1829 None
1830 })
1831 .collect::<Vec<_>>()
1832 }),
1833 )
1834 });
1835
1836 let selection = selection.map(|point| snapshot.point_to_offset(point));
1837 let context = self.context.read(cx);
1838
1839 let mut text = String::new();
1840 for message in context.messages(cx) {
1841 if message.offset_range.start >= selection.range().end {
1842 break;
1843 } else if message.offset_range.end >= selection.range().start {
1844 let range = cmp::max(message.offset_range.start, selection.range().start)
1845 ..cmp::min(message.offset_range.end, selection.range().end);
1846 if !range.is_empty() {
1847 for chunk in context.buffer().read(cx).text_for_range(range) {
1848 text.push_str(chunk);
1849 }
1850 if message.offset_range.end < selection.range().end {
1851 text.push('\n');
1852 }
1853 }
1854 }
1855 }
1856
1857 (text, CopyMetadata { creases }, vec![selection])
1858 }
1859
1860 fn paste(
1861 &mut self,
1862 action: &editor::actions::Paste,
1863 window: &mut Window,
1864 cx: &mut Context<Self>,
1865 ) {
1866 cx.stop_propagation();
1867
1868 let images = if let Some(item) = cx.read_from_clipboard() {
1869 item.into_entries()
1870 .filter_map(|entry| {
1871 if let ClipboardEntry::Image(image) = entry {
1872 Some(image)
1873 } else {
1874 None
1875 }
1876 })
1877 .collect()
1878 } else {
1879 Vec::new()
1880 };
1881
1882 let metadata = if let Some(item) = cx.read_from_clipboard() {
1883 item.entries().first().and_then(|entry| {
1884 if let ClipboardEntry::String(text) = entry {
1885 text.metadata_json::<CopyMetadata>()
1886 } else {
1887 None
1888 }
1889 })
1890 } else {
1891 None
1892 };
1893
1894 if images.is_empty() {
1895 self.editor.update(cx, |editor, cx| {
1896 let paste_position = editor.selections.newest::<usize>(cx).head();
1897 editor.paste(action, window, cx);
1898
1899 if let Some(metadata) = metadata {
1900 let buffer = editor.buffer().read(cx).snapshot(cx);
1901
1902 let mut buffer_rows_to_fold = BTreeSet::new();
1903 let weak_editor = cx.entity().downgrade();
1904 editor.insert_creases(
1905 metadata.creases.into_iter().map(|metadata| {
1906 let start = buffer.anchor_after(
1907 paste_position + metadata.range_relative_to_selection.start,
1908 );
1909 let end = buffer.anchor_before(
1910 paste_position + metadata.range_relative_to_selection.end,
1911 );
1912
1913 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1914 buffer_rows_to_fold.insert(buffer_row);
1915 Crease::inline(
1916 start..end,
1917 FoldPlaceholder {
1918 render: render_fold_icon_button(
1919 weak_editor.clone(),
1920 metadata.crease.icon,
1921 metadata.crease.label.clone(),
1922 ),
1923 ..Default::default()
1924 },
1925 render_slash_command_output_toggle,
1926 |_, _, _, _| Empty.into_any(),
1927 )
1928 .with_metadata(metadata.crease.clone())
1929 }),
1930 cx,
1931 );
1932 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1933 editor.fold_at(&FoldAt { buffer_row }, window, cx);
1934 }
1935 }
1936 });
1937 } else {
1938 let mut image_positions = Vec::new();
1939 self.editor.update(cx, |editor, cx| {
1940 editor.transact(window, cx, |editor, _window, cx| {
1941 let edits = editor
1942 .selections
1943 .all::<usize>(cx)
1944 .into_iter()
1945 .map(|selection| (selection.start..selection.end, "\n"));
1946 editor.edit(edits, cx);
1947
1948 let snapshot = editor.buffer().read(cx).snapshot(cx);
1949 for selection in editor.selections.all::<usize>(cx) {
1950 image_positions.push(snapshot.anchor_before(selection.end));
1951 }
1952 });
1953 });
1954
1955 self.context.update(cx, |context, cx| {
1956 for image in images {
1957 let Some(render_image) = image.to_image_data(cx.svg_renderer()).log_err()
1958 else {
1959 continue;
1960 };
1961 let image_id = image.id();
1962 let image_task = LanguageModelImage::from_image(image, cx).shared();
1963
1964 for image_position in image_positions.iter() {
1965 context.insert_content(
1966 Content::Image {
1967 anchor: image_position.text_anchor,
1968 image_id,
1969 image: image_task.clone(),
1970 render_image: render_image.clone(),
1971 },
1972 cx,
1973 );
1974 }
1975 }
1976 });
1977 }
1978 }
1979
1980 fn update_image_blocks(&mut self, cx: &mut Context<Self>) {
1981 self.editor.update(cx, |editor, cx| {
1982 let buffer = editor.buffer().read(cx).snapshot(cx);
1983 let excerpt_id = *buffer.as_singleton().unwrap().0;
1984 let old_blocks = std::mem::take(&mut self.image_blocks);
1985 let new_blocks = self
1986 .context
1987 .read(cx)
1988 .contents(cx)
1989 .map(
1990 |Content::Image {
1991 anchor,
1992 render_image,
1993 ..
1994 }| (anchor, render_image),
1995 )
1996 .filter_map(|(anchor, render_image)| {
1997 const MAX_HEIGHT_IN_LINES: u32 = 8;
1998 let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
1999 let image = render_image.clone();
2000 anchor.is_valid(&buffer).then(|| BlockProperties {
2001 placement: BlockPlacement::Above(anchor),
2002 height: MAX_HEIGHT_IN_LINES,
2003 style: BlockStyle::Sticky,
2004 render: Arc::new(move |cx| {
2005 let image_size = size_for_image(
2006 &image,
2007 size(
2008 cx.max_width - cx.gutter_dimensions.full_width(),
2009 MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
2010 ),
2011 );
2012 h_flex()
2013 .pl(cx.gutter_dimensions.full_width())
2014 .child(
2015 img(image.clone())
2016 .object_fit(gpui::ObjectFit::ScaleDown)
2017 .w(image_size.width)
2018 .h(image_size.height),
2019 )
2020 .into_any_element()
2021 }),
2022 priority: 0,
2023 })
2024 })
2025 .collect::<Vec<_>>();
2026
2027 editor.remove_blocks(old_blocks, None, cx);
2028 let ids = editor.insert_blocks(new_blocks, None, cx);
2029 self.image_blocks = HashSet::from_iter(ids);
2030 });
2031 }
2032
2033 fn split(&mut self, _: &Split, _window: &mut Window, cx: &mut Context<Self>) {
2034 self.context.update(cx, |context, cx| {
2035 let selections = self.editor.read(cx).selections.disjoint_anchors();
2036 for selection in selections.as_ref() {
2037 let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
2038 let range = selection
2039 .map(|endpoint| endpoint.to_offset(&buffer))
2040 .range();
2041 context.split_message(range, cx);
2042 }
2043 });
2044 }
2045
2046 fn toggle_model_selector(
2047 &mut self,
2048 _: &ToggleModelSelector,
2049 window: &mut Window,
2050 cx: &mut Context<Self>,
2051 ) {
2052 self.language_model_selector_menu_handle.toggle(window, cx);
2053 }
2054
2055 fn save(&mut self, _: &Save, _window: &mut Window, cx: &mut Context<Self>) {
2056 self.context.update(cx, |context, cx| {
2057 context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
2058 });
2059 }
2060
2061 pub fn title(&self, cx: &App) -> Cow<str> {
2062 self.context
2063 .read(cx)
2064 .summary()
2065 .map(|summary| summary.text.clone())
2066 .map(Cow::Owned)
2067 .unwrap_or_else(|| Cow::Borrowed(DEFAULT_TAB_TITLE))
2068 }
2069
2070 #[allow(clippy::too_many_arguments)]
2071 fn render_patch_block(
2072 &mut self,
2073 range: Range<text::Anchor>,
2074 max_width: Pixels,
2075 gutter_width: Pixels,
2076 id: BlockId,
2077 selected: bool,
2078 window: &mut Window,
2079 cx: &mut Context<Self>,
2080 ) -> Option<AnyElement> {
2081 let snapshot = self
2082 .editor
2083 .update(cx, |editor, cx| editor.snapshot(window, cx));
2084 let (excerpt_id, _buffer_id, _) = snapshot.buffer_snapshot.as_singleton().unwrap();
2085 let excerpt_id = *excerpt_id;
2086 let anchor = snapshot
2087 .buffer_snapshot
2088 .anchor_in_excerpt(excerpt_id, range.start)
2089 .unwrap();
2090
2091 let theme = cx.theme().clone();
2092 let patch = self.context.read(cx).patch_for_range(&range, cx)?;
2093 let paths = patch
2094 .paths()
2095 .map(|p| SharedString::from(p.to_string()))
2096 .collect::<BTreeSet<_>>();
2097
2098 Some(
2099 v_flex()
2100 .id(id)
2101 .bg(theme.colors().editor_background)
2102 .ml(gutter_width)
2103 .pb_1()
2104 .w(max_width - gutter_width)
2105 .rounded_md()
2106 .border_1()
2107 .border_color(theme.colors().border_variant)
2108 .overflow_hidden()
2109 .hover(|style| style.border_color(theme.colors().text_accent))
2110 .when(selected, |this| {
2111 this.border_color(theme.colors().text_accent)
2112 })
2113 .cursor(CursorStyle::PointingHand)
2114 .on_click(cx.listener(move |this, _, window, cx| {
2115 this.editor.update(cx, |editor, cx| {
2116 editor.change_selections(None, window, cx, |selections| {
2117 selections.select_ranges(vec![anchor..anchor]);
2118 });
2119 });
2120 this.focus_active_patch(window, cx);
2121 }))
2122 .child(
2123 div()
2124 .px_2()
2125 .py_1()
2126 .overflow_hidden()
2127 .text_ellipsis()
2128 .border_b_1()
2129 .border_color(theme.colors().border_variant)
2130 .bg(theme.colors().element_background)
2131 .child(
2132 Label::new(patch.title.clone())
2133 .size(LabelSize::Small)
2134 .color(Color::Muted),
2135 ),
2136 )
2137 .children(paths.into_iter().map(|path| {
2138 h_flex()
2139 .px_2()
2140 .pt_1()
2141 .gap_1p5()
2142 .child(Icon::new(IconName::File).size(IconSize::Small))
2143 .child(Label::new(path).size(LabelSize::Small))
2144 }))
2145 .when(patch.status == AssistantPatchStatus::Pending, |div| {
2146 div.child(
2147 h_flex()
2148 .pt_1()
2149 .px_2()
2150 .gap_1()
2151 .child(
2152 Icon::new(IconName::ArrowCircle)
2153 .size(IconSize::XSmall)
2154 .color(Color::Muted)
2155 .with_animation(
2156 "arrow-circle",
2157 Animation::new(Duration::from_secs(2)).repeat(),
2158 |icon, delta| {
2159 icon.transform(Transformation::rotate(percentage(
2160 delta,
2161 )))
2162 },
2163 ),
2164 )
2165 .child(
2166 Label::new("Generating…")
2167 .color(Color::Muted)
2168 .size(LabelSize::Small)
2169 .with_animation(
2170 "pulsating-label",
2171 Animation::new(Duration::from_secs(2))
2172 .repeat()
2173 .with_easing(pulsating_between(0.4, 0.8)),
2174 |label, delta| label.alpha(delta),
2175 ),
2176 ),
2177 )
2178 })
2179 .into_any(),
2180 )
2181 }
2182
2183 fn render_notice(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2184 // This was previously gated behind the `zed-pro` feature flag. Since we
2185 // aren't planning to ship that right now, we're just hard-coding this
2186 // value to not show the nudge.
2187 let nudge = Some(false);
2188
2189 if nudge.map_or(false, |value| value) {
2190 Some(
2191 h_flex()
2192 .p_3()
2193 .border_b_1()
2194 .border_color(cx.theme().colors().border_variant)
2195 .bg(cx.theme().colors().editor_background)
2196 .justify_between()
2197 .child(
2198 h_flex()
2199 .gap_3()
2200 .child(Icon::new(IconName::ZedAssistant).color(Color::Accent))
2201 .child(Label::new("Zed AI is here! Get started by signing in →")),
2202 )
2203 .child(
2204 Button::new("sign-in", "Sign in")
2205 .size(ButtonSize::Compact)
2206 .style(ButtonStyle::Filled)
2207 .on_click(cx.listener(|this, _event, _window, cx| {
2208 let client = this
2209 .workspace
2210 .update(cx, |workspace, _| workspace.client().clone())
2211 .log_err();
2212
2213 if let Some(client) = client {
2214 cx.spawn(|this, mut cx| async move {
2215 client.authenticate_and_connect(true, &mut cx).await?;
2216 this.update(&mut cx, |_, cx| cx.notify())
2217 })
2218 .detach_and_log_err(cx)
2219 }
2220 })),
2221 )
2222 .into_any_element(),
2223 )
2224 } else if let Some(configuration_error) = configuration_error(cx) {
2225 let label = match configuration_error {
2226 ConfigurationError::NoProvider => "No LLM provider selected.",
2227 ConfigurationError::ProviderNotAuthenticated => "LLM provider is not configured.",
2228 ConfigurationError::ProviderPendingTermsAcceptance(_) => {
2229 "LLM provider requires accepting the Terms of Service."
2230 }
2231 };
2232 Some(
2233 h_flex()
2234 .px_3()
2235 .py_2()
2236 .border_b_1()
2237 .border_color(cx.theme().colors().border_variant)
2238 .bg(cx.theme().colors().editor_background)
2239 .justify_between()
2240 .child(
2241 h_flex()
2242 .gap_3()
2243 .child(
2244 Icon::new(IconName::Warning)
2245 .size(IconSize::Small)
2246 .color(Color::Warning),
2247 )
2248 .child(Label::new(label)),
2249 )
2250 .child(
2251 Button::new("open-configuration", "Configure Providers")
2252 .size(ButtonSize::Compact)
2253 .icon(Some(IconName::SlidersVertical))
2254 .icon_size(IconSize::Small)
2255 .icon_position(IconPosition::Start)
2256 .style(ButtonStyle::Filled)
2257 .on_click({
2258 let focus_handle = self.focus_handle(cx).clone();
2259 move |_event, window, cx| {
2260 focus_handle.dispatch_action(&ShowConfiguration, window, cx);
2261 }
2262 }),
2263 )
2264 .into_any_element(),
2265 )
2266 } else {
2267 None
2268 }
2269 }
2270
2271 fn render_send_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2272 let focus_handle = self.focus_handle(cx).clone();
2273
2274 let (style, tooltip) = match token_state(&self.context, cx) {
2275 Some(TokenState::NoTokensLeft { .. }) => (
2276 ButtonStyle::Tinted(TintColor::Error),
2277 Some(Tooltip::text("Token limit reached")(window, cx)),
2278 ),
2279 Some(TokenState::HasMoreTokens {
2280 over_warn_threshold,
2281 ..
2282 }) => {
2283 let (style, tooltip) = if over_warn_threshold {
2284 (
2285 ButtonStyle::Tinted(TintColor::Warning),
2286 Some(Tooltip::text("Token limit is close to exhaustion")(
2287 window, cx,
2288 )),
2289 )
2290 } else {
2291 (ButtonStyle::Filled, None)
2292 };
2293 (style, tooltip)
2294 }
2295 None => (ButtonStyle::Filled, None),
2296 };
2297
2298 let provider = LanguageModelRegistry::read_global(cx).active_provider();
2299
2300 let has_configuration_error = configuration_error(cx).is_some();
2301 let needs_to_accept_terms = self.show_accept_terms
2302 && provider
2303 .as_ref()
2304 .map_or(false, |provider| provider.must_accept_terms(cx));
2305 let disabled = has_configuration_error || needs_to_accept_terms;
2306
2307 ButtonLike::new("send_button")
2308 .disabled(disabled)
2309 .style(style)
2310 .when_some(tooltip, |button, tooltip| {
2311 button.tooltip(move |_, _| tooltip.clone())
2312 })
2313 .layer(ElevationIndex::ModalSurface)
2314 .child(Label::new(
2315 if AssistantSettings::get_global(cx).are_live_diffs_enabled(cx) {
2316 "Chat"
2317 } else {
2318 "Send"
2319 },
2320 ))
2321 .children(
2322 KeyBinding::for_action_in(&Assist, &focus_handle, window, cx)
2323 .map(|binding| binding.into_any_element()),
2324 )
2325 .on_click(move |_event, window, cx| {
2326 focus_handle.dispatch_action(&Assist, window, cx);
2327 })
2328 }
2329
2330 fn render_edit_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2331 let focus_handle = self.focus_handle(cx).clone();
2332
2333 let (style, tooltip) = match token_state(&self.context, cx) {
2334 Some(TokenState::NoTokensLeft { .. }) => (
2335 ButtonStyle::Tinted(TintColor::Error),
2336 Some(Tooltip::text("Token limit reached")(window, cx)),
2337 ),
2338 Some(TokenState::HasMoreTokens {
2339 over_warn_threshold,
2340 ..
2341 }) => {
2342 let (style, tooltip) = if over_warn_threshold {
2343 (
2344 ButtonStyle::Tinted(TintColor::Warning),
2345 Some(Tooltip::text("Token limit is close to exhaustion")(
2346 window, cx,
2347 )),
2348 )
2349 } else {
2350 (ButtonStyle::Filled, None)
2351 };
2352 (style, tooltip)
2353 }
2354 None => (ButtonStyle::Filled, None),
2355 };
2356
2357 let provider = LanguageModelRegistry::read_global(cx).active_provider();
2358
2359 let has_configuration_error = configuration_error(cx).is_some();
2360 let needs_to_accept_terms = self.show_accept_terms
2361 && provider
2362 .as_ref()
2363 .map_or(false, |provider| provider.must_accept_terms(cx));
2364 let disabled = has_configuration_error || needs_to_accept_terms;
2365
2366 ButtonLike::new("edit_button")
2367 .disabled(disabled)
2368 .style(style)
2369 .when_some(tooltip, |button, tooltip| {
2370 button.tooltip(move |_, _| tooltip.clone())
2371 })
2372 .layer(ElevationIndex::ModalSurface)
2373 .child(Label::new("Suggest Edits"))
2374 .children(
2375 KeyBinding::for_action_in(&Edit, &focus_handle, window, cx)
2376 .map(|binding| binding.into_any_element()),
2377 )
2378 .on_click(move |_event, window, cx| {
2379 focus_handle.dispatch_action(&Edit, window, cx);
2380 })
2381 }
2382
2383 fn render_inject_context_menu(&self, cx: &mut Context<Self>) -> impl IntoElement {
2384 slash_command_picker::SlashCommandSelector::new(
2385 self.slash_commands.clone(),
2386 cx.entity().downgrade(),
2387 IconButton::new("trigger", IconName::Plus)
2388 .icon_size(IconSize::Small)
2389 .icon_color(Color::Muted),
2390 move |window, cx| {
2391 Tooltip::with_meta(
2392 "Add Context",
2393 None,
2394 "Type / to insert via keyboard",
2395 window,
2396 cx,
2397 )
2398 },
2399 )
2400 }
2401
2402 fn render_language_model_selector(&self, cx: &mut Context<Self>) -> impl IntoElement {
2403 let active_model = LanguageModelRegistry::read_global(cx).active_model();
2404 let focus_handle = self.editor().focus_handle(cx).clone();
2405 let model_name = match active_model {
2406 Some(model) => model.name().0,
2407 None => SharedString::from("No model selected"),
2408 };
2409
2410 LanguageModelSelectorPopoverMenu::new(
2411 self.language_model_selector.clone(),
2412 ButtonLike::new("active-model")
2413 .style(ButtonStyle::Subtle)
2414 .child(
2415 h_flex()
2416 .gap_0p5()
2417 .child(
2418 Label::new(model_name)
2419 .size(LabelSize::Small)
2420 .color(Color::Muted),
2421 )
2422 .child(
2423 Icon::new(IconName::ChevronDown)
2424 .color(Color::Muted)
2425 .size(IconSize::XSmall),
2426 ),
2427 ),
2428 move |window, cx| {
2429 Tooltip::for_action_in(
2430 "Change Model",
2431 &ToggleModelSelector,
2432 &focus_handle,
2433 window,
2434 cx,
2435 )
2436 },
2437 gpui::Corner::BottomLeft,
2438 )
2439 .with_handle(self.language_model_selector_menu_handle.clone())
2440 }
2441
2442 fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2443 let last_error = self.last_error.as_ref()?;
2444
2445 Some(
2446 div()
2447 .absolute()
2448 .right_3()
2449 .bottom_12()
2450 .max_w_96()
2451 .py_2()
2452 .px_3()
2453 .elevation_2(cx)
2454 .occlude()
2455 .child(match last_error {
2456 AssistError::FileRequired => self.render_file_required_error(cx),
2457 AssistError::PaymentRequired => self.render_payment_required_error(cx),
2458 AssistError::MaxMonthlySpendReached => {
2459 self.render_max_monthly_spend_reached_error(cx)
2460 }
2461 AssistError::Message(error_message) => {
2462 self.render_assist_error(error_message, cx)
2463 }
2464 })
2465 .into_any(),
2466 )
2467 }
2468
2469 fn render_file_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2470 v_flex()
2471 .gap_0p5()
2472 .child(
2473 h_flex()
2474 .gap_1p5()
2475 .items_center()
2476 .child(Icon::new(IconName::Warning).color(Color::Warning))
2477 .child(
2478 Label::new("Suggest Edits needs a file to edit").weight(FontWeight::MEDIUM),
2479 ),
2480 )
2481 .child(
2482 div()
2483 .id("error-message")
2484 .max_h_24()
2485 .overflow_y_scroll()
2486 .child(Label::new(
2487 "To include files, type /file or /tab in your prompt.",
2488 )),
2489 )
2490 .child(
2491 h_flex()
2492 .justify_end()
2493 .mt_1()
2494 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2495 |this, _, _window, cx| {
2496 this.last_error = None;
2497 cx.notify();
2498 },
2499 ))),
2500 )
2501 .into_any()
2502 }
2503
2504 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2505 const ERROR_MESSAGE: &str = "Free tier exceeded. Subscribe and add payment to continue using Zed LLMs. You'll be billed at cost for tokens used.";
2506
2507 v_flex()
2508 .gap_0p5()
2509 .child(
2510 h_flex()
2511 .gap_1p5()
2512 .items_center()
2513 .child(Icon::new(IconName::XCircle).color(Color::Error))
2514 .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2515 )
2516 .child(
2517 div()
2518 .id("error-message")
2519 .max_h_24()
2520 .overflow_y_scroll()
2521 .child(Label::new(ERROR_MESSAGE)),
2522 )
2523 .child(
2524 h_flex()
2525 .justify_end()
2526 .mt_1()
2527 .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
2528 |this, _, _window, cx| {
2529 this.last_error = None;
2530 cx.open_url(&zed_urls::account_url(cx));
2531 cx.notify();
2532 },
2533 )))
2534 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2535 |this, _, _window, cx| {
2536 this.last_error = None;
2537 cx.notify();
2538 },
2539 ))),
2540 )
2541 .into_any()
2542 }
2543
2544 fn render_max_monthly_spend_reached_error(&self, cx: &mut Context<Self>) -> AnyElement {
2545 const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
2546
2547 v_flex()
2548 .gap_0p5()
2549 .child(
2550 h_flex()
2551 .gap_1p5()
2552 .items_center()
2553 .child(Icon::new(IconName::XCircle).color(Color::Error))
2554 .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
2555 )
2556 .child(
2557 div()
2558 .id("error-message")
2559 .max_h_24()
2560 .overflow_y_scroll()
2561 .child(Label::new(ERROR_MESSAGE)),
2562 )
2563 .child(
2564 h_flex()
2565 .justify_end()
2566 .mt_1()
2567 .child(
2568 Button::new("subscribe", "Update Monthly Spend Limit").on_click(
2569 cx.listener(|this, _, _window, cx| {
2570 this.last_error = None;
2571 cx.open_url(&zed_urls::account_url(cx));
2572 cx.notify();
2573 }),
2574 ),
2575 )
2576 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2577 |this, _, _window, cx| {
2578 this.last_error = None;
2579 cx.notify();
2580 },
2581 ))),
2582 )
2583 .into_any()
2584 }
2585
2586 fn render_assist_error(
2587 &self,
2588 error_message: &SharedString,
2589 cx: &mut Context<Self>,
2590 ) -> AnyElement {
2591 v_flex()
2592 .gap_0p5()
2593 .child(
2594 h_flex()
2595 .gap_1p5()
2596 .items_center()
2597 .child(Icon::new(IconName::XCircle).color(Color::Error))
2598 .child(
2599 Label::new("Error interacting with language model")
2600 .weight(FontWeight::MEDIUM),
2601 ),
2602 )
2603 .child(
2604 div()
2605 .id("error-message")
2606 .max_h_32()
2607 .overflow_y_scroll()
2608 .child(Label::new(error_message.clone())),
2609 )
2610 .child(
2611 h_flex()
2612 .justify_end()
2613 .mt_1()
2614 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2615 |this, _, _window, cx| {
2616 this.last_error = None;
2617 cx.notify();
2618 },
2619 ))),
2620 )
2621 .into_any()
2622 }
2623}
2624
2625/// Returns the contents of the *outermost* fenced code block that contains the given offset.
2626fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
2627 const CODE_BLOCK_NODE: &'static str = "fenced_code_block";
2628 const CODE_BLOCK_CONTENT: &'static str = "code_fence_content";
2629
2630 let layer = snapshot.syntax_layers().next()?;
2631
2632 let root_node = layer.node();
2633 let mut cursor = root_node.walk();
2634
2635 // Go to the first child for the given offset
2636 while cursor.goto_first_child_for_byte(offset).is_some() {
2637 // If we're at the end of the node, go to the next one.
2638 // Example: if you have a fenced-code-block, and you're on the start of the line
2639 // right after the closing ```, you want to skip the fenced-code-block and
2640 // go to the next sibling.
2641 if cursor.node().end_byte() == offset {
2642 cursor.goto_next_sibling();
2643 }
2644
2645 if cursor.node().start_byte() > offset {
2646 break;
2647 }
2648
2649 // We found the fenced code block.
2650 if cursor.node().kind() == CODE_BLOCK_NODE {
2651 // Now we need to find the child node that contains the code.
2652 cursor.goto_first_child();
2653 loop {
2654 if cursor.node().kind() == CODE_BLOCK_CONTENT {
2655 return Some(cursor.node().byte_range());
2656 }
2657 if !cursor.goto_next_sibling() {
2658 break;
2659 }
2660 }
2661 }
2662 }
2663
2664 None
2665}
2666
2667fn render_fold_icon_button(
2668 editor: WeakEntity<Editor>,
2669 icon: IconName,
2670 label: SharedString,
2671) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2672 Arc::new(move |fold_id, fold_range, _cx| {
2673 let editor = editor.clone();
2674 ButtonLike::new(fold_id)
2675 .style(ButtonStyle::Filled)
2676 .layer(ElevationIndex::ElevatedSurface)
2677 .child(Icon::new(icon))
2678 .child(Label::new(label.clone()).single_line())
2679 .on_click(move |_, window, cx| {
2680 editor
2681 .update(cx, |editor, cx| {
2682 let buffer_start = fold_range
2683 .start
2684 .to_point(&editor.buffer().read(cx).read(cx));
2685 let buffer_row = MultiBufferRow(buffer_start.row);
2686 editor.unfold_at(&UnfoldAt { buffer_row }, window, cx);
2687 })
2688 .ok();
2689 })
2690 .into_any_element()
2691 })
2692}
2693
2694type ToggleFold = Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>;
2695
2696fn render_slash_command_output_toggle(
2697 row: MultiBufferRow,
2698 is_folded: bool,
2699 fold: ToggleFold,
2700 _window: &mut Window,
2701 _cx: &mut App,
2702) -> AnyElement {
2703 Disclosure::new(
2704 ("slash-command-output-fold-indicator", row.0 as u64),
2705 !is_folded,
2706 )
2707 .toggle_state(is_folded)
2708 .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2709 .into_any_element()
2710}
2711
2712pub fn fold_toggle(
2713 name: &'static str,
2714) -> impl Fn(
2715 MultiBufferRow,
2716 bool,
2717 Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
2718 &mut Window,
2719 &mut App,
2720) -> AnyElement {
2721 move |row, is_folded, fold, _window, _cx| {
2722 Disclosure::new((name, row.0 as u64), !is_folded)
2723 .toggle_state(is_folded)
2724 .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2725 .into_any_element()
2726 }
2727}
2728
2729fn quote_selection_fold_placeholder(title: String, editor: WeakEntity<Editor>) -> FoldPlaceholder {
2730 FoldPlaceholder {
2731 render: Arc::new({
2732 move |fold_id, fold_range, _cx| {
2733 let editor = editor.clone();
2734 ButtonLike::new(fold_id)
2735 .style(ButtonStyle::Filled)
2736 .layer(ElevationIndex::ElevatedSurface)
2737 .child(Icon::new(IconName::TextSnippet))
2738 .child(Label::new(title.clone()).single_line())
2739 .on_click(move |_, window, cx| {
2740 editor
2741 .update(cx, |editor, cx| {
2742 let buffer_start = fold_range
2743 .start
2744 .to_point(&editor.buffer().read(cx).read(cx));
2745 let buffer_row = MultiBufferRow(buffer_start.row);
2746 editor.unfold_at(&UnfoldAt { buffer_row }, window, cx);
2747 })
2748 .ok();
2749 })
2750 .into_any_element()
2751 }
2752 }),
2753 merge_adjacent: false,
2754 ..Default::default()
2755 }
2756}
2757
2758fn render_quote_selection_output_toggle(
2759 row: MultiBufferRow,
2760 is_folded: bool,
2761 fold: ToggleFold,
2762 _window: &mut Window,
2763 _cx: &mut App,
2764) -> AnyElement {
2765 Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
2766 .toggle_state(is_folded)
2767 .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2768 .into_any_element()
2769}
2770
2771fn render_pending_slash_command_gutter_decoration(
2772 row: MultiBufferRow,
2773 status: &PendingSlashCommandStatus,
2774 confirm_command: Arc<dyn Fn(&mut Window, &mut App)>,
2775) -> AnyElement {
2776 let mut icon = IconButton::new(
2777 ("slash-command-gutter-decoration", row.0),
2778 ui::IconName::TriangleRight,
2779 )
2780 .on_click(move |_e, window, cx| confirm_command(window, cx))
2781 .icon_size(ui::IconSize::Small)
2782 .size(ui::ButtonSize::None);
2783
2784 match status {
2785 PendingSlashCommandStatus::Idle => {
2786 icon = icon.icon_color(Color::Muted);
2787 }
2788 PendingSlashCommandStatus::Running { .. } => {
2789 icon = icon.toggle_state(true);
2790 }
2791 PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
2792 }
2793
2794 icon.into_any_element()
2795}
2796
2797fn render_docs_slash_command_trailer(
2798 row: MultiBufferRow,
2799 command: ParsedSlashCommand,
2800 cx: &mut App,
2801) -> AnyElement {
2802 if command.arguments.is_empty() {
2803 return Empty.into_any();
2804 }
2805 let args = DocsSlashCommandArgs::parse(&command.arguments);
2806
2807 let Some(store) = args
2808 .provider()
2809 .and_then(|provider| IndexedDocsStore::try_global(provider, cx).ok())
2810 else {
2811 return Empty.into_any();
2812 };
2813
2814 let Some(package) = args.package() else {
2815 return Empty.into_any();
2816 };
2817
2818 let mut children = Vec::new();
2819
2820 if store.is_indexing(&package) {
2821 children.push(
2822 div()
2823 .id(("crates-being-indexed", row.0))
2824 .child(Icon::new(IconName::ArrowCircle).with_animation(
2825 "arrow-circle",
2826 Animation::new(Duration::from_secs(4)).repeat(),
2827 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2828 ))
2829 .tooltip({
2830 let package = package.clone();
2831 Tooltip::text(format!("Indexing {package}…"))
2832 })
2833 .into_any_element(),
2834 );
2835 }
2836
2837 if let Some(latest_error) = store.latest_error_for_package(&package) {
2838 children.push(
2839 div()
2840 .id(("latest-error", row.0))
2841 .child(
2842 Icon::new(IconName::Warning)
2843 .size(IconSize::Small)
2844 .color(Color::Warning),
2845 )
2846 .tooltip(Tooltip::text(format!("Failed to index: {latest_error}")))
2847 .into_any_element(),
2848 )
2849 }
2850
2851 let is_indexing = store.is_indexing(&package);
2852 let latest_error = store.latest_error_for_package(&package);
2853
2854 if !is_indexing && latest_error.is_none() {
2855 return Empty.into_any();
2856 }
2857
2858 h_flex().gap_2().children(children).into_any_element()
2859}
2860
2861#[derive(Debug, Clone, Serialize, Deserialize)]
2862struct CopyMetadata {
2863 creases: Vec<SelectedCreaseMetadata>,
2864}
2865
2866#[derive(Debug, Clone, Serialize, Deserialize)]
2867struct SelectedCreaseMetadata {
2868 range_relative_to_selection: Range<usize>,
2869 crease: CreaseMetadata,
2870}
2871
2872impl EventEmitter<EditorEvent> for ContextEditor {}
2873impl EventEmitter<SearchEvent> for ContextEditor {}
2874
2875impl Render for ContextEditor {
2876 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2877 let provider = LanguageModelRegistry::read_global(cx).active_provider();
2878 let accept_terms = if self.show_accept_terms {
2879 provider.as_ref().and_then(|provider| {
2880 provider.render_accept_terms(LanguageModelProviderTosView::PromptEditorPopup, cx)
2881 })
2882 } else {
2883 None
2884 };
2885
2886 v_flex()
2887 .key_context("ContextEditor")
2888 .capture_action(cx.listener(ContextEditor::cancel))
2889 .capture_action(cx.listener(ContextEditor::save))
2890 .capture_action(cx.listener(ContextEditor::copy))
2891 .capture_action(cx.listener(ContextEditor::cut))
2892 .capture_action(cx.listener(ContextEditor::paste))
2893 .capture_action(cx.listener(ContextEditor::cycle_message_role))
2894 .capture_action(cx.listener(ContextEditor::confirm_command))
2895 .on_action(cx.listener(ContextEditor::edit))
2896 .on_action(cx.listener(ContextEditor::assist))
2897 .on_action(cx.listener(ContextEditor::split))
2898 .on_action(cx.listener(ContextEditor::toggle_model_selector))
2899 .size_full()
2900 .children(self.render_notice(cx))
2901 .child(
2902 div()
2903 .flex_grow()
2904 .bg(cx.theme().colors().editor_background)
2905 .child(self.editor.clone()),
2906 )
2907 .when_some(accept_terms, |this, element| {
2908 this.child(
2909 div()
2910 .absolute()
2911 .right_3()
2912 .bottom_12()
2913 .max_w_96()
2914 .py_2()
2915 .px_3()
2916 .elevation_2(cx)
2917 .bg(cx.theme().colors().surface_background)
2918 .occlude()
2919 .child(element),
2920 )
2921 })
2922 .children(self.render_last_error(cx))
2923 .child(
2924 h_flex().w_full().relative().child(
2925 h_flex()
2926 .p_2()
2927 .w_full()
2928 .border_t_1()
2929 .border_color(cx.theme().colors().border_variant)
2930 .bg(cx.theme().colors().editor_background)
2931 .child(
2932 h_flex()
2933 .gap_1()
2934 .child(self.render_inject_context_menu(cx))
2935 .child(ui::Divider::vertical())
2936 .child(
2937 div()
2938 .pl_0p5()
2939 .child(self.render_language_model_selector(cx)),
2940 ),
2941 )
2942 .child(
2943 h_flex()
2944 .w_full()
2945 .justify_end()
2946 .when(
2947 AssistantSettings::get_global(cx).are_live_diffs_enabled(cx),
2948 |buttons| {
2949 buttons
2950 .items_center()
2951 .gap_1p5()
2952 .child(self.render_edit_button(window, cx))
2953 .child(
2954 Label::new("or")
2955 .size(LabelSize::Small)
2956 .color(Color::Muted),
2957 )
2958 },
2959 )
2960 .child(self.render_send_button(window, cx)),
2961 ),
2962 ),
2963 )
2964 }
2965}
2966
2967impl Focusable for ContextEditor {
2968 fn focus_handle(&self, cx: &App) -> FocusHandle {
2969 self.editor.focus_handle(cx)
2970 }
2971}
2972
2973impl Item for ContextEditor {
2974 type Event = editor::EditorEvent;
2975
2976 fn tab_content_text(&self, _window: &Window, cx: &App) -> Option<SharedString> {
2977 Some(util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into())
2978 }
2979
2980 fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
2981 match event {
2982 EditorEvent::Edited { .. } => {
2983 f(item::ItemEvent::Edit);
2984 }
2985 EditorEvent::TitleChanged => {
2986 f(item::ItemEvent::UpdateTab);
2987 }
2988 _ => {}
2989 }
2990 }
2991
2992 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
2993 Some(self.title(cx).to_string().into())
2994 }
2995
2996 fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
2997 Some(Box::new(handle.clone()))
2998 }
2999
3000 fn set_nav_history(
3001 &mut self,
3002 nav_history: pane::ItemNavHistory,
3003 window: &mut Window,
3004 cx: &mut Context<Self>,
3005 ) {
3006 self.editor.update(cx, |editor, cx| {
3007 Item::set_nav_history(editor, nav_history, window, cx)
3008 })
3009 }
3010
3011 fn navigate(
3012 &mut self,
3013 data: Box<dyn std::any::Any>,
3014 window: &mut Window,
3015 cx: &mut Context<Self>,
3016 ) -> bool {
3017 self.editor
3018 .update(cx, |editor, cx| Item::navigate(editor, data, window, cx))
3019 }
3020
3021 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3022 self.editor
3023 .update(cx, |editor, cx| Item::deactivated(editor, window, cx))
3024 }
3025
3026 fn act_as_type<'a>(
3027 &'a self,
3028 type_id: TypeId,
3029 self_handle: &'a Entity<Self>,
3030 _: &'a App,
3031 ) -> Option<AnyView> {
3032 if type_id == TypeId::of::<Self>() {
3033 Some(self_handle.to_any())
3034 } else if type_id == TypeId::of::<Editor>() {
3035 Some(self.editor.to_any())
3036 } else {
3037 None
3038 }
3039 }
3040
3041 fn include_in_nav_history() -> bool {
3042 false
3043 }
3044}
3045
3046impl SearchableItem for ContextEditor {
3047 type Match = <Editor as SearchableItem>::Match;
3048
3049 fn clear_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3050 self.editor.update(cx, |editor, cx| {
3051 editor.clear_matches(window, cx);
3052 });
3053 }
3054
3055 fn update_matches(
3056 &mut self,
3057 matches: &[Self::Match],
3058 window: &mut Window,
3059 cx: &mut Context<Self>,
3060 ) {
3061 self.editor
3062 .update(cx, |editor, cx| editor.update_matches(matches, window, cx));
3063 }
3064
3065 fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
3066 self.editor
3067 .update(cx, |editor, cx| editor.query_suggestion(window, cx))
3068 }
3069
3070 fn activate_match(
3071 &mut self,
3072 index: usize,
3073 matches: &[Self::Match],
3074 window: &mut Window,
3075 cx: &mut Context<Self>,
3076 ) {
3077 self.editor.update(cx, |editor, cx| {
3078 editor.activate_match(index, matches, window, cx);
3079 });
3080 }
3081
3082 fn select_matches(
3083 &mut self,
3084 matches: &[Self::Match],
3085 window: &mut Window,
3086 cx: &mut Context<Self>,
3087 ) {
3088 self.editor
3089 .update(cx, |editor, cx| editor.select_matches(matches, window, cx));
3090 }
3091
3092 fn replace(
3093 &mut self,
3094 identifier: &Self::Match,
3095 query: &project::search::SearchQuery,
3096 window: &mut Window,
3097 cx: &mut Context<Self>,
3098 ) {
3099 self.editor.update(cx, |editor, cx| {
3100 editor.replace(identifier, query, window, cx)
3101 });
3102 }
3103
3104 fn find_matches(
3105 &mut self,
3106 query: Arc<project::search::SearchQuery>,
3107 window: &mut Window,
3108 cx: &mut Context<Self>,
3109 ) -> Task<Vec<Self::Match>> {
3110 self.editor
3111 .update(cx, |editor, cx| editor.find_matches(query, window, cx))
3112 }
3113
3114 fn active_match_index(
3115 &mut self,
3116 matches: &[Self::Match],
3117 window: &mut Window,
3118 cx: &mut Context<Self>,
3119 ) -> Option<usize> {
3120 self.editor.update(cx, |editor, cx| {
3121 editor.active_match_index(matches, window, cx)
3122 })
3123 }
3124}
3125
3126impl FollowableItem for ContextEditor {
3127 fn remote_id(&self) -> Option<workspace::ViewId> {
3128 self.remote_id
3129 }
3130
3131 fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant> {
3132 let context = self.context.read(cx);
3133 Some(proto::view::Variant::ContextEditor(
3134 proto::view::ContextEditor {
3135 context_id: context.id().to_proto(),
3136 editor: if let Some(proto::view::Variant::Editor(proto)) =
3137 self.editor.read(cx).to_state_proto(window, cx)
3138 {
3139 Some(proto)
3140 } else {
3141 None
3142 },
3143 },
3144 ))
3145 }
3146
3147 fn from_state_proto(
3148 workspace: Entity<Workspace>,
3149 id: workspace::ViewId,
3150 state: &mut Option<proto::view::Variant>,
3151 window: &mut Window,
3152 cx: &mut App,
3153 ) -> Option<Task<Result<Entity<Self>>>> {
3154 let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
3155 return None;
3156 };
3157 let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
3158 unreachable!()
3159 };
3160
3161 let context_id = ContextId::from_proto(state.context_id);
3162 let editor_state = state.editor?;
3163
3164 let project = workspace.read(cx).project().clone();
3165 let assistant_panel_delegate = <dyn AssistantPanelDelegate>::try_global(cx)?;
3166
3167 let context_editor_task = workspace.update(cx, |workspace, cx| {
3168 assistant_panel_delegate.open_remote_context(workspace, context_id, window, cx)
3169 });
3170
3171 Some(window.spawn(cx, |mut cx| async move {
3172 let context_editor = context_editor_task.await?;
3173 context_editor
3174 .update_in(&mut cx, |context_editor, window, cx| {
3175 context_editor.remote_id = Some(id);
3176 context_editor.editor.update(cx, |editor, cx| {
3177 editor.apply_update_proto(
3178 &project,
3179 proto::update_view::Variant::Editor(proto::update_view::Editor {
3180 selections: editor_state.selections,
3181 pending_selection: editor_state.pending_selection,
3182 scroll_top_anchor: editor_state.scroll_top_anchor,
3183 scroll_x: editor_state.scroll_y,
3184 scroll_y: editor_state.scroll_y,
3185 ..Default::default()
3186 }),
3187 window,
3188 cx,
3189 )
3190 })
3191 })?
3192 .await?;
3193 Ok(context_editor)
3194 }))
3195 }
3196
3197 fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
3198 Editor::to_follow_event(event)
3199 }
3200
3201 fn add_event_to_update_proto(
3202 &self,
3203 event: &Self::Event,
3204 update: &mut Option<proto::update_view::Variant>,
3205 window: &Window,
3206 cx: &App,
3207 ) -> bool {
3208 self.editor
3209 .read(cx)
3210 .add_event_to_update_proto(event, update, window, cx)
3211 }
3212
3213 fn apply_update_proto(
3214 &mut self,
3215 project: &Entity<Project>,
3216 message: proto::update_view::Variant,
3217 window: &mut Window,
3218 cx: &mut Context<Self>,
3219 ) -> Task<Result<()>> {
3220 self.editor.update(cx, |editor, cx| {
3221 editor.apply_update_proto(project, message, window, cx)
3222 })
3223 }
3224
3225 fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
3226 true
3227 }
3228
3229 fn set_leader_peer_id(
3230 &mut self,
3231 leader_peer_id: Option<proto::PeerId>,
3232 window: &mut Window,
3233 cx: &mut Context<Self>,
3234 ) {
3235 self.editor.update(cx, |editor, cx| {
3236 editor.set_leader_peer_id(leader_peer_id, window, cx)
3237 })
3238 }
3239
3240 fn dedup(&self, existing: &Self, _window: &Window, cx: &App) -> Option<item::Dedup> {
3241 if existing.context.read(cx).id() == self.context.read(cx).id() {
3242 Some(item::Dedup::KeepExisting)
3243 } else {
3244 None
3245 }
3246 }
3247}
3248
3249pub struct ContextEditorToolbarItem {
3250 active_context_editor: Option<WeakEntity<ContextEditor>>,
3251 model_summary_editor: Entity<Editor>,
3252}
3253
3254impl ContextEditorToolbarItem {
3255 pub fn new(model_summary_editor: Entity<Editor>) -> Self {
3256 Self {
3257 active_context_editor: None,
3258 model_summary_editor,
3259 }
3260 }
3261}
3262
3263pub fn render_remaining_tokens(
3264 context_editor: &Entity<ContextEditor>,
3265 cx: &App,
3266) -> Option<impl IntoElement> {
3267 let context = &context_editor.read(cx).context;
3268
3269 let (token_count_color, token_count, max_token_count, tooltip) = match token_state(context, cx)?
3270 {
3271 TokenState::NoTokensLeft {
3272 max_token_count,
3273 token_count,
3274 } => (
3275 Color::Error,
3276 token_count,
3277 max_token_count,
3278 Some("Token Limit Reached"),
3279 ),
3280 TokenState::HasMoreTokens {
3281 max_token_count,
3282 token_count,
3283 over_warn_threshold,
3284 } => {
3285 let (color, tooltip) = if over_warn_threshold {
3286 (Color::Warning, Some("Token Limit is Close to Exhaustion"))
3287 } else {
3288 (Color::Muted, None)
3289 };
3290 (color, token_count, max_token_count, tooltip)
3291 }
3292 };
3293
3294 Some(
3295 h_flex()
3296 .id("token-count")
3297 .gap_0p5()
3298 .child(
3299 Label::new(humanize_token_count(token_count))
3300 .size(LabelSize::Small)
3301 .color(token_count_color),
3302 )
3303 .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
3304 .child(
3305 Label::new(humanize_token_count(max_token_count))
3306 .size(LabelSize::Small)
3307 .color(Color::Muted),
3308 )
3309 .when_some(tooltip, |element, tooltip| {
3310 element.tooltip(Tooltip::text(tooltip))
3311 }),
3312 )
3313}
3314
3315impl Render for ContextEditorToolbarItem {
3316 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3317 let left_side = h_flex()
3318 .group("chat-title-group")
3319 .gap_1()
3320 .items_center()
3321 .flex_grow()
3322 .child(
3323 div()
3324 .w_full()
3325 .when(self.active_context_editor.is_some(), |left_side| {
3326 left_side.child(self.model_summary_editor.clone())
3327 }),
3328 )
3329 .child(
3330 div().visible_on_hover("chat-title-group").child(
3331 IconButton::new("regenerate-context", IconName::RefreshTitle)
3332 .shape(ui::IconButtonShape::Square)
3333 .tooltip(Tooltip::text("Regenerate Title"))
3334 .on_click(cx.listener(move |_, _, _window, cx| {
3335 cx.emit(ContextEditorToolbarItemEvent::RegenerateSummary)
3336 })),
3337 ),
3338 );
3339
3340 let right_side = h_flex()
3341 .gap_2()
3342 // TODO display this in a nicer way, once we have a design for it.
3343 // .children({
3344 // let project = self
3345 // .workspace
3346 // .upgrade()
3347 // .map(|workspace| workspace.read(cx).project().downgrade());
3348 //
3349 // let scan_items_remaining = cx.update_global(|db: &mut SemanticDb, cx| {
3350 // project.and_then(|project| db.remaining_summaries(&project, cx))
3351 // });
3352 // scan_items_remaining
3353 // .map(|remaining_items| format!("Files to scan: {}", remaining_items))
3354 // })
3355 .children(
3356 self.active_context_editor
3357 .as_ref()
3358 .and_then(|editor| editor.upgrade())
3359 .and_then(|editor| render_remaining_tokens(&editor, cx)),
3360 );
3361
3362 h_flex()
3363 .px_0p5()
3364 .size_full()
3365 .gap_2()
3366 .justify_between()
3367 .child(left_side)
3368 .child(right_side)
3369 }
3370}
3371
3372impl ToolbarItemView for ContextEditorToolbarItem {
3373 fn set_active_pane_item(
3374 &mut self,
3375 active_pane_item: Option<&dyn ItemHandle>,
3376 _window: &mut Window,
3377 cx: &mut Context<Self>,
3378 ) -> ToolbarItemLocation {
3379 self.active_context_editor = active_pane_item
3380 .and_then(|item| item.act_as::<ContextEditor>(cx))
3381 .map(|editor| editor.downgrade());
3382 cx.notify();
3383 if self.active_context_editor.is_none() {
3384 ToolbarItemLocation::Hidden
3385 } else {
3386 ToolbarItemLocation::PrimaryRight
3387 }
3388 }
3389
3390 fn pane_focus_update(
3391 &mut self,
3392 _pane_focused: bool,
3393 _window: &mut Window,
3394 cx: &mut Context<Self>,
3395 ) {
3396 cx.notify();
3397 }
3398}
3399
3400impl EventEmitter<ToolbarItemEvent> for ContextEditorToolbarItem {}
3401
3402pub enum ContextEditorToolbarItemEvent {
3403 RegenerateSummary,
3404}
3405impl EventEmitter<ContextEditorToolbarItemEvent> for ContextEditorToolbarItem {}
3406
3407enum PendingSlashCommand {}
3408
3409fn invoked_slash_command_fold_placeholder(
3410 command_id: InvokedSlashCommandId,
3411 context: WeakEntity<AssistantContext>,
3412) -> FoldPlaceholder {
3413 FoldPlaceholder {
3414 constrain_width: false,
3415 merge_adjacent: false,
3416 render: Arc::new(move |fold_id, _, cx| {
3417 let Some(context) = context.upgrade() else {
3418 return Empty.into_any();
3419 };
3420
3421 let Some(command) = context.read(cx).invoked_slash_command(&command_id) else {
3422 return Empty.into_any();
3423 };
3424
3425 h_flex()
3426 .id(fold_id)
3427 .px_1()
3428 .ml_6()
3429 .gap_2()
3430 .bg(cx.theme().colors().surface_background)
3431 .rounded_md()
3432 .child(Label::new(format!("/{}", command.name.clone())))
3433 .map(|parent| match &command.status {
3434 InvokedSlashCommandStatus::Running(_) => {
3435 parent.child(Icon::new(IconName::ArrowCircle).with_animation(
3436 "arrow-circle",
3437 Animation::new(Duration::from_secs(4)).repeat(),
3438 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
3439 ))
3440 }
3441 InvokedSlashCommandStatus::Error(message) => parent.child(
3442 Label::new(format!("error: {message}"))
3443 .single_line()
3444 .color(Color::Error),
3445 ),
3446 InvokedSlashCommandStatus::Finished => parent,
3447 })
3448 .into_any_element()
3449 }),
3450 type_tag: Some(TypeId::of::<PendingSlashCommand>()),
3451 }
3452}
3453
3454enum TokenState {
3455 NoTokensLeft {
3456 max_token_count: usize,
3457 token_count: usize,
3458 },
3459 HasMoreTokens {
3460 max_token_count: usize,
3461 token_count: usize,
3462 over_warn_threshold: bool,
3463 },
3464}
3465
3466fn token_state(context: &Entity<AssistantContext>, cx: &App) -> Option<TokenState> {
3467 const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
3468
3469 let model = LanguageModelRegistry::read_global(cx).active_model()?;
3470 let token_count = context.read(cx).token_count()?;
3471 let max_token_count = model.max_token_count();
3472
3473 let remaining_tokens = max_token_count as isize - token_count as isize;
3474 let token_state = if remaining_tokens <= 0 {
3475 TokenState::NoTokensLeft {
3476 max_token_count,
3477 token_count,
3478 }
3479 } else {
3480 let over_warn_threshold =
3481 token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
3482 TokenState::HasMoreTokens {
3483 max_token_count,
3484 token_count,
3485 over_warn_threshold,
3486 }
3487 };
3488 Some(token_state)
3489}
3490
3491fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
3492 let image_size = data
3493 .size(0)
3494 .map(|dimension| Pixels::from(u32::from(dimension)));
3495 let image_ratio = image_size.width / image_size.height;
3496 let bounds_ratio = max_size.width / max_size.height;
3497
3498 if image_size.width > max_size.width || image_size.height > max_size.height {
3499 if bounds_ratio > image_ratio {
3500 size(
3501 image_size.width * (max_size.height / image_size.height),
3502 max_size.height,
3503 )
3504 } else {
3505 size(
3506 max_size.width,
3507 image_size.height * (max_size.width / image_size.width),
3508 )
3509 }
3510 } else {
3511 size(image_size.width, image_size.height)
3512 }
3513}
3514
3515pub enum ConfigurationError {
3516 NoProvider,
3517 ProviderNotAuthenticated,
3518 ProviderPendingTermsAcceptance(Arc<dyn LanguageModelProvider>),
3519}
3520
3521fn configuration_error(cx: &App) -> Option<ConfigurationError> {
3522 let provider = LanguageModelRegistry::read_global(cx).active_provider();
3523 let is_authenticated = provider
3524 .as_ref()
3525 .map_or(false, |provider| provider.is_authenticated(cx));
3526
3527 if provider.is_some() && is_authenticated {
3528 return None;
3529 }
3530
3531 if provider.is_none() {
3532 return Some(ConfigurationError::NoProvider);
3533 }
3534
3535 if !is_authenticated {
3536 return Some(ConfigurationError::ProviderNotAuthenticated);
3537 }
3538
3539 None
3540}
3541
3542pub fn humanize_token_count(count: usize) -> String {
3543 match count {
3544 0..=999 => count.to_string(),
3545 1000..=9999 => {
3546 let thousands = count / 1000;
3547 let hundreds = (count % 1000 + 50) / 100;
3548 if hundreds == 0 {
3549 format!("{}k", thousands)
3550 } else if hundreds == 10 {
3551 format!("{}k", thousands + 1)
3552 } else {
3553 format!("{}.{}k", thousands, hundreds)
3554 }
3555 }
3556 _ => format!("{}k", (count + 500) / 1000),
3557 }
3558}
3559
3560pub fn make_lsp_adapter_delegate(
3561 project: &Entity<Project>,
3562 cx: &mut App,
3563) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
3564 project.update(cx, |project, cx| {
3565 // TODO: Find the right worktree.
3566 let Some(worktree) = project.worktrees(cx).next() else {
3567 return Ok(None::<Arc<dyn LspAdapterDelegate>>);
3568 };
3569 let http_client = project.client().http_client().clone();
3570 project.lsp_store().update(cx, |_, cx| {
3571 Ok(Some(LocalLspAdapterDelegate::new(
3572 project.languages().clone(),
3573 project.environment(),
3574 cx.weak_entity(),
3575 &worktree,
3576 http_client,
3577 project.fs().clone(),
3578 cx,
3579 ) as Arc<dyn LspAdapterDelegate>))
3580 })
3581 })
3582}
3583
3584#[cfg(test)]
3585mod tests {
3586 use super::*;
3587 use gpui::App;
3588 use language::Buffer;
3589 use unindent::Unindent;
3590
3591 #[gpui::test]
3592 fn test_find_code_blocks(cx: &mut App) {
3593 let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
3594
3595 let buffer = cx.new(|cx| {
3596 let text = r#"
3597 line 0
3598 line 1
3599 ```rust
3600 fn main() {}
3601 ```
3602 line 5
3603 line 6
3604 line 7
3605 ```go
3606 func main() {}
3607 ```
3608 line 11
3609 ```
3610 this is plain text code block
3611 ```
3612
3613 ```go
3614 func another() {}
3615 ```
3616 line 19
3617 "#
3618 .unindent();
3619 let mut buffer = Buffer::local(text, cx);
3620 buffer.set_language(Some(markdown.clone()), cx);
3621 buffer
3622 });
3623 let snapshot = buffer.read(cx).snapshot();
3624
3625 let code_blocks = vec![
3626 Point::new(3, 0)..Point::new(4, 0),
3627 Point::new(9, 0)..Point::new(10, 0),
3628 Point::new(13, 0)..Point::new(14, 0),
3629 Point::new(17, 0)..Point::new(18, 0),
3630 ]
3631 .into_iter()
3632 .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
3633 .collect::<Vec<_>>();
3634
3635 let expected_results = vec![
3636 (0, None),
3637 (1, None),
3638 (2, Some(code_blocks[0].clone())),
3639 (3, Some(code_blocks[0].clone())),
3640 (4, Some(code_blocks[0].clone())),
3641 (5, None),
3642 (6, None),
3643 (7, None),
3644 (8, Some(code_blocks[1].clone())),
3645 (9, Some(code_blocks[1].clone())),
3646 (10, Some(code_blocks[1].clone())),
3647 (11, None),
3648 (12, Some(code_blocks[2].clone())),
3649 (13, Some(code_blocks[2].clone())),
3650 (14, Some(code_blocks[2].clone())),
3651 (15, None),
3652 (16, Some(code_blocks[3].clone())),
3653 (17, Some(code_blocks[3].clone())),
3654 (18, Some(code_blocks[3].clone())),
3655 (19, None),
3656 ];
3657
3658 for (row, expected) in expected_results {
3659 let offset = snapshot.point_to_offset(Point::new(row, 0));
3660 let range = find_surrounding_code_block(&snapshot, offset);
3661 assert_eq!(range, expected, "unexpected result on row {:?}", row);
3662 }
3663 }
3664}