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