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