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