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