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