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