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