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