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