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