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