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