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