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