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