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.read_with(&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(&mut cx, |this, _| {
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.read_with(&cx, |this, _| this.workspace.clone())?
1125 .update_in(&mut cx, |workspace, window, cx| {
1126 workspace.add_item_to_active_pane(Box::new(editor.clone()), None, false, window, cx)
1127 })
1128 .log_err();
1129
1130 Ok(())
1131 }
1132
1133 async fn update_patch_editor(
1134 this: WeakEntity<Self>,
1135 patch: AssistantPatch,
1136 mut cx: AsyncWindowContext,
1137 ) -> Result<()> {
1138 let project = this.update(&mut cx, |this, _| this.project.clone())?;
1139 let resolved_patch = patch.resolve(project.clone(), &mut cx).await;
1140 this.update_in(&mut cx, |this, window, cx| {
1141 let patch_state = this.patches.get_mut(&patch.range)?;
1142
1143 let locations = resolved_patch
1144 .edit_groups
1145 .iter()
1146 .map(|(buffer, groups)| ProposedChangeLocation {
1147 buffer: buffer.clone(),
1148 ranges: groups
1149 .iter()
1150 .map(|group| group.context_range.clone())
1151 .collect(),
1152 })
1153 .collect();
1154
1155 if let Some(state) = &mut patch_state.editor {
1156 if let Some(editor) = state.editor.upgrade() {
1157 editor.update(cx, |editor, cx| {
1158 editor.set_title(patch.title.clone(), cx);
1159 editor.reset_locations(locations, window, cx);
1160 resolved_patch.apply(editor, cx);
1161 });
1162
1163 state.opened_patch = patch;
1164 } else {
1165 patch_state.editor.take();
1166 }
1167 }
1168 patch_state.update_task.take();
1169
1170 Some(())
1171 })?;
1172 Ok(())
1173 }
1174
1175 fn handle_editor_search_event(
1176 &mut self,
1177 _: &Entity<Editor>,
1178 event: &SearchEvent,
1179 _window: &mut Window,
1180 cx: &mut Context<Self>,
1181 ) {
1182 cx.emit(event.clone());
1183 }
1184
1185 fn cursor_scroll_position(
1186 &self,
1187 window: &mut Window,
1188 cx: &mut Context<Self>,
1189 ) -> Option<ScrollPosition> {
1190 self.editor.update(cx, |editor, cx| {
1191 let snapshot = editor.snapshot(window, cx);
1192 let cursor = editor.selections.newest_anchor().head();
1193 let cursor_row = cursor
1194 .to_display_point(&snapshot.display_snapshot)
1195 .row()
1196 .as_f32();
1197 let scroll_position = editor
1198 .scroll_manager
1199 .anchor()
1200 .scroll_position(&snapshot.display_snapshot);
1201
1202 let scroll_bottom = scroll_position.y + editor.visible_line_count().unwrap_or(0.);
1203 if (scroll_position.y..scroll_bottom).contains(&cursor_row) {
1204 Some(ScrollPosition {
1205 cursor,
1206 offset_before_cursor: point(scroll_position.x, cursor_row - scroll_position.y),
1207 })
1208 } else {
1209 None
1210 }
1211 })
1212 }
1213
1214 fn esc_kbd(cx: &App) -> Div {
1215 let colors = cx.theme().colors().clone();
1216
1217 h_flex()
1218 .items_center()
1219 .gap_1()
1220 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
1221 .text_size(TextSize::XSmall.rems(cx))
1222 .text_color(colors.text_muted)
1223 .child("Press")
1224 .child(
1225 h_flex()
1226 .rounded_md()
1227 .px_1()
1228 .mr_0p5()
1229 .border_1()
1230 .border_color(colors.border_variant.alpha(0.6))
1231 .bg(colors.element_background.alpha(0.6))
1232 .child("esc"),
1233 )
1234 .child("to cancel")
1235 }
1236
1237 fn update_message_headers(&mut self, cx: &mut Context<Self>) {
1238 self.editor.update(cx, |editor, cx| {
1239 let buffer = editor.buffer().read(cx).snapshot(cx);
1240
1241 let excerpt_id = *buffer.as_singleton().unwrap().0;
1242 let mut old_blocks = std::mem::take(&mut self.blocks);
1243 let mut blocks_to_remove: HashMap<_, _> = old_blocks
1244 .iter()
1245 .map(|(message_id, (_, block_id))| (*message_id, *block_id))
1246 .collect();
1247 let mut blocks_to_replace: HashMap<_, RenderBlock> = Default::default();
1248
1249 let render_block = |message: MessageMetadata| -> RenderBlock {
1250 Arc::new({
1251 let context = self.context.clone();
1252
1253 move |cx| {
1254 let message_id = MessageId(message.timestamp);
1255 let llm_loading = message.role == Role::Assistant
1256 && message.status == MessageStatus::Pending;
1257
1258 let (label, spinner, note) = match message.role {
1259 Role::User => (
1260 Label::new("You").color(Color::Default).into_any_element(),
1261 None,
1262 None,
1263 ),
1264 Role::Assistant => {
1265 let base_label = Label::new("Assistant").color(Color::Info);
1266 let mut spinner = None;
1267 let mut note = None;
1268 let animated_label = if llm_loading {
1269 base_label
1270 .with_animation(
1271 "pulsating-label",
1272 Animation::new(Duration::from_secs(2))
1273 .repeat()
1274 .with_easing(pulsating_between(0.4, 0.8)),
1275 |label, delta| label.alpha(delta),
1276 )
1277 .into_any_element()
1278 } else {
1279 base_label.into_any_element()
1280 };
1281 if llm_loading {
1282 spinner = Some(
1283 Icon::new(IconName::ArrowCircle)
1284 .size(IconSize::XSmall)
1285 .color(Color::Info)
1286 .with_animation(
1287 "arrow-circle",
1288 Animation::new(Duration::from_secs(2)).repeat(),
1289 |icon, delta| {
1290 icon.transform(Transformation::rotate(
1291 percentage(delta),
1292 ))
1293 },
1294 )
1295 .into_any_element(),
1296 );
1297 note = Some(Self::esc_kbd(cx).into_any_element());
1298 }
1299 (animated_label, spinner, note)
1300 }
1301 Role::System => (
1302 Label::new("System")
1303 .color(Color::Warning)
1304 .into_any_element(),
1305 None,
1306 None,
1307 ),
1308 };
1309
1310 let sender = h_flex()
1311 .items_center()
1312 .gap_2p5()
1313 .child(
1314 ButtonLike::new("role")
1315 .style(ButtonStyle::Filled)
1316 .child(
1317 h_flex()
1318 .items_center()
1319 .gap_1p5()
1320 .child(label)
1321 .children(spinner),
1322 )
1323 .tooltip(|window, cx| {
1324 Tooltip::with_meta(
1325 "Toggle message role",
1326 None,
1327 "Available roles: You (User), Assistant, System",
1328 window,
1329 cx,
1330 )
1331 })
1332 .on_click({
1333 let context = context.clone();
1334 move |_, _window, cx| {
1335 context.update(cx, |context, cx| {
1336 context.cycle_message_roles(
1337 HashSet::from_iter(Some(message_id)),
1338 cx,
1339 )
1340 })
1341 }
1342 }),
1343 )
1344 .children(note);
1345
1346 h_flex()
1347 .id(("message_header", message_id.as_u64()))
1348 .pl(cx.gutter_dimensions.full_width())
1349 .h_11()
1350 .w_full()
1351 .relative()
1352 .gap_1p5()
1353 .child(sender)
1354 .children(match &message.cache {
1355 Some(cache) if cache.is_final_anchor => match cache.status {
1356 CacheStatus::Cached => Some(
1357 div()
1358 .id("cached")
1359 .child(
1360 Icon::new(IconName::DatabaseZap)
1361 .size(IconSize::XSmall)
1362 .color(Color::Hint),
1363 )
1364 .tooltip(|window, cx| {
1365 Tooltip::with_meta(
1366 "Context Cached",
1367 None,
1368 "Large messages cached to optimize performance",
1369 window,
1370 cx,
1371 )
1372 })
1373 .into_any_element(),
1374 ),
1375 CacheStatus::Pending => Some(
1376 div()
1377 .child(
1378 Icon::new(IconName::Ellipsis)
1379 .size(IconSize::XSmall)
1380 .color(Color::Hint),
1381 )
1382 .into_any_element(),
1383 ),
1384 },
1385 _ => None,
1386 })
1387 .children(match &message.status {
1388 MessageStatus::Error(error) => Some(
1389 Button::new("show-error", "Error")
1390 .color(Color::Error)
1391 .selected_label_color(Color::Error)
1392 .selected_icon_color(Color::Error)
1393 .icon(IconName::XCircle)
1394 .icon_color(Color::Error)
1395 .icon_size(IconSize::XSmall)
1396 .icon_position(IconPosition::Start)
1397 .tooltip(Tooltip::text("View Details"))
1398 .on_click({
1399 let context = context.clone();
1400 let error = error.clone();
1401 move |_, _window, cx| {
1402 context.update(cx, |_, cx| {
1403 cx.emit(ContextEvent::ShowAssistError(
1404 error.clone(),
1405 ));
1406 });
1407 }
1408 })
1409 .into_any_element(),
1410 ),
1411 MessageStatus::Canceled => Some(
1412 h_flex()
1413 .gap_1()
1414 .items_center()
1415 .child(
1416 Icon::new(IconName::XCircle)
1417 .color(Color::Disabled)
1418 .size(IconSize::XSmall),
1419 )
1420 .child(
1421 Label::new("Canceled")
1422 .size(LabelSize::Small)
1423 .color(Color::Disabled),
1424 )
1425 .into_any_element(),
1426 ),
1427 _ => None,
1428 })
1429 .into_any_element()
1430 }
1431 })
1432 };
1433 let create_block_properties = |message: &Message| BlockProperties {
1434 height: 2,
1435 style: BlockStyle::Sticky,
1436 placement: BlockPlacement::Above(
1437 buffer
1438 .anchor_in_excerpt(excerpt_id, message.anchor_range.start)
1439 .unwrap(),
1440 ),
1441 priority: usize::MAX,
1442 render: render_block(MessageMetadata::from(message)),
1443 };
1444 let mut new_blocks = vec![];
1445 let mut block_index_to_message = vec![];
1446 for message in self.context.read(cx).messages(cx) {
1447 if let Some(_) = blocks_to_remove.remove(&message.id) {
1448 // This is an old message that we might modify.
1449 let Some((meta, block_id)) = old_blocks.get_mut(&message.id) else {
1450 debug_assert!(
1451 false,
1452 "old_blocks should contain a message_id we've just removed."
1453 );
1454 continue;
1455 };
1456 // Should we modify it?
1457 let message_meta = MessageMetadata::from(&message);
1458 if meta != &message_meta {
1459 blocks_to_replace.insert(*block_id, render_block(message_meta.clone()));
1460 *meta = message_meta;
1461 }
1462 } else {
1463 // This is a new message.
1464 new_blocks.push(create_block_properties(&message));
1465 block_index_to_message.push((message.id, MessageMetadata::from(&message)));
1466 }
1467 }
1468 editor.replace_blocks(blocks_to_replace, None, cx);
1469 editor.remove_blocks(blocks_to_remove.into_values().collect(), None, cx);
1470
1471 let ids = editor.insert_blocks(new_blocks, None, cx);
1472 old_blocks.extend(ids.into_iter().zip(block_index_to_message).map(
1473 |(block_id, (message_id, message_meta))| (message_id, (message_meta, block_id)),
1474 ));
1475 self.blocks = old_blocks;
1476 });
1477 }
1478
1479 /// Returns either the selected text, or the content of the Markdown code
1480 /// block surrounding the cursor.
1481 fn get_selection_or_code_block(
1482 context_editor_view: &Entity<ContextEditor>,
1483 cx: &mut Context<Workspace>,
1484 ) -> Option<(String, bool)> {
1485 const CODE_FENCE_DELIMITER: &'static str = "```";
1486
1487 let context_editor = context_editor_view.read(cx).editor.clone();
1488 context_editor.update(cx, |context_editor, cx| {
1489 if context_editor.selections.newest::<Point>(cx).is_empty() {
1490 let snapshot = context_editor.buffer().read(cx).snapshot(cx);
1491 let (_, _, snapshot) = snapshot.as_singleton()?;
1492
1493 let head = context_editor.selections.newest::<Point>(cx).head();
1494 let offset = snapshot.point_to_offset(head);
1495
1496 let surrounding_code_block_range = find_surrounding_code_block(snapshot, offset)?;
1497 let mut text = snapshot
1498 .text_for_range(surrounding_code_block_range)
1499 .collect::<String>();
1500
1501 // If there is no newline trailing the closing three-backticks, then
1502 // tree-sitter-md extends the range of the content node to include
1503 // the backticks.
1504 if text.ends_with(CODE_FENCE_DELIMITER) {
1505 text.drain((text.len() - CODE_FENCE_DELIMITER.len())..);
1506 }
1507
1508 (!text.is_empty()).then_some((text, true))
1509 } else {
1510 let selection = context_editor.selections.newest_adjusted(cx);
1511 let buffer = context_editor.buffer().read(cx).snapshot(cx);
1512 let selected_text = buffer.text_for_range(selection.range()).collect::<String>();
1513
1514 (!selected_text.is_empty()).then_some((selected_text, false))
1515 }
1516 })
1517 }
1518
1519 pub fn insert_selection(
1520 workspace: &mut Workspace,
1521 _: &InsertIntoEditor,
1522 window: &mut Window,
1523 cx: &mut Context<Workspace>,
1524 ) {
1525 let Some(assistant_panel_delegate) = <dyn AssistantPanelDelegate>::try_global(cx) else {
1526 return;
1527 };
1528 let Some(context_editor_view) =
1529 assistant_panel_delegate.active_context_editor(workspace, window, cx)
1530 else {
1531 return;
1532 };
1533 let Some(active_editor_view) = workspace
1534 .active_item(cx)
1535 .and_then(|item| item.act_as::<Editor>(cx))
1536 else {
1537 return;
1538 };
1539
1540 if let Some((text, _)) = Self::get_selection_or_code_block(&context_editor_view, cx) {
1541 active_editor_view.update(cx, |editor, cx| {
1542 editor.insert(&text, window, cx);
1543 editor.focus_handle(cx).focus(window);
1544 })
1545 }
1546 }
1547
1548 pub fn copy_code(
1549 workspace: &mut Workspace,
1550 _: &CopyCode,
1551 window: &mut Window,
1552 cx: &mut Context<Workspace>,
1553 ) {
1554 let result = maybe!({
1555 let assistant_panel_delegate = <dyn AssistantPanelDelegate>::try_global(cx)?;
1556 let context_editor_view =
1557 assistant_panel_delegate.active_context_editor(workspace, window, cx)?;
1558 Self::get_selection_or_code_block(&context_editor_view, cx)
1559 });
1560 let Some((text, is_code_block)) = result else {
1561 return;
1562 };
1563
1564 cx.write_to_clipboard(ClipboardItem::new_string(text));
1565
1566 struct CopyToClipboardToast;
1567 workspace.show_toast(
1568 Toast::new(
1569 NotificationId::unique::<CopyToClipboardToast>(),
1570 format!(
1571 "{} copied to clipboard.",
1572 if is_code_block {
1573 "Code block"
1574 } else {
1575 "Selection"
1576 }
1577 ),
1578 )
1579 .autohide(),
1580 cx,
1581 );
1582 }
1583
1584 pub fn insert_dragged_files(
1585 workspace: &mut Workspace,
1586 action: &InsertDraggedFiles,
1587 window: &mut Window,
1588 cx: &mut Context<Workspace>,
1589 ) {
1590 let Some(assistant_panel_delegate) = <dyn AssistantPanelDelegate>::try_global(cx) else {
1591 return;
1592 };
1593 let Some(context_editor_view) =
1594 assistant_panel_delegate.active_context_editor(workspace, window, cx)
1595 else {
1596 return;
1597 };
1598
1599 let project = workspace.project().clone();
1600
1601 let paths = match action {
1602 InsertDraggedFiles::ProjectPaths(paths) => Task::ready((paths.clone(), vec![])),
1603 InsertDraggedFiles::ExternalFiles(paths) => {
1604 let tasks = paths
1605 .clone()
1606 .into_iter()
1607 .map(|path| Workspace::project_path_for_path(project.clone(), &path, false, cx))
1608 .collect::<Vec<_>>();
1609
1610 cx.spawn(move |_, cx| async move {
1611 let mut paths = vec![];
1612 let mut worktrees = vec![];
1613
1614 let opened_paths = futures::future::join_all(tasks).await;
1615 for (worktree, project_path) in opened_paths.into_iter().flatten() {
1616 let Ok(worktree_root_name) =
1617 worktree.read_with(&cx, |worktree, _| worktree.root_name().to_string())
1618 else {
1619 continue;
1620 };
1621
1622 let mut full_path = PathBuf::from(worktree_root_name.clone());
1623 full_path.push(&project_path.path);
1624 paths.push(full_path);
1625 worktrees.push(worktree);
1626 }
1627
1628 (paths, worktrees)
1629 })
1630 }
1631 };
1632
1633 window
1634 .spawn(cx, |mut cx| async move {
1635 let (paths, dragged_file_worktrees) = paths.await;
1636 let cmd_name = FileSlashCommand.name();
1637
1638 context_editor_view
1639 .update_in(&mut cx, |context_editor, window, cx| {
1640 let file_argument = paths
1641 .into_iter()
1642 .map(|path| path.to_string_lossy().to_string())
1643 .collect::<Vec<_>>()
1644 .join(" ");
1645
1646 context_editor.editor.update(cx, |editor, cx| {
1647 editor.insert("\n", window, cx);
1648 editor.insert(&format!("/{} {}", cmd_name, file_argument), window, cx);
1649 });
1650
1651 context_editor.confirm_command(&ConfirmCommand, window, cx);
1652
1653 context_editor
1654 .dragged_file_worktrees
1655 .extend(dragged_file_worktrees);
1656 })
1657 .log_err();
1658 })
1659 .detach();
1660 }
1661
1662 pub fn quote_selection(
1663 workspace: &mut Workspace,
1664 _: &QuoteSelection,
1665 window: &mut Window,
1666 cx: &mut Context<Workspace>,
1667 ) {
1668 let Some(assistant_panel_delegate) = <dyn AssistantPanelDelegate>::try_global(cx) else {
1669 return;
1670 };
1671
1672 let Some(creases) = selections_creases(workspace, cx) else {
1673 return;
1674 };
1675
1676 if creases.is_empty() {
1677 return;
1678 }
1679
1680 assistant_panel_delegate.quote_selection(workspace, creases, window, cx);
1681 }
1682
1683 pub fn quote_creases(
1684 &mut self,
1685 creases: Vec<(String, String)>,
1686 window: &mut Window,
1687 cx: &mut Context<Self>,
1688 ) {
1689 self.editor.update(cx, |editor, cx| {
1690 editor.insert("\n", window, cx);
1691 for (text, crease_title) in creases {
1692 let point = editor.selections.newest::<Point>(cx).head();
1693 let start_row = MultiBufferRow(point.row);
1694
1695 editor.insert(&text, window, cx);
1696
1697 let snapshot = editor.buffer().read(cx).snapshot(cx);
1698 let anchor_before = snapshot.anchor_after(point);
1699 let anchor_after = editor
1700 .selections
1701 .newest_anchor()
1702 .head()
1703 .bias_left(&snapshot);
1704
1705 editor.insert("\n", window, cx);
1706
1707 let fold_placeholder =
1708 quote_selection_fold_placeholder(crease_title, cx.entity().downgrade());
1709 let crease = Crease::inline(
1710 anchor_before..anchor_after,
1711 fold_placeholder,
1712 render_quote_selection_output_toggle,
1713 |_, _, _, _| Empty.into_any(),
1714 );
1715 editor.insert_creases(vec![crease], cx);
1716 editor.fold_at(
1717 &FoldAt {
1718 buffer_row: start_row,
1719 },
1720 window,
1721 cx,
1722 );
1723 }
1724 })
1725 }
1726
1727 fn copy(&mut self, _: &editor::actions::Copy, _window: &mut Window, cx: &mut Context<Self>) {
1728 if self.editor.read(cx).selections.count() == 1 {
1729 let (copied_text, metadata, _) = self.get_clipboard_contents(cx);
1730 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1731 copied_text,
1732 metadata,
1733 ));
1734 cx.stop_propagation();
1735 return;
1736 }
1737
1738 cx.propagate();
1739 }
1740
1741 fn cut(&mut self, _: &editor::actions::Cut, window: &mut Window, cx: &mut Context<Self>) {
1742 if self.editor.read(cx).selections.count() == 1 {
1743 let (copied_text, metadata, selections) = self.get_clipboard_contents(cx);
1744
1745 self.editor.update(cx, |editor, cx| {
1746 editor.transact(window, cx, |this, window, cx| {
1747 this.change_selections(Some(Autoscroll::fit()), window, cx, |s| {
1748 s.select(selections);
1749 });
1750 this.insert("", window, cx);
1751 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1752 copied_text,
1753 metadata,
1754 ));
1755 });
1756 });
1757
1758 cx.stop_propagation();
1759 return;
1760 }
1761
1762 cx.propagate();
1763 }
1764
1765 fn get_clipboard_contents(
1766 &mut self,
1767 cx: &mut Context<Self>,
1768 ) -> (String, CopyMetadata, Vec<text::Selection<usize>>) {
1769 let (selection, creases) = self.editor.update(cx, |editor, cx| {
1770 let mut selection = editor.selections.newest_adjusted(cx);
1771 let snapshot = editor.buffer().read(cx).snapshot(cx);
1772
1773 selection.goal = SelectionGoal::None;
1774
1775 let selection_start = snapshot.point_to_offset(selection.start);
1776
1777 (
1778 selection.map(|point| snapshot.point_to_offset(point)),
1779 editor.display_map.update(cx, |display_map, cx| {
1780 display_map
1781 .snapshot(cx)
1782 .crease_snapshot
1783 .creases_in_range(
1784 MultiBufferRow(selection.start.row)
1785 ..MultiBufferRow(selection.end.row + 1),
1786 &snapshot,
1787 )
1788 .filter_map(|crease| {
1789 if let Crease::Inline {
1790 range, metadata, ..
1791 } = &crease
1792 {
1793 let metadata = metadata.as_ref()?;
1794 let start = range
1795 .start
1796 .to_offset(&snapshot)
1797 .saturating_sub(selection_start);
1798 let end = range
1799 .end
1800 .to_offset(&snapshot)
1801 .saturating_sub(selection_start);
1802
1803 let range_relative_to_selection = start..end;
1804 if !range_relative_to_selection.is_empty() {
1805 return Some(SelectedCreaseMetadata {
1806 range_relative_to_selection,
1807 crease: metadata.clone(),
1808 });
1809 }
1810 }
1811 None
1812 })
1813 .collect::<Vec<_>>()
1814 }),
1815 )
1816 });
1817
1818 let context = self.context.read(cx);
1819
1820 let mut text = String::new();
1821 for message in context.messages(cx) {
1822 if message.offset_range.start >= selection.range().end {
1823 break;
1824 } else if message.offset_range.end >= selection.range().start {
1825 let range = cmp::max(message.offset_range.start, selection.range().start)
1826 ..cmp::min(message.offset_range.end, selection.range().end);
1827 if !range.is_empty() {
1828 for chunk in context.buffer().read(cx).text_for_range(range) {
1829 text.push_str(chunk);
1830 }
1831 if message.offset_range.end < selection.range().end {
1832 text.push('\n');
1833 }
1834 }
1835 }
1836 }
1837
1838 (text, CopyMetadata { creases }, vec![selection])
1839 }
1840
1841 fn paste(
1842 &mut self,
1843 action: &editor::actions::Paste,
1844 window: &mut Window,
1845 cx: &mut Context<Self>,
1846 ) {
1847 cx.stop_propagation();
1848
1849 let images = if let Some(item) = cx.read_from_clipboard() {
1850 item.into_entries()
1851 .filter_map(|entry| {
1852 if let ClipboardEntry::Image(image) = entry {
1853 Some(image)
1854 } else {
1855 None
1856 }
1857 })
1858 .collect()
1859 } else {
1860 Vec::new()
1861 };
1862
1863 let metadata = if let Some(item) = cx.read_from_clipboard() {
1864 item.entries().first().and_then(|entry| {
1865 if let ClipboardEntry::String(text) = entry {
1866 text.metadata_json::<CopyMetadata>()
1867 } else {
1868 None
1869 }
1870 })
1871 } else {
1872 None
1873 };
1874
1875 if images.is_empty() {
1876 self.editor.update(cx, |editor, cx| {
1877 let paste_position = editor.selections.newest::<usize>(cx).head();
1878 editor.paste(action, window, cx);
1879
1880 if let Some(metadata) = metadata {
1881 let buffer = editor.buffer().read(cx).snapshot(cx);
1882
1883 let mut buffer_rows_to_fold = BTreeSet::new();
1884 let weak_editor = cx.entity().downgrade();
1885 editor.insert_creases(
1886 metadata.creases.into_iter().map(|metadata| {
1887 let start = buffer.anchor_after(
1888 paste_position + metadata.range_relative_to_selection.start,
1889 );
1890 let end = buffer.anchor_before(
1891 paste_position + metadata.range_relative_to_selection.end,
1892 );
1893
1894 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1895 buffer_rows_to_fold.insert(buffer_row);
1896 Crease::inline(
1897 start..end,
1898 FoldPlaceholder {
1899 render: render_fold_icon_button(
1900 weak_editor.clone(),
1901 metadata.crease.icon,
1902 metadata.crease.label.clone(),
1903 ),
1904 ..Default::default()
1905 },
1906 render_slash_command_output_toggle,
1907 |_, _, _, _| Empty.into_any(),
1908 )
1909 .with_metadata(metadata.crease.clone())
1910 }),
1911 cx,
1912 );
1913 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1914 editor.fold_at(&FoldAt { buffer_row }, window, cx);
1915 }
1916 }
1917 });
1918 } else {
1919 let mut image_positions = Vec::new();
1920 self.editor.update(cx, |editor, cx| {
1921 editor.transact(window, cx, |editor, _window, cx| {
1922 let edits = editor
1923 .selections
1924 .all::<usize>(cx)
1925 .into_iter()
1926 .map(|selection| (selection.start..selection.end, "\n"));
1927 editor.edit(edits, cx);
1928
1929 let snapshot = editor.buffer().read(cx).snapshot(cx);
1930 for selection in editor.selections.all::<usize>(cx) {
1931 image_positions.push(snapshot.anchor_before(selection.end));
1932 }
1933 });
1934 });
1935
1936 self.context.update(cx, |context, cx| {
1937 for image in images {
1938 let Some(render_image) = image.to_image_data(cx.svg_renderer()).log_err()
1939 else {
1940 continue;
1941 };
1942 let image_id = image.id();
1943 let image_task = LanguageModelImage::from_image(image, cx).shared();
1944
1945 for image_position in image_positions.iter() {
1946 context.insert_content(
1947 Content::Image {
1948 anchor: image_position.text_anchor,
1949 image_id,
1950 image: image_task.clone(),
1951 render_image: render_image.clone(),
1952 },
1953 cx,
1954 );
1955 }
1956 }
1957 });
1958 }
1959 }
1960
1961 fn update_image_blocks(&mut self, cx: &mut Context<Self>) {
1962 self.editor.update(cx, |editor, cx| {
1963 let buffer = editor.buffer().read(cx).snapshot(cx);
1964 let excerpt_id = *buffer.as_singleton().unwrap().0;
1965 let old_blocks = std::mem::take(&mut self.image_blocks);
1966 let new_blocks = self
1967 .context
1968 .read(cx)
1969 .contents(cx)
1970 .map(
1971 |Content::Image {
1972 anchor,
1973 render_image,
1974 ..
1975 }| (anchor, render_image),
1976 )
1977 .filter_map(|(anchor, render_image)| {
1978 const MAX_HEIGHT_IN_LINES: u32 = 8;
1979 let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
1980 let image = render_image.clone();
1981 anchor.is_valid(&buffer).then(|| BlockProperties {
1982 placement: BlockPlacement::Above(anchor),
1983 height: MAX_HEIGHT_IN_LINES,
1984 style: BlockStyle::Sticky,
1985 render: Arc::new(move |cx| {
1986 let image_size = size_for_image(
1987 &image,
1988 size(
1989 cx.max_width - cx.gutter_dimensions.full_width(),
1990 MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
1991 ),
1992 );
1993 h_flex()
1994 .pl(cx.gutter_dimensions.full_width())
1995 .child(
1996 img(image.clone())
1997 .object_fit(gpui::ObjectFit::ScaleDown)
1998 .w(image_size.width)
1999 .h(image_size.height),
2000 )
2001 .into_any_element()
2002 }),
2003 priority: 0,
2004 })
2005 })
2006 .collect::<Vec<_>>();
2007
2008 editor.remove_blocks(old_blocks, None, cx);
2009 let ids = editor.insert_blocks(new_blocks, None, cx);
2010 self.image_blocks = HashSet::from_iter(ids);
2011 });
2012 }
2013
2014 fn split(&mut self, _: &Split, _window: &mut Window, cx: &mut Context<Self>) {
2015 self.context.update(cx, |context, cx| {
2016 let selections = self.editor.read(cx).selections.disjoint_anchors();
2017 for selection in selections.as_ref() {
2018 let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
2019 let range = selection
2020 .map(|endpoint| endpoint.to_offset(&buffer))
2021 .range();
2022 context.split_message(range, cx);
2023 }
2024 });
2025 }
2026
2027 fn toggle_model_selector(
2028 &mut self,
2029 _: &ToggleModelSelector,
2030 window: &mut Window,
2031 cx: &mut Context<Self>,
2032 ) {
2033 self.language_model_selector_menu_handle.toggle(window, cx);
2034 }
2035
2036 fn save(&mut self, _: &Save, _window: &mut Window, cx: &mut Context<Self>) {
2037 self.context.update(cx, |context, cx| {
2038 context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
2039 });
2040 }
2041
2042 pub fn title(&self, cx: &App) -> Cow<str> {
2043 self.context
2044 .read(cx)
2045 .summary()
2046 .map(|summary| summary.text.clone())
2047 .map(Cow::Owned)
2048 .unwrap_or_else(|| Cow::Borrowed(DEFAULT_TAB_TITLE))
2049 }
2050
2051 #[allow(clippy::too_many_arguments)]
2052 fn render_patch_block(
2053 &mut self,
2054 range: Range<text::Anchor>,
2055 max_width: Pixels,
2056 gutter_width: Pixels,
2057 id: BlockId,
2058 selected: bool,
2059 window: &mut Window,
2060 cx: &mut Context<Self>,
2061 ) -> Option<AnyElement> {
2062 let snapshot = self
2063 .editor
2064 .update(cx, |editor, cx| editor.snapshot(window, cx));
2065 let (excerpt_id, _buffer_id, _) = snapshot.buffer_snapshot.as_singleton().unwrap();
2066 let excerpt_id = *excerpt_id;
2067 let anchor = snapshot
2068 .buffer_snapshot
2069 .anchor_in_excerpt(excerpt_id, range.start)
2070 .unwrap();
2071
2072 let theme = cx.theme().clone();
2073 let patch = self.context.read(cx).patch_for_range(&range, cx)?;
2074 let paths = patch
2075 .paths()
2076 .map(|p| SharedString::from(p.to_string()))
2077 .collect::<BTreeSet<_>>();
2078
2079 Some(
2080 v_flex()
2081 .id(id)
2082 .bg(theme.colors().editor_background)
2083 .ml(gutter_width)
2084 .pb_1()
2085 .w(max_width - gutter_width)
2086 .rounded_md()
2087 .border_1()
2088 .border_color(theme.colors().border_variant)
2089 .overflow_hidden()
2090 .hover(|style| style.border_color(theme.colors().text_accent))
2091 .when(selected, |this| {
2092 this.border_color(theme.colors().text_accent)
2093 })
2094 .cursor(CursorStyle::PointingHand)
2095 .on_click(cx.listener(move |this, _, window, cx| {
2096 this.editor.update(cx, |editor, cx| {
2097 editor.change_selections(None, window, cx, |selections| {
2098 selections.select_ranges(vec![anchor..anchor]);
2099 });
2100 });
2101 this.focus_active_patch(window, cx);
2102 }))
2103 .child(
2104 div()
2105 .px_2()
2106 .py_1()
2107 .overflow_hidden()
2108 .text_ellipsis()
2109 .border_b_1()
2110 .border_color(theme.colors().border_variant)
2111 .bg(theme.colors().element_background)
2112 .child(
2113 Label::new(patch.title.clone())
2114 .size(LabelSize::Small)
2115 .color(Color::Muted),
2116 ),
2117 )
2118 .children(paths.into_iter().map(|path| {
2119 h_flex()
2120 .px_2()
2121 .pt_1()
2122 .gap_1p5()
2123 .child(Icon::new(IconName::File).size(IconSize::Small))
2124 .child(Label::new(path).size(LabelSize::Small))
2125 }))
2126 .when(patch.status == AssistantPatchStatus::Pending, |div| {
2127 div.child(
2128 h_flex()
2129 .pt_1()
2130 .px_2()
2131 .gap_1()
2132 .child(
2133 Icon::new(IconName::ArrowCircle)
2134 .size(IconSize::XSmall)
2135 .color(Color::Muted)
2136 .with_animation(
2137 "arrow-circle",
2138 Animation::new(Duration::from_secs(2)).repeat(),
2139 |icon, delta| {
2140 icon.transform(Transformation::rotate(percentage(
2141 delta,
2142 )))
2143 },
2144 ),
2145 )
2146 .child(
2147 Label::new("Generating…")
2148 .color(Color::Muted)
2149 .size(LabelSize::Small)
2150 .with_animation(
2151 "pulsating-label",
2152 Animation::new(Duration::from_secs(2))
2153 .repeat()
2154 .with_easing(pulsating_between(0.4, 0.8)),
2155 |label, delta| label.alpha(delta),
2156 ),
2157 ),
2158 )
2159 })
2160 .into_any(),
2161 )
2162 }
2163
2164 fn render_notice(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2165 // This was previously gated behind the `zed-pro` feature flag. Since we
2166 // aren't planning to ship that right now, we're just hard-coding this
2167 // value to not show the nudge.
2168 let nudge = Some(false);
2169
2170 if nudge.map_or(false, |value| value) {
2171 Some(
2172 h_flex()
2173 .p_3()
2174 .border_b_1()
2175 .border_color(cx.theme().colors().border_variant)
2176 .bg(cx.theme().colors().editor_background)
2177 .justify_between()
2178 .child(
2179 h_flex()
2180 .gap_3()
2181 .child(Icon::new(IconName::ZedAssistant).color(Color::Accent))
2182 .child(Label::new("Zed AI is here! Get started by signing in →")),
2183 )
2184 .child(
2185 Button::new("sign-in", "Sign in")
2186 .size(ButtonSize::Compact)
2187 .style(ButtonStyle::Filled)
2188 .on_click(cx.listener(|this, _event, _window, cx| {
2189 let client = this
2190 .workspace
2191 .update(cx, |workspace, _| workspace.client().clone())
2192 .log_err();
2193
2194 if let Some(client) = client {
2195 cx.spawn(|this, mut cx| async move {
2196 client.authenticate_and_connect(true, &mut cx).await?;
2197 this.update(&mut cx, |_, cx| cx.notify())
2198 })
2199 .detach_and_log_err(cx)
2200 }
2201 })),
2202 )
2203 .into_any_element(),
2204 )
2205 } else if let Some(configuration_error) = configuration_error(cx) {
2206 let label = match configuration_error {
2207 ConfigurationError::NoProvider => "No LLM provider selected.",
2208 ConfigurationError::ProviderNotAuthenticated => "LLM provider is not configured.",
2209 ConfigurationError::ProviderPendingTermsAcceptance(_) => {
2210 "LLM provider requires accepting the Terms of Service."
2211 }
2212 };
2213 Some(
2214 h_flex()
2215 .px_3()
2216 .py_2()
2217 .border_b_1()
2218 .border_color(cx.theme().colors().border_variant)
2219 .bg(cx.theme().colors().editor_background)
2220 .justify_between()
2221 .child(
2222 h_flex()
2223 .gap_3()
2224 .child(
2225 Icon::new(IconName::Warning)
2226 .size(IconSize::Small)
2227 .color(Color::Warning),
2228 )
2229 .child(Label::new(label)),
2230 )
2231 .child(
2232 Button::new("open-configuration", "Configure Providers")
2233 .size(ButtonSize::Compact)
2234 .icon(Some(IconName::SlidersVertical))
2235 .icon_size(IconSize::Small)
2236 .icon_position(IconPosition::Start)
2237 .style(ButtonStyle::Filled)
2238 .on_click({
2239 let focus_handle = self.focus_handle(cx).clone();
2240 move |_event, window, cx| {
2241 focus_handle.dispatch_action(&ShowConfiguration, window, cx);
2242 }
2243 }),
2244 )
2245 .into_any_element(),
2246 )
2247 } else {
2248 None
2249 }
2250 }
2251
2252 fn render_send_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2253 let focus_handle = self.focus_handle(cx).clone();
2254
2255 let (style, tooltip) = match token_state(&self.context, cx) {
2256 Some(TokenState::NoTokensLeft { .. }) => (
2257 ButtonStyle::Tinted(TintColor::Error),
2258 Some(Tooltip::text("Token limit reached")(window, cx)),
2259 ),
2260 Some(TokenState::HasMoreTokens {
2261 over_warn_threshold,
2262 ..
2263 }) => {
2264 let (style, tooltip) = if over_warn_threshold {
2265 (
2266 ButtonStyle::Tinted(TintColor::Warning),
2267 Some(Tooltip::text("Token limit is close to exhaustion")(
2268 window, cx,
2269 )),
2270 )
2271 } else {
2272 (ButtonStyle::Filled, None)
2273 };
2274 (style, tooltip)
2275 }
2276 None => (ButtonStyle::Filled, None),
2277 };
2278
2279 let provider = LanguageModelRegistry::read_global(cx).active_provider();
2280
2281 let has_configuration_error = configuration_error(cx).is_some();
2282 let needs_to_accept_terms = self.show_accept_terms
2283 && provider
2284 .as_ref()
2285 .map_or(false, |provider| provider.must_accept_terms(cx));
2286 let disabled = has_configuration_error || needs_to_accept_terms;
2287
2288 ButtonLike::new("send_button")
2289 .disabled(disabled)
2290 .style(style)
2291 .when_some(tooltip, |button, tooltip| {
2292 button.tooltip(move |_, _| tooltip.clone())
2293 })
2294 .layer(ElevationIndex::ModalSurface)
2295 .child(Label::new(
2296 if AssistantSettings::get_global(cx).are_live_diffs_enabled(cx) {
2297 "Chat"
2298 } else {
2299 "Send"
2300 },
2301 ))
2302 .children(
2303 KeyBinding::for_action_in(&Assist, &focus_handle, window, cx)
2304 .map(|binding| binding.into_any_element()),
2305 )
2306 .on_click(move |_event, window, cx| {
2307 focus_handle.dispatch_action(&Assist, window, cx);
2308 })
2309 }
2310
2311 fn render_edit_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2312 let focus_handle = self.focus_handle(cx).clone();
2313
2314 let (style, tooltip) = match token_state(&self.context, cx) {
2315 Some(TokenState::NoTokensLeft { .. }) => (
2316 ButtonStyle::Tinted(TintColor::Error),
2317 Some(Tooltip::text("Token limit reached")(window, cx)),
2318 ),
2319 Some(TokenState::HasMoreTokens {
2320 over_warn_threshold,
2321 ..
2322 }) => {
2323 let (style, tooltip) = if over_warn_threshold {
2324 (
2325 ButtonStyle::Tinted(TintColor::Warning),
2326 Some(Tooltip::text("Token limit is close to exhaustion")(
2327 window, cx,
2328 )),
2329 )
2330 } else {
2331 (ButtonStyle::Filled, None)
2332 };
2333 (style, tooltip)
2334 }
2335 None => (ButtonStyle::Filled, None),
2336 };
2337
2338 let provider = LanguageModelRegistry::read_global(cx).active_provider();
2339
2340 let has_configuration_error = configuration_error(cx).is_some();
2341 let needs_to_accept_terms = self.show_accept_terms
2342 && provider
2343 .as_ref()
2344 .map_or(false, |provider| provider.must_accept_terms(cx));
2345 let disabled = has_configuration_error || needs_to_accept_terms;
2346
2347 ButtonLike::new("edit_button")
2348 .disabled(disabled)
2349 .style(style)
2350 .when_some(tooltip, |button, tooltip| {
2351 button.tooltip(move |_, _| tooltip.clone())
2352 })
2353 .layer(ElevationIndex::ModalSurface)
2354 .child(Label::new("Suggest Edits"))
2355 .children(
2356 KeyBinding::for_action_in(&Edit, &focus_handle, window, cx)
2357 .map(|binding| binding.into_any_element()),
2358 )
2359 .on_click(move |_event, window, cx| {
2360 focus_handle.dispatch_action(&Edit, window, cx);
2361 })
2362 }
2363
2364 fn render_inject_context_menu(&self, cx: &mut Context<Self>) -> impl IntoElement {
2365 slash_command_picker::SlashCommandSelector::new(
2366 self.slash_commands.clone(),
2367 cx.entity().downgrade(),
2368 IconButton::new("trigger", IconName::Plus)
2369 .icon_size(IconSize::Small)
2370 .icon_color(Color::Muted),
2371 move |window, cx| {
2372 Tooltip::with_meta(
2373 "Add Context",
2374 None,
2375 "Type / to insert via keyboard",
2376 window,
2377 cx,
2378 )
2379 },
2380 )
2381 }
2382
2383 fn render_language_model_selector(&self, cx: &mut Context<Self>) -> impl IntoElement {
2384 let active_model = LanguageModelRegistry::read_global(cx).active_model();
2385 let focus_handle = self.editor().focus_handle(cx).clone();
2386 let model_name = match active_model {
2387 Some(model) => model.name().0,
2388 None => SharedString::from("No model selected"),
2389 };
2390
2391 LanguageModelSelectorPopoverMenu::new(
2392 self.language_model_selector.clone(),
2393 ButtonLike::new("active-model")
2394 .style(ButtonStyle::Subtle)
2395 .child(
2396 h_flex()
2397 .gap_0p5()
2398 .child(
2399 Label::new(model_name)
2400 .size(LabelSize::Small)
2401 .color(Color::Muted),
2402 )
2403 .child(
2404 Icon::new(IconName::ChevronDown)
2405 .color(Color::Muted)
2406 .size(IconSize::XSmall),
2407 ),
2408 ),
2409 move |window, cx| {
2410 Tooltip::for_action_in(
2411 "Change Model",
2412 &ToggleModelSelector,
2413 &focus_handle,
2414 window,
2415 cx,
2416 )
2417 },
2418 gpui::Corner::BottomLeft,
2419 )
2420 .with_handle(self.language_model_selector_menu_handle.clone())
2421 }
2422
2423 fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2424 let last_error = self.last_error.as_ref()?;
2425
2426 Some(
2427 div()
2428 .absolute()
2429 .right_3()
2430 .bottom_12()
2431 .max_w_96()
2432 .py_2()
2433 .px_3()
2434 .elevation_2(cx)
2435 .occlude()
2436 .child(match last_error {
2437 AssistError::FileRequired => self.render_file_required_error(cx),
2438 AssistError::PaymentRequired => self.render_payment_required_error(cx),
2439 AssistError::MaxMonthlySpendReached => {
2440 self.render_max_monthly_spend_reached_error(cx)
2441 }
2442 AssistError::Message(error_message) => {
2443 self.render_assist_error(error_message, cx)
2444 }
2445 })
2446 .into_any(),
2447 )
2448 }
2449
2450 fn render_file_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2451 v_flex()
2452 .gap_0p5()
2453 .child(
2454 h_flex()
2455 .gap_1p5()
2456 .items_center()
2457 .child(Icon::new(IconName::Warning).color(Color::Warning))
2458 .child(
2459 Label::new("Suggest Edits needs a file to edit").weight(FontWeight::MEDIUM),
2460 ),
2461 )
2462 .child(
2463 div()
2464 .id("error-message")
2465 .max_h_24()
2466 .overflow_y_scroll()
2467 .child(Label::new(
2468 "To include files, type /file or /tab in your prompt.",
2469 )),
2470 )
2471 .child(
2472 h_flex()
2473 .justify_end()
2474 .mt_1()
2475 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2476 |this, _, _window, cx| {
2477 this.last_error = None;
2478 cx.notify();
2479 },
2480 ))),
2481 )
2482 .into_any()
2483 }
2484
2485 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2486 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.";
2487
2488 v_flex()
2489 .gap_0p5()
2490 .child(
2491 h_flex()
2492 .gap_1p5()
2493 .items_center()
2494 .child(Icon::new(IconName::XCircle).color(Color::Error))
2495 .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2496 )
2497 .child(
2498 div()
2499 .id("error-message")
2500 .max_h_24()
2501 .overflow_y_scroll()
2502 .child(Label::new(ERROR_MESSAGE)),
2503 )
2504 .child(
2505 h_flex()
2506 .justify_end()
2507 .mt_1()
2508 .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
2509 |this, _, _window, cx| {
2510 this.last_error = None;
2511 cx.open_url(&zed_urls::account_url(cx));
2512 cx.notify();
2513 },
2514 )))
2515 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2516 |this, _, _window, cx| {
2517 this.last_error = None;
2518 cx.notify();
2519 },
2520 ))),
2521 )
2522 .into_any()
2523 }
2524
2525 fn render_max_monthly_spend_reached_error(&self, cx: &mut Context<Self>) -> AnyElement {
2526 const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
2527
2528 v_flex()
2529 .gap_0p5()
2530 .child(
2531 h_flex()
2532 .gap_1p5()
2533 .items_center()
2534 .child(Icon::new(IconName::XCircle).color(Color::Error))
2535 .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
2536 )
2537 .child(
2538 div()
2539 .id("error-message")
2540 .max_h_24()
2541 .overflow_y_scroll()
2542 .child(Label::new(ERROR_MESSAGE)),
2543 )
2544 .child(
2545 h_flex()
2546 .justify_end()
2547 .mt_1()
2548 .child(
2549 Button::new("subscribe", "Update Monthly Spend Limit").on_click(
2550 cx.listener(|this, _, _window, cx| {
2551 this.last_error = None;
2552 cx.open_url(&zed_urls::account_url(cx));
2553 cx.notify();
2554 }),
2555 ),
2556 )
2557 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2558 |this, _, _window, cx| {
2559 this.last_error = None;
2560 cx.notify();
2561 },
2562 ))),
2563 )
2564 .into_any()
2565 }
2566
2567 fn render_assist_error(
2568 &self,
2569 error_message: &SharedString,
2570 cx: &mut Context<Self>,
2571 ) -> AnyElement {
2572 v_flex()
2573 .gap_0p5()
2574 .child(
2575 h_flex()
2576 .gap_1p5()
2577 .items_center()
2578 .child(Icon::new(IconName::XCircle).color(Color::Error))
2579 .child(
2580 Label::new("Error interacting with language model")
2581 .weight(FontWeight::MEDIUM),
2582 ),
2583 )
2584 .child(
2585 div()
2586 .id("error-message")
2587 .max_h_32()
2588 .overflow_y_scroll()
2589 .child(Label::new(error_message.clone())),
2590 )
2591 .child(
2592 h_flex()
2593 .justify_end()
2594 .mt_1()
2595 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2596 |this, _, _window, cx| {
2597 this.last_error = None;
2598 cx.notify();
2599 },
2600 ))),
2601 )
2602 .into_any()
2603 }
2604}
2605
2606/// Returns the contents of the *outermost* fenced code block that contains the given offset.
2607fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
2608 const CODE_BLOCK_NODE: &'static str = "fenced_code_block";
2609 const CODE_BLOCK_CONTENT: &'static str = "code_fence_content";
2610
2611 let layer = snapshot.syntax_layers().next()?;
2612
2613 let root_node = layer.node();
2614 let mut cursor = root_node.walk();
2615
2616 // Go to the first child for the given offset
2617 while cursor.goto_first_child_for_byte(offset).is_some() {
2618 // If we're at the end of the node, go to the next one.
2619 // Example: if you have a fenced-code-block, and you're on the start of the line
2620 // right after the closing ```, you want to skip the fenced-code-block and
2621 // go to the next sibling.
2622 if cursor.node().end_byte() == offset {
2623 cursor.goto_next_sibling();
2624 }
2625
2626 if cursor.node().start_byte() > offset {
2627 break;
2628 }
2629
2630 // We found the fenced code block.
2631 if cursor.node().kind() == CODE_BLOCK_NODE {
2632 // Now we need to find the child node that contains the code.
2633 cursor.goto_first_child();
2634 loop {
2635 if cursor.node().kind() == CODE_BLOCK_CONTENT {
2636 return Some(cursor.node().byte_range());
2637 }
2638 if !cursor.goto_next_sibling() {
2639 break;
2640 }
2641 }
2642 }
2643 }
2644
2645 None
2646}
2647
2648fn render_fold_icon_button(
2649 editor: WeakEntity<Editor>,
2650 icon: IconName,
2651 label: SharedString,
2652) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2653 Arc::new(move |fold_id, fold_range, _cx| {
2654 let editor = editor.clone();
2655 ButtonLike::new(fold_id)
2656 .style(ButtonStyle::Filled)
2657 .layer(ElevationIndex::ElevatedSurface)
2658 .child(Icon::new(icon))
2659 .child(Label::new(label.clone()).single_line())
2660 .on_click(move |_, window, cx| {
2661 editor
2662 .update(cx, |editor, cx| {
2663 let buffer_start = fold_range
2664 .start
2665 .to_point(&editor.buffer().read(cx).read(cx));
2666 let buffer_row = MultiBufferRow(buffer_start.row);
2667 editor.unfold_at(&UnfoldAt { buffer_row }, window, cx);
2668 })
2669 .ok();
2670 })
2671 .into_any_element()
2672 })
2673}
2674
2675type ToggleFold = Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>;
2676
2677fn render_slash_command_output_toggle(
2678 row: MultiBufferRow,
2679 is_folded: bool,
2680 fold: ToggleFold,
2681 _window: &mut Window,
2682 _cx: &mut App,
2683) -> AnyElement {
2684 Disclosure::new(
2685 ("slash-command-output-fold-indicator", row.0 as u64),
2686 !is_folded,
2687 )
2688 .toggle_state(is_folded)
2689 .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2690 .into_any_element()
2691}
2692
2693pub fn fold_toggle(
2694 name: &'static str,
2695) -> impl Fn(
2696 MultiBufferRow,
2697 bool,
2698 Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
2699 &mut Window,
2700 &mut App,
2701) -> AnyElement {
2702 move |row, is_folded, fold, _window, _cx| {
2703 Disclosure::new((name, row.0 as u64), !is_folded)
2704 .toggle_state(is_folded)
2705 .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2706 .into_any_element()
2707 }
2708}
2709
2710fn quote_selection_fold_placeholder(title: String, editor: WeakEntity<Editor>) -> FoldPlaceholder {
2711 FoldPlaceholder {
2712 render: Arc::new({
2713 move |fold_id, fold_range, _cx| {
2714 let editor = editor.clone();
2715 ButtonLike::new(fold_id)
2716 .style(ButtonStyle::Filled)
2717 .layer(ElevationIndex::ElevatedSurface)
2718 .child(Icon::new(IconName::TextSnippet))
2719 .child(Label::new(title.clone()).single_line())
2720 .on_click(move |_, window, cx| {
2721 editor
2722 .update(cx, |editor, cx| {
2723 let buffer_start = fold_range
2724 .start
2725 .to_point(&editor.buffer().read(cx).read(cx));
2726 let buffer_row = MultiBufferRow(buffer_start.row);
2727 editor.unfold_at(&UnfoldAt { buffer_row }, window, cx);
2728 })
2729 .ok();
2730 })
2731 .into_any_element()
2732 }
2733 }),
2734 merge_adjacent: false,
2735 ..Default::default()
2736 }
2737}
2738
2739fn render_quote_selection_output_toggle(
2740 row: MultiBufferRow,
2741 is_folded: bool,
2742 fold: ToggleFold,
2743 _window: &mut Window,
2744 _cx: &mut App,
2745) -> AnyElement {
2746 Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
2747 .toggle_state(is_folded)
2748 .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2749 .into_any_element()
2750}
2751
2752fn render_pending_slash_command_gutter_decoration(
2753 row: MultiBufferRow,
2754 status: &PendingSlashCommandStatus,
2755 confirm_command: Arc<dyn Fn(&mut Window, &mut App)>,
2756) -> AnyElement {
2757 let mut icon = IconButton::new(
2758 ("slash-command-gutter-decoration", row.0),
2759 ui::IconName::TriangleRight,
2760 )
2761 .on_click(move |_e, window, cx| confirm_command(window, cx))
2762 .icon_size(ui::IconSize::Small)
2763 .size(ui::ButtonSize::None);
2764
2765 match status {
2766 PendingSlashCommandStatus::Idle => {
2767 icon = icon.icon_color(Color::Muted);
2768 }
2769 PendingSlashCommandStatus::Running { .. } => {
2770 icon = icon.toggle_state(true);
2771 }
2772 PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
2773 }
2774
2775 icon.into_any_element()
2776}
2777
2778fn render_docs_slash_command_trailer(
2779 row: MultiBufferRow,
2780 command: ParsedSlashCommand,
2781 cx: &mut App,
2782) -> AnyElement {
2783 if command.arguments.is_empty() {
2784 return Empty.into_any();
2785 }
2786 let args = DocsSlashCommandArgs::parse(&command.arguments);
2787
2788 let Some(store) = args
2789 .provider()
2790 .and_then(|provider| IndexedDocsStore::try_global(provider, cx).ok())
2791 else {
2792 return Empty.into_any();
2793 };
2794
2795 let Some(package) = args.package() else {
2796 return Empty.into_any();
2797 };
2798
2799 let mut children = Vec::new();
2800
2801 if store.is_indexing(&package) {
2802 children.push(
2803 div()
2804 .id(("crates-being-indexed", row.0))
2805 .child(Icon::new(IconName::ArrowCircle).with_animation(
2806 "arrow-circle",
2807 Animation::new(Duration::from_secs(4)).repeat(),
2808 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2809 ))
2810 .tooltip({
2811 let package = package.clone();
2812 Tooltip::text(format!("Indexing {package}…"))
2813 })
2814 .into_any_element(),
2815 );
2816 }
2817
2818 if let Some(latest_error) = store.latest_error_for_package(&package) {
2819 children.push(
2820 div()
2821 .id(("latest-error", row.0))
2822 .child(
2823 Icon::new(IconName::Warning)
2824 .size(IconSize::Small)
2825 .color(Color::Warning),
2826 )
2827 .tooltip(Tooltip::text(format!("Failed to index: {latest_error}")))
2828 .into_any_element(),
2829 )
2830 }
2831
2832 let is_indexing = store.is_indexing(&package);
2833 let latest_error = store.latest_error_for_package(&package);
2834
2835 if !is_indexing && latest_error.is_none() {
2836 return Empty.into_any();
2837 }
2838
2839 h_flex().gap_2().children(children).into_any_element()
2840}
2841
2842#[derive(Debug, Clone, Serialize, Deserialize)]
2843struct CopyMetadata {
2844 creases: Vec<SelectedCreaseMetadata>,
2845}
2846
2847#[derive(Debug, Clone, Serialize, Deserialize)]
2848struct SelectedCreaseMetadata {
2849 range_relative_to_selection: Range<usize>,
2850 crease: CreaseMetadata,
2851}
2852
2853impl EventEmitter<EditorEvent> for ContextEditor {}
2854impl EventEmitter<SearchEvent> for ContextEditor {}
2855
2856impl Render for ContextEditor {
2857 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2858 let provider = LanguageModelRegistry::read_global(cx).active_provider();
2859 let accept_terms = if self.show_accept_terms {
2860 provider.as_ref().and_then(|provider| {
2861 provider.render_accept_terms(LanguageModelProviderTosView::PromptEditorPopup, cx)
2862 })
2863 } else {
2864 None
2865 };
2866
2867 v_flex()
2868 .key_context("ContextEditor")
2869 .capture_action(cx.listener(ContextEditor::cancel))
2870 .capture_action(cx.listener(ContextEditor::save))
2871 .capture_action(cx.listener(ContextEditor::copy))
2872 .capture_action(cx.listener(ContextEditor::cut))
2873 .capture_action(cx.listener(ContextEditor::paste))
2874 .capture_action(cx.listener(ContextEditor::cycle_message_role))
2875 .capture_action(cx.listener(ContextEditor::confirm_command))
2876 .on_action(cx.listener(ContextEditor::edit))
2877 .on_action(cx.listener(ContextEditor::assist))
2878 .on_action(cx.listener(ContextEditor::split))
2879 .on_action(cx.listener(ContextEditor::toggle_model_selector))
2880 .size_full()
2881 .children(self.render_notice(cx))
2882 .child(
2883 div()
2884 .flex_grow()
2885 .bg(cx.theme().colors().editor_background)
2886 .child(self.editor.clone()),
2887 )
2888 .when_some(accept_terms, |this, element| {
2889 this.child(
2890 div()
2891 .absolute()
2892 .right_3()
2893 .bottom_12()
2894 .max_w_96()
2895 .py_2()
2896 .px_3()
2897 .elevation_2(cx)
2898 .bg(cx.theme().colors().surface_background)
2899 .occlude()
2900 .child(element),
2901 )
2902 })
2903 .children(self.render_last_error(cx))
2904 .child(
2905 h_flex().w_full().relative().child(
2906 h_flex()
2907 .p_2()
2908 .w_full()
2909 .border_t_1()
2910 .border_color(cx.theme().colors().border_variant)
2911 .bg(cx.theme().colors().editor_background)
2912 .child(
2913 h_flex()
2914 .gap_1()
2915 .child(self.render_inject_context_menu(cx))
2916 .child(ui::Divider::vertical())
2917 .child(
2918 div()
2919 .pl_0p5()
2920 .child(self.render_language_model_selector(cx)),
2921 ),
2922 )
2923 .child(
2924 h_flex()
2925 .w_full()
2926 .justify_end()
2927 .when(
2928 AssistantSettings::get_global(cx).are_live_diffs_enabled(cx),
2929 |buttons| {
2930 buttons
2931 .items_center()
2932 .gap_1p5()
2933 .child(self.render_edit_button(window, cx))
2934 .child(
2935 Label::new("or")
2936 .size(LabelSize::Small)
2937 .color(Color::Muted),
2938 )
2939 },
2940 )
2941 .child(self.render_send_button(window, cx)),
2942 ),
2943 ),
2944 )
2945 }
2946}
2947
2948impl Focusable for ContextEditor {
2949 fn focus_handle(&self, cx: &App) -> FocusHandle {
2950 self.editor.focus_handle(cx)
2951 }
2952}
2953
2954impl Item for ContextEditor {
2955 type Event = editor::EditorEvent;
2956
2957 fn tab_content_text(&self, _window: &Window, cx: &App) -> Option<SharedString> {
2958 Some(util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into())
2959 }
2960
2961 fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
2962 match event {
2963 EditorEvent::Edited { .. } => {
2964 f(item::ItemEvent::Edit);
2965 }
2966 EditorEvent::TitleChanged => {
2967 f(item::ItemEvent::UpdateTab);
2968 }
2969 _ => {}
2970 }
2971 }
2972
2973 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
2974 Some(self.title(cx).to_string().into())
2975 }
2976
2977 fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
2978 Some(Box::new(handle.clone()))
2979 }
2980
2981 fn set_nav_history(
2982 &mut self,
2983 nav_history: pane::ItemNavHistory,
2984 window: &mut Window,
2985 cx: &mut Context<Self>,
2986 ) {
2987 self.editor.update(cx, |editor, cx| {
2988 Item::set_nav_history(editor, nav_history, window, cx)
2989 })
2990 }
2991
2992 fn navigate(
2993 &mut self,
2994 data: Box<dyn std::any::Any>,
2995 window: &mut Window,
2996 cx: &mut Context<Self>,
2997 ) -> bool {
2998 self.editor
2999 .update(cx, |editor, cx| Item::navigate(editor, data, window, cx))
3000 }
3001
3002 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3003 self.editor
3004 .update(cx, |editor, cx| Item::deactivated(editor, window, cx))
3005 }
3006
3007 fn act_as_type<'a>(
3008 &'a self,
3009 type_id: TypeId,
3010 self_handle: &'a Entity<Self>,
3011 _: &'a App,
3012 ) -> Option<AnyView> {
3013 if type_id == TypeId::of::<Self>() {
3014 Some(self_handle.to_any())
3015 } else if type_id == TypeId::of::<Editor>() {
3016 Some(self.editor.to_any())
3017 } else {
3018 None
3019 }
3020 }
3021
3022 fn include_in_nav_history() -> bool {
3023 false
3024 }
3025}
3026
3027impl SearchableItem for ContextEditor {
3028 type Match = <Editor as SearchableItem>::Match;
3029
3030 fn clear_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3031 self.editor.update(cx, |editor, cx| {
3032 editor.clear_matches(window, cx);
3033 });
3034 }
3035
3036 fn update_matches(
3037 &mut self,
3038 matches: &[Self::Match],
3039 window: &mut Window,
3040 cx: &mut Context<Self>,
3041 ) {
3042 self.editor
3043 .update(cx, |editor, cx| editor.update_matches(matches, window, cx));
3044 }
3045
3046 fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
3047 self.editor
3048 .update(cx, |editor, cx| editor.query_suggestion(window, cx))
3049 }
3050
3051 fn activate_match(
3052 &mut self,
3053 index: usize,
3054 matches: &[Self::Match],
3055 window: &mut Window,
3056 cx: &mut Context<Self>,
3057 ) {
3058 self.editor.update(cx, |editor, cx| {
3059 editor.activate_match(index, matches, window, cx);
3060 });
3061 }
3062
3063 fn select_matches(
3064 &mut self,
3065 matches: &[Self::Match],
3066 window: &mut Window,
3067 cx: &mut Context<Self>,
3068 ) {
3069 self.editor
3070 .update(cx, |editor, cx| editor.select_matches(matches, window, cx));
3071 }
3072
3073 fn replace(
3074 &mut self,
3075 identifier: &Self::Match,
3076 query: &project::search::SearchQuery,
3077 window: &mut Window,
3078 cx: &mut Context<Self>,
3079 ) {
3080 self.editor.update(cx, |editor, cx| {
3081 editor.replace(identifier, query, window, cx)
3082 });
3083 }
3084
3085 fn find_matches(
3086 &mut self,
3087 query: Arc<project::search::SearchQuery>,
3088 window: &mut Window,
3089 cx: &mut Context<Self>,
3090 ) -> Task<Vec<Self::Match>> {
3091 self.editor
3092 .update(cx, |editor, cx| editor.find_matches(query, window, cx))
3093 }
3094
3095 fn active_match_index(
3096 &mut self,
3097 matches: &[Self::Match],
3098 window: &mut Window,
3099 cx: &mut Context<Self>,
3100 ) -> Option<usize> {
3101 self.editor.update(cx, |editor, cx| {
3102 editor.active_match_index(matches, window, cx)
3103 })
3104 }
3105}
3106
3107impl FollowableItem for ContextEditor {
3108 fn remote_id(&self) -> Option<workspace::ViewId> {
3109 self.remote_id
3110 }
3111
3112 fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant> {
3113 let context = self.context.read(cx);
3114 Some(proto::view::Variant::ContextEditor(
3115 proto::view::ContextEditor {
3116 context_id: context.id().to_proto(),
3117 editor: if let Some(proto::view::Variant::Editor(proto)) =
3118 self.editor.read(cx).to_state_proto(window, cx)
3119 {
3120 Some(proto)
3121 } else {
3122 None
3123 },
3124 },
3125 ))
3126 }
3127
3128 fn from_state_proto(
3129 workspace: Entity<Workspace>,
3130 id: workspace::ViewId,
3131 state: &mut Option<proto::view::Variant>,
3132 window: &mut Window,
3133 cx: &mut App,
3134 ) -> Option<Task<Result<Entity<Self>>>> {
3135 let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
3136 return None;
3137 };
3138 let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
3139 unreachable!()
3140 };
3141
3142 let context_id = ContextId::from_proto(state.context_id);
3143 let editor_state = state.editor?;
3144
3145 let project = workspace.read(cx).project().clone();
3146 let assistant_panel_delegate = <dyn AssistantPanelDelegate>::try_global(cx)?;
3147
3148 let context_editor_task = workspace.update(cx, |workspace, cx| {
3149 assistant_panel_delegate.open_remote_context(workspace, context_id, window, cx)
3150 });
3151
3152 Some(window.spawn(cx, |mut cx| async move {
3153 let context_editor = context_editor_task.await?;
3154 context_editor
3155 .update_in(&mut cx, |context_editor, window, cx| {
3156 context_editor.remote_id = Some(id);
3157 context_editor.editor.update(cx, |editor, cx| {
3158 editor.apply_update_proto(
3159 &project,
3160 proto::update_view::Variant::Editor(proto::update_view::Editor {
3161 selections: editor_state.selections,
3162 pending_selection: editor_state.pending_selection,
3163 scroll_top_anchor: editor_state.scroll_top_anchor,
3164 scroll_x: editor_state.scroll_y,
3165 scroll_y: editor_state.scroll_y,
3166 ..Default::default()
3167 }),
3168 window,
3169 cx,
3170 )
3171 })
3172 })?
3173 .await?;
3174 Ok(context_editor)
3175 }))
3176 }
3177
3178 fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
3179 Editor::to_follow_event(event)
3180 }
3181
3182 fn add_event_to_update_proto(
3183 &self,
3184 event: &Self::Event,
3185 update: &mut Option<proto::update_view::Variant>,
3186 window: &Window,
3187 cx: &App,
3188 ) -> bool {
3189 self.editor
3190 .read(cx)
3191 .add_event_to_update_proto(event, update, window, cx)
3192 }
3193
3194 fn apply_update_proto(
3195 &mut self,
3196 project: &Entity<Project>,
3197 message: proto::update_view::Variant,
3198 window: &mut Window,
3199 cx: &mut Context<Self>,
3200 ) -> Task<Result<()>> {
3201 self.editor.update(cx, |editor, cx| {
3202 editor.apply_update_proto(project, message, window, cx)
3203 })
3204 }
3205
3206 fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
3207 true
3208 }
3209
3210 fn set_leader_peer_id(
3211 &mut self,
3212 leader_peer_id: Option<proto::PeerId>,
3213 window: &mut Window,
3214 cx: &mut Context<Self>,
3215 ) {
3216 self.editor.update(cx, |editor, cx| {
3217 editor.set_leader_peer_id(leader_peer_id, window, cx)
3218 })
3219 }
3220
3221 fn dedup(&self, existing: &Self, _window: &Window, cx: &App) -> Option<item::Dedup> {
3222 if existing.context.read(cx).id() == self.context.read(cx).id() {
3223 Some(item::Dedup::KeepExisting)
3224 } else {
3225 None
3226 }
3227 }
3228}
3229
3230pub struct ContextEditorToolbarItem {
3231 active_context_editor: Option<WeakEntity<ContextEditor>>,
3232 model_summary_editor: Entity<Editor>,
3233}
3234
3235impl ContextEditorToolbarItem {
3236 pub fn new(model_summary_editor: Entity<Editor>) -> Self {
3237 Self {
3238 active_context_editor: None,
3239 model_summary_editor,
3240 }
3241 }
3242}
3243
3244pub fn render_remaining_tokens(
3245 context_editor: &Entity<ContextEditor>,
3246 cx: &App,
3247) -> Option<impl IntoElement> {
3248 let context = &context_editor.read(cx).context;
3249
3250 let (token_count_color, token_count, max_token_count, tooltip) = match token_state(context, cx)?
3251 {
3252 TokenState::NoTokensLeft {
3253 max_token_count,
3254 token_count,
3255 } => (
3256 Color::Error,
3257 token_count,
3258 max_token_count,
3259 Some("Token Limit Reached"),
3260 ),
3261 TokenState::HasMoreTokens {
3262 max_token_count,
3263 token_count,
3264 over_warn_threshold,
3265 } => {
3266 let (color, tooltip) = if over_warn_threshold {
3267 (Color::Warning, Some("Token Limit is Close to Exhaustion"))
3268 } else {
3269 (Color::Muted, None)
3270 };
3271 (color, token_count, max_token_count, tooltip)
3272 }
3273 };
3274
3275 Some(
3276 h_flex()
3277 .id("token-count")
3278 .gap_0p5()
3279 .child(
3280 Label::new(humanize_token_count(token_count))
3281 .size(LabelSize::Small)
3282 .color(token_count_color),
3283 )
3284 .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
3285 .child(
3286 Label::new(humanize_token_count(max_token_count))
3287 .size(LabelSize::Small)
3288 .color(Color::Muted),
3289 )
3290 .when_some(tooltip, |element, tooltip| {
3291 element.tooltip(Tooltip::text(tooltip))
3292 }),
3293 )
3294}
3295
3296impl Render for ContextEditorToolbarItem {
3297 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3298 let left_side = h_flex()
3299 .group("chat-title-group")
3300 .gap_1()
3301 .items_center()
3302 .flex_grow()
3303 .child(
3304 div()
3305 .w_full()
3306 .when(self.active_context_editor.is_some(), |left_side| {
3307 left_side.child(self.model_summary_editor.clone())
3308 }),
3309 )
3310 .child(
3311 div().visible_on_hover("chat-title-group").child(
3312 IconButton::new("regenerate-context", IconName::RefreshTitle)
3313 .shape(ui::IconButtonShape::Square)
3314 .tooltip(Tooltip::text("Regenerate Title"))
3315 .on_click(cx.listener(move |_, _, _window, cx| {
3316 cx.emit(ContextEditorToolbarItemEvent::RegenerateSummary)
3317 })),
3318 ),
3319 );
3320
3321 let right_side = h_flex()
3322 .gap_2()
3323 // TODO display this in a nicer way, once we have a design for it.
3324 // .children({
3325 // let project = self
3326 // .workspace
3327 // .upgrade()
3328 // .map(|workspace| workspace.read(cx).project().downgrade());
3329 //
3330 // let scan_items_remaining = cx.update_global(|db: &mut SemanticDb, cx| {
3331 // project.and_then(|project| db.remaining_summaries(&project, cx))
3332 // });
3333 // scan_items_remaining
3334 // .map(|remaining_items| format!("Files to scan: {}", remaining_items))
3335 // })
3336 .children(
3337 self.active_context_editor
3338 .as_ref()
3339 .and_then(|editor| editor.upgrade())
3340 .and_then(|editor| render_remaining_tokens(&editor, cx)),
3341 );
3342
3343 h_flex()
3344 .px_0p5()
3345 .size_full()
3346 .gap_2()
3347 .justify_between()
3348 .child(left_side)
3349 .child(right_side)
3350 }
3351}
3352
3353impl ToolbarItemView for ContextEditorToolbarItem {
3354 fn set_active_pane_item(
3355 &mut self,
3356 active_pane_item: Option<&dyn ItemHandle>,
3357 _window: &mut Window,
3358 cx: &mut Context<Self>,
3359 ) -> ToolbarItemLocation {
3360 self.active_context_editor = active_pane_item
3361 .and_then(|item| item.act_as::<ContextEditor>(cx))
3362 .map(|editor| editor.downgrade());
3363 cx.notify();
3364 if self.active_context_editor.is_none() {
3365 ToolbarItemLocation::Hidden
3366 } else {
3367 ToolbarItemLocation::PrimaryRight
3368 }
3369 }
3370
3371 fn pane_focus_update(
3372 &mut self,
3373 _pane_focused: bool,
3374 _window: &mut Window,
3375 cx: &mut Context<Self>,
3376 ) {
3377 cx.notify();
3378 }
3379}
3380
3381impl EventEmitter<ToolbarItemEvent> for ContextEditorToolbarItem {}
3382
3383pub enum ContextEditorToolbarItemEvent {
3384 RegenerateSummary,
3385}
3386impl EventEmitter<ContextEditorToolbarItemEvent> for ContextEditorToolbarItem {}
3387
3388enum PendingSlashCommand {}
3389
3390fn invoked_slash_command_fold_placeholder(
3391 command_id: InvokedSlashCommandId,
3392 context: WeakEntity<AssistantContext>,
3393) -> FoldPlaceholder {
3394 FoldPlaceholder {
3395 constrain_width: false,
3396 merge_adjacent: false,
3397 render: Arc::new(move |fold_id, _, cx| {
3398 let Some(context) = context.upgrade() else {
3399 return Empty.into_any();
3400 };
3401
3402 let Some(command) = context.read(cx).invoked_slash_command(&command_id) else {
3403 return Empty.into_any();
3404 };
3405
3406 h_flex()
3407 .id(fold_id)
3408 .px_1()
3409 .ml_6()
3410 .gap_2()
3411 .bg(cx.theme().colors().surface_background)
3412 .rounded_md()
3413 .child(Label::new(format!("/{}", command.name.clone())))
3414 .map(|parent| match &command.status {
3415 InvokedSlashCommandStatus::Running(_) => {
3416 parent.child(Icon::new(IconName::ArrowCircle).with_animation(
3417 "arrow-circle",
3418 Animation::new(Duration::from_secs(4)).repeat(),
3419 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
3420 ))
3421 }
3422 InvokedSlashCommandStatus::Error(message) => parent.child(
3423 Label::new(format!("error: {message}"))
3424 .single_line()
3425 .color(Color::Error),
3426 ),
3427 InvokedSlashCommandStatus::Finished => parent,
3428 })
3429 .into_any_element()
3430 }),
3431 type_tag: Some(TypeId::of::<PendingSlashCommand>()),
3432 }
3433}
3434
3435enum TokenState {
3436 NoTokensLeft {
3437 max_token_count: usize,
3438 token_count: usize,
3439 },
3440 HasMoreTokens {
3441 max_token_count: usize,
3442 token_count: usize,
3443 over_warn_threshold: bool,
3444 },
3445}
3446
3447fn token_state(context: &Entity<AssistantContext>, cx: &App) -> Option<TokenState> {
3448 const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
3449
3450 let model = LanguageModelRegistry::read_global(cx).active_model()?;
3451 let token_count = context.read(cx).token_count()?;
3452 let max_token_count = model.max_token_count();
3453
3454 let remaining_tokens = max_token_count as isize - token_count as isize;
3455 let token_state = if remaining_tokens <= 0 {
3456 TokenState::NoTokensLeft {
3457 max_token_count,
3458 token_count,
3459 }
3460 } else {
3461 let over_warn_threshold =
3462 token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
3463 TokenState::HasMoreTokens {
3464 max_token_count,
3465 token_count,
3466 over_warn_threshold,
3467 }
3468 };
3469 Some(token_state)
3470}
3471
3472fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
3473 let image_size = data
3474 .size(0)
3475 .map(|dimension| Pixels::from(u32::from(dimension)));
3476 let image_ratio = image_size.width / image_size.height;
3477 let bounds_ratio = max_size.width / max_size.height;
3478
3479 if image_size.width > max_size.width || image_size.height > max_size.height {
3480 if bounds_ratio > image_ratio {
3481 size(
3482 image_size.width * (max_size.height / image_size.height),
3483 max_size.height,
3484 )
3485 } else {
3486 size(
3487 max_size.width,
3488 image_size.height * (max_size.width / image_size.width),
3489 )
3490 }
3491 } else {
3492 size(image_size.width, image_size.height)
3493 }
3494}
3495
3496pub enum ConfigurationError {
3497 NoProvider,
3498 ProviderNotAuthenticated,
3499 ProviderPendingTermsAcceptance(Arc<dyn LanguageModelProvider>),
3500}
3501
3502fn configuration_error(cx: &App) -> Option<ConfigurationError> {
3503 let provider = LanguageModelRegistry::read_global(cx).active_provider();
3504 let is_authenticated = provider
3505 .as_ref()
3506 .map_or(false, |provider| provider.is_authenticated(cx));
3507
3508 if provider.is_some() && is_authenticated {
3509 return None;
3510 }
3511
3512 if provider.is_none() {
3513 return Some(ConfigurationError::NoProvider);
3514 }
3515
3516 if !is_authenticated {
3517 return Some(ConfigurationError::ProviderNotAuthenticated);
3518 }
3519
3520 None
3521}
3522
3523pub fn humanize_token_count(count: usize) -> String {
3524 match count {
3525 0..=999 => count.to_string(),
3526 1000..=9999 => {
3527 let thousands = count / 1000;
3528 let hundreds = (count % 1000 + 50) / 100;
3529 if hundreds == 0 {
3530 format!("{}k", thousands)
3531 } else if hundreds == 10 {
3532 format!("{}k", thousands + 1)
3533 } else {
3534 format!("{}.{}k", thousands, hundreds)
3535 }
3536 }
3537 _ => format!("{}k", (count + 500) / 1000),
3538 }
3539}
3540
3541pub fn make_lsp_adapter_delegate(
3542 project: &Entity<Project>,
3543 cx: &mut App,
3544) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
3545 project.update(cx, |project, cx| {
3546 // TODO: Find the right worktree.
3547 let Some(worktree) = project.worktrees(cx).next() else {
3548 return Ok(None::<Arc<dyn LspAdapterDelegate>>);
3549 };
3550 let http_client = project.client().http_client().clone();
3551 project.lsp_store().update(cx, |_, cx| {
3552 Ok(Some(LocalLspAdapterDelegate::new(
3553 project.languages().clone(),
3554 project.environment(),
3555 cx.weak_entity(),
3556 &worktree,
3557 http_client,
3558 project.fs().clone(),
3559 cx,
3560 ) as Arc<dyn LspAdapterDelegate>))
3561 })
3562 })
3563}
3564
3565#[cfg(test)]
3566mod tests {
3567 use super::*;
3568 use gpui::App;
3569 use language::Buffer;
3570 use unindent::Unindent;
3571
3572 #[gpui::test]
3573 fn test_find_code_blocks(cx: &mut App) {
3574 let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
3575
3576 let buffer = cx.new(|cx| {
3577 let text = r#"
3578 line 0
3579 line 1
3580 ```rust
3581 fn main() {}
3582 ```
3583 line 5
3584 line 6
3585 line 7
3586 ```go
3587 func main() {}
3588 ```
3589 line 11
3590 ```
3591 this is plain text code block
3592 ```
3593
3594 ```go
3595 func another() {}
3596 ```
3597 line 19
3598 "#
3599 .unindent();
3600 let mut buffer = Buffer::local(text, cx);
3601 buffer.set_language(Some(markdown.clone()), cx);
3602 buffer
3603 });
3604 let snapshot = buffer.read(cx).snapshot();
3605
3606 let code_blocks = vec![
3607 Point::new(3, 0)..Point::new(4, 0),
3608 Point::new(9, 0)..Point::new(10, 0),
3609 Point::new(13, 0)..Point::new(14, 0),
3610 Point::new(17, 0)..Point::new(18, 0),
3611 ]
3612 .into_iter()
3613 .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
3614 .collect::<Vec<_>>();
3615
3616 let expected_results = vec![
3617 (0, None),
3618 (1, None),
3619 (2, Some(code_blocks[0].clone())),
3620 (3, Some(code_blocks[0].clone())),
3621 (4, Some(code_blocks[0].clone())),
3622 (5, None),
3623 (6, None),
3624 (7, None),
3625 (8, Some(code_blocks[1].clone())),
3626 (9, Some(code_blocks[1].clone())),
3627 (10, Some(code_blocks[1].clone())),
3628 (11, None),
3629 (12, Some(code_blocks[2].clone())),
3630 (13, Some(code_blocks[2].clone())),
3631 (14, Some(code_blocks[2].clone())),
3632 (15, None),
3633 (16, Some(code_blocks[3].clone())),
3634 (17, Some(code_blocks[3].clone())),
3635 (18, Some(code_blocks[3].clone())),
3636 (19, None),
3637 ];
3638
3639 for (row, expected) in expected_results {
3640 let offset = snapshot.point_to_offset(Point::new(row, 0));
3641 let range = find_surrounding_code_block(&snapshot, offset);
3642 assert_eq!(range, expected, "unexpected result on row {:?}", row);
3643 }
3644 }
3645}