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