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