1use crate::{
2 language_model_selector::{
3 LanguageModelSelector, ToggleModelSelector, language_model_selector,
4 },
5 max_mode_tooltip::MaxModeTooltip,
6};
7use agent_settings::{AgentSettings, CompletionMode};
8use anyhow::Result;
9use assistant_slash_command::{SlashCommand, SlashCommandOutputSection, SlashCommandWorkingSet};
10use assistant_slash_commands::{
11 DefaultSlashCommand, DocsSlashCommand, DocsSlashCommandArgs, FileSlashCommand,
12 selections_creases,
13};
14use client::{proto, zed_urls};
15use collections::{BTreeSet, HashMap, HashSet, hash_map};
16use editor::{
17 Anchor, Editor, EditorEvent, MenuInlineCompletionsPolicy, MultiBuffer, MultiBufferSnapshot,
18 RowExt, ToOffset as _, ToPoint,
19 actions::{MoveToEndOfLine, Newline, ShowCompletions},
20 display_map::{
21 BlockPlacement, BlockProperties, BlockStyle, Crease, CreaseMetadata, CustomBlockId, FoldId,
22 RenderBlock, ToDisplayPoint,
23 },
24 scroll::Autoscroll,
25};
26use editor::{FoldPlaceholder, display_map::CreaseId};
27use fs::Fs;
28use futures::FutureExt;
29use gpui::{
30 Animation, AnimationExt, AnyElement, AnyView, App, ClipboardEntry, ClipboardItem, Empty,
31 Entity, EventEmitter, FocusHandle, Focusable, FontWeight, Global, InteractiveElement,
32 IntoElement, ParentElement, Pixels, Render, RenderImage, SharedString, Size,
33 StatefulInteractiveElement, Styled, Subscription, Task, Transformation, WeakEntity, actions,
34 div, img, impl_internal_actions, percentage, point, prelude::*, pulsating_between, size,
35};
36use indexed_docs::IndexedDocsStore;
37use language::{
38 BufferSnapshot, LspAdapterDelegate, ToOffset,
39 language_settings::{SoftWrap, all_language_settings},
40};
41use language_model::{
42 LanguageModelImage, LanguageModelProvider, LanguageModelProviderTosView, LanguageModelRegistry,
43 Role,
44};
45use multi_buffer::MultiBufferRow;
46use picker::{Picker, popover_menu::PickerPopoverMenu};
47use project::{Project, Worktree};
48use project::{ProjectPath, lsp_store::LocalLspAdapterDelegate};
49use rope::Point;
50use serde::{Deserialize, Serialize};
51use settings::{Settings, SettingsStore, update_settings_file};
52use std::{
53 any::TypeId,
54 cmp,
55 ops::Range,
56 path::{Path, PathBuf},
57 rc::Rc,
58 sync::Arc,
59 time::Duration,
60};
61use text::SelectionGoal;
62use ui::{
63 ButtonLike, Disclosure, ElevationIndex, KeyBinding, PopoverMenuHandle, TintColor, Tooltip,
64 prelude::*,
65};
66use util::{ResultExt, maybe};
67use workspace::{
68 CollaboratorId,
69 searchable::{Direction, SearchableItemHandle},
70};
71use workspace::{
72 Save, Toast, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace,
73 item::{self, FollowableItem, Item, ItemHandle},
74 notifications::NotificationId,
75 pane,
76 searchable::{SearchEvent, SearchableItem},
77};
78
79use crate::{
80 AssistantContext, CacheStatus, Content, ContextEvent, ContextId, InvokedSlashCommandId,
81 InvokedSlashCommandStatus, Message, MessageId, MessageMetadata, MessageStatus,
82 ParsedSlashCommand, PendingSlashCommandStatus,
83};
84use crate::{
85 ThoughtProcessOutputSection, slash_command::SlashCommandCompletionProvider,
86 slash_command_picker,
87};
88
89actions!(
90 assistant,
91 [
92 Assist,
93 ConfirmCommand,
94 CopyCode,
95 CycleMessageRole,
96 InsertIntoEditor,
97 QuoteSelection,
98 Split,
99 ]
100);
101
102#[derive(PartialEq, Clone)]
103pub enum InsertDraggedFiles {
104 ProjectPaths(Vec<ProjectPath>),
105 ExternalFiles(Vec<PathBuf>),
106}
107
108impl_internal_actions!(assistant, [InsertDraggedFiles]);
109
110#[derive(Copy, Clone, Debug, PartialEq)]
111struct ScrollPosition {
112 offset_before_cursor: gpui::Point<f32>,
113 cursor: Anchor,
114}
115
116type MessageHeader = MessageMetadata;
117
118#[derive(Clone)]
119enum AssistError {
120 PaymentRequired,
121 Message(SharedString),
122}
123
124pub enum ThoughtProcessStatus {
125 Pending,
126 Completed,
127}
128
129pub trait AgentPanelDelegate {
130 fn active_context_editor(
131 &self,
132 workspace: &mut Workspace,
133 window: &mut Window,
134 cx: &mut Context<Workspace>,
135 ) -> Option<Entity<ContextEditor>>;
136
137 fn open_saved_context(
138 &self,
139 workspace: &mut Workspace,
140 path: Arc<Path>,
141 window: &mut Window,
142 cx: &mut Context<Workspace>,
143 ) -> Task<Result<()>>;
144
145 fn open_remote_context(
146 &self,
147 workspace: &mut Workspace,
148 context_id: ContextId,
149 window: &mut Window,
150 cx: &mut Context<Workspace>,
151 ) -> Task<Result<Entity<ContextEditor>>>;
152
153 fn quote_selection(
154 &self,
155 workspace: &mut Workspace,
156 selection_ranges: Vec<Range<Anchor>>,
157 buffer: Entity<MultiBuffer>,
158 window: &mut Window,
159 cx: &mut Context<Workspace>,
160 );
161}
162
163impl dyn AgentPanelDelegate {
164 /// Returns the global [`AssistantPanelDelegate`], if it exists.
165 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
166 cx.try_global::<GlobalAssistantPanelDelegate>()
167 .map(|global| global.0.clone())
168 }
169
170 /// Sets the global [`AssistantPanelDelegate`].
171 pub fn set_global(delegate: Arc<Self>, cx: &mut App) {
172 cx.set_global(GlobalAssistantPanelDelegate(delegate));
173 }
174}
175
176struct GlobalAssistantPanelDelegate(Arc<dyn AgentPanelDelegate>);
177
178impl Global for GlobalAssistantPanelDelegate {}
179
180pub struct ContextEditor {
181 context: Entity<AssistantContext>,
182 fs: Arc<dyn Fs>,
183 slash_commands: Arc<SlashCommandWorkingSet>,
184 workspace: WeakEntity<Workspace>,
185 project: Entity<Project>,
186 lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
187 editor: Entity<Editor>,
188 pending_thought_process: Option<(CreaseId, language::Anchor)>,
189 blocks: HashMap<MessageId, (MessageHeader, CustomBlockId)>,
190 image_blocks: HashSet<CustomBlockId>,
191 scroll_position: Option<ScrollPosition>,
192 remote_id: Option<workspace::ViewId>,
193 pending_slash_command_creases: HashMap<Range<language::Anchor>, CreaseId>,
194 invoked_slash_command_creases: HashMap<InvokedSlashCommandId, CreaseId>,
195 _subscriptions: Vec<Subscription>,
196 last_error: Option<AssistError>,
197 show_accept_terms: bool,
198 pub(crate) slash_menu_handle:
199 PopoverMenuHandle<Picker<slash_command_picker::SlashCommandDelegate>>,
200 // dragged_file_worktrees is used to keep references to worktrees that were added
201 // when the user drag/dropped an external file onto the context editor. Since
202 // the worktree is not part of the project panel, it would be dropped as soon as
203 // the file is opened. In order to keep the worktree alive for the duration of the
204 // context editor, we keep a reference here.
205 dragged_file_worktrees: Vec<Entity<Worktree>>,
206 language_model_selector: Entity<LanguageModelSelector>,
207 language_model_selector_menu_handle: PopoverMenuHandle<LanguageModelSelector>,
208}
209
210pub const DEFAULT_TAB_TITLE: &str = "New Chat";
211const MAX_TAB_TITLE_LEN: usize = 16;
212
213impl ContextEditor {
214 pub fn for_context(
215 context: Entity<AssistantContext>,
216 fs: Arc<dyn Fs>,
217 workspace: WeakEntity<Workspace>,
218 project: Entity<Project>,
219 lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
220 window: &mut Window,
221 cx: &mut Context<Self>,
222 ) -> Self {
223 let completion_provider = SlashCommandCompletionProvider::new(
224 context.read(cx).slash_commands().clone(),
225 Some(cx.entity().downgrade()),
226 Some(workspace.clone()),
227 );
228
229 let editor = cx.new(|cx| {
230 let mut editor =
231 Editor::for_buffer(context.read(cx).buffer().clone(), None, window, cx);
232 editor.disable_scrollbars_and_minimap(window, cx);
233 editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
234 editor.set_show_line_numbers(false, cx);
235 editor.set_show_git_diff_gutter(false, cx);
236 editor.set_show_code_actions(false, cx);
237 editor.set_show_runnables(false, cx);
238 editor.set_show_breakpoints(false, cx);
239 editor.set_show_wrap_guides(false, cx);
240 editor.set_show_indent_guides(false, cx);
241 editor.set_completion_provider(Some(Rc::new(completion_provider)));
242 editor.set_menu_inline_completions_policy(MenuInlineCompletionsPolicy::Never);
243 editor.set_collaboration_hub(Box::new(project.clone()));
244
245 let show_edit_predictions = all_language_settings(None, cx)
246 .edit_predictions
247 .enabled_in_text_threads;
248
249 editor.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
250
251 editor
252 });
253
254 let _subscriptions = vec![
255 cx.observe(&context, |_, _, cx| cx.notify()),
256 cx.subscribe_in(&context, window, Self::handle_context_event),
257 cx.subscribe_in(&editor, window, Self::handle_editor_event),
258 cx.subscribe_in(&editor, window, Self::handle_editor_search_event),
259 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
260 ];
261
262 let slash_command_sections = context.read(cx).slash_command_output_sections().to_vec();
263 let thought_process_sections = context.read(cx).thought_process_output_sections().to_vec();
264 let slash_commands = context.read(cx).slash_commands().clone();
265 let mut this = Self {
266 context,
267 slash_commands,
268 editor,
269 lsp_adapter_delegate,
270 blocks: Default::default(),
271 image_blocks: Default::default(),
272 scroll_position: None,
273 remote_id: None,
274 pending_thought_process: None,
275 fs: fs.clone(),
276 workspace,
277 project,
278 pending_slash_command_creases: HashMap::default(),
279 invoked_slash_command_creases: HashMap::default(),
280 _subscriptions,
281 last_error: None,
282 show_accept_terms: false,
283 slash_menu_handle: Default::default(),
284 dragged_file_worktrees: Vec::new(),
285 language_model_selector: cx.new(|cx| {
286 language_model_selector(
287 |cx| LanguageModelRegistry::read_global(cx).default_model(),
288 move |model, cx| {
289 update_settings_file::<AgentSettings>(
290 fs.clone(),
291 cx,
292 move |settings, _| settings.set_model(model.clone()),
293 );
294 },
295 window,
296 cx,
297 )
298 }),
299 language_model_selector_menu_handle: PopoverMenuHandle::default(),
300 };
301 this.update_message_headers(cx);
302 this.update_image_blocks(cx);
303 this.insert_slash_command_output_sections(slash_command_sections, false, window, cx);
304 this.insert_thought_process_output_sections(
305 thought_process_sections
306 .into_iter()
307 .map(|section| (section, ThoughtProcessStatus::Completed)),
308 window,
309 cx,
310 );
311 this
312 }
313
314 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
315 self.editor.update(cx, |editor, cx| {
316 let show_edit_predictions = all_language_settings(None, cx)
317 .edit_predictions
318 .enabled_in_text_threads;
319
320 editor.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
321 });
322 }
323
324 pub fn context(&self) -> &Entity<AssistantContext> {
325 &self.context
326 }
327
328 pub fn editor(&self) -> &Entity<Editor> {
329 &self.editor
330 }
331
332 pub fn insert_default_prompt(&mut self, window: &mut Window, cx: &mut Context<Self>) {
333 let command_name = DefaultSlashCommand.name();
334 self.editor.update(cx, |editor, cx| {
335 editor.insert(&format!("/{command_name}\n\n"), window, cx)
336 });
337 let command = self.context.update(cx, |context, cx| {
338 context.reparse(cx);
339 context.parsed_slash_commands()[0].clone()
340 });
341 self.run_command(
342 command.source_range,
343 &command.name,
344 &command.arguments,
345 false,
346 self.workspace.clone(),
347 window,
348 cx,
349 );
350 }
351
352 fn assist(&mut self, _: &Assist, window: &mut Window, cx: &mut Context<Self>) {
353 if self.sending_disabled(cx) {
354 return;
355 }
356 self.send_to_model(window, cx);
357 }
358
359 fn send_to_model(&mut self, window: &mut Window, cx: &mut Context<Self>) {
360 let provider = LanguageModelRegistry::read_global(cx)
361 .default_model()
362 .map(|default| default.provider);
363 if provider
364 .as_ref()
365 .map_or(false, |provider| provider.must_accept_terms(cx))
366 {
367 self.show_accept_terms = true;
368 cx.notify();
369 return;
370 }
371
372 self.last_error = None;
373
374 if let Some(user_message) = self.context.update(cx, |context, cx| context.assist(cx)) {
375 let new_selection = {
376 let cursor = user_message
377 .start
378 .to_offset(self.context.read(cx).buffer().read(cx));
379 cursor..cursor
380 };
381 self.editor.update(cx, |editor, cx| {
382 editor.change_selections(Some(Autoscroll::fit()), window, cx, |selections| {
383 selections.select_ranges([new_selection])
384 });
385 });
386 // Avoid scrolling to the new cursor position so the assistant's output is stable.
387 cx.defer_in(window, |this, _, _| this.scroll_position = None);
388 }
389
390 cx.notify();
391 }
392
393 fn cancel(
394 &mut self,
395 _: &editor::actions::Cancel,
396 _window: &mut Window,
397 cx: &mut Context<Self>,
398 ) {
399 self.last_error = None;
400
401 if self
402 .context
403 .update(cx, |context, cx| context.cancel_last_assist(cx))
404 {
405 return;
406 }
407
408 cx.propagate();
409 }
410
411 fn cycle_message_role(
412 &mut self,
413 _: &CycleMessageRole,
414 _window: &mut Window,
415 cx: &mut Context<Self>,
416 ) {
417 let cursors = self.cursors(cx);
418 self.context.update(cx, |context, cx| {
419 let messages = context
420 .messages_for_offsets(cursors, cx)
421 .into_iter()
422 .map(|message| message.id)
423 .collect();
424 context.cycle_message_roles(messages, cx)
425 });
426 }
427
428 fn cursors(&self, cx: &mut App) -> Vec<usize> {
429 let selections = self
430 .editor
431 .update(cx, |editor, cx| editor.selections.all::<usize>(cx));
432 selections
433 .into_iter()
434 .map(|selection| selection.head())
435 .collect()
436 }
437
438 pub fn insert_command(&mut self, name: &str, window: &mut Window, cx: &mut Context<Self>) {
439 if let Some(command) = self.slash_commands.command(name, cx) {
440 self.editor.update(cx, |editor, cx| {
441 editor.transact(window, cx, |editor, window, cx| {
442 editor
443 .change_selections(Some(Autoscroll::fit()), window, cx, |s| s.try_cancel());
444 let snapshot = editor.buffer().read(cx).snapshot(cx);
445 let newest_cursor = editor.selections.newest::<Point>(cx).head();
446 if newest_cursor.column > 0
447 || snapshot
448 .chars_at(newest_cursor)
449 .next()
450 .map_or(false, |ch| ch != '\n')
451 {
452 editor.move_to_end_of_line(
453 &MoveToEndOfLine {
454 stop_at_soft_wraps: false,
455 },
456 window,
457 cx,
458 );
459 editor.newline(&Newline, window, cx);
460 }
461
462 editor.insert(&format!("/{name}"), window, cx);
463 if command.accepts_arguments() {
464 editor.insert(" ", window, cx);
465 editor.show_completions(&ShowCompletions::default(), window, cx);
466 }
467 });
468 });
469 if !command.requires_argument() {
470 self.confirm_command(&ConfirmCommand, window, cx);
471 }
472 }
473 }
474
475 pub fn confirm_command(
476 &mut self,
477 _: &ConfirmCommand,
478 window: &mut Window,
479 cx: &mut Context<Self>,
480 ) {
481 if self.editor.read(cx).has_visible_completions_menu() {
482 return;
483 }
484
485 let selections = self.editor.read(cx).selections.disjoint_anchors();
486 let mut commands_by_range = HashMap::default();
487 let workspace = self.workspace.clone();
488 self.context.update(cx, |context, cx| {
489 context.reparse(cx);
490 for selection in selections.iter() {
491 if let Some(command) =
492 context.pending_command_for_position(selection.head().text_anchor, cx)
493 {
494 commands_by_range
495 .entry(command.source_range.clone())
496 .or_insert_with(|| command.clone());
497 }
498 }
499 });
500
501 if commands_by_range.is_empty() {
502 cx.propagate();
503 } else {
504 for command in commands_by_range.into_values() {
505 self.run_command(
506 command.source_range,
507 &command.name,
508 &command.arguments,
509 true,
510 workspace.clone(),
511 window,
512 cx,
513 );
514 }
515 cx.stop_propagation();
516 }
517 }
518
519 pub fn run_command(
520 &mut self,
521 command_range: Range<language::Anchor>,
522 name: &str,
523 arguments: &[String],
524 ensure_trailing_newline: bool,
525 workspace: WeakEntity<Workspace>,
526 window: &mut Window,
527 cx: &mut Context<Self>,
528 ) {
529 if let Some(command) = self.slash_commands.command(name, cx) {
530 let context = self.context.read(cx);
531 let sections = context
532 .slash_command_output_sections()
533 .into_iter()
534 .filter(|section| section.is_valid(context.buffer().read(cx)))
535 .cloned()
536 .collect::<Vec<_>>();
537 let snapshot = context.buffer().read(cx).snapshot();
538 let output = command.run(
539 arguments,
540 §ions,
541 snapshot,
542 workspace,
543 self.lsp_adapter_delegate.clone(),
544 window,
545 cx,
546 );
547 self.context.update(cx, |context, cx| {
548 context.insert_command_output(
549 command_range,
550 name,
551 output,
552 ensure_trailing_newline,
553 cx,
554 )
555 });
556 }
557 }
558
559 fn handle_context_event(
560 &mut self,
561 _: &Entity<AssistantContext>,
562 event: &ContextEvent,
563 window: &mut Window,
564 cx: &mut Context<Self>,
565 ) {
566 let context_editor = cx.entity().downgrade();
567
568 match event {
569 ContextEvent::MessagesEdited => {
570 self.update_message_headers(cx);
571 self.update_image_blocks(cx);
572 self.context.update(cx, |context, cx| {
573 context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
574 });
575 }
576 ContextEvent::SummaryChanged => {
577 cx.emit(EditorEvent::TitleChanged);
578 self.context.update(cx, |context, cx| {
579 context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
580 });
581 }
582 ContextEvent::SummaryGenerated => {}
583 ContextEvent::StartedThoughtProcess(range) => {
584 let creases = self.insert_thought_process_output_sections(
585 [(
586 ThoughtProcessOutputSection {
587 range: range.clone(),
588 },
589 ThoughtProcessStatus::Pending,
590 )],
591 window,
592 cx,
593 );
594 self.pending_thought_process = Some((creases[0], range.start));
595 }
596 ContextEvent::EndedThoughtProcess(end) => {
597 if let Some((crease_id, start)) = self.pending_thought_process.take() {
598 self.editor.update(cx, |editor, cx| {
599 let multi_buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
600 let (excerpt_id, _, _) = multi_buffer_snapshot.as_singleton().unwrap();
601 let start_anchor = multi_buffer_snapshot
602 .anchor_in_excerpt(*excerpt_id, start)
603 .unwrap();
604
605 editor.display_map.update(cx, |display_map, cx| {
606 display_map.unfold_intersecting(
607 vec![start_anchor..start_anchor],
608 true,
609 cx,
610 );
611 });
612 editor.remove_creases(vec![crease_id], cx);
613 });
614 self.insert_thought_process_output_sections(
615 [(
616 ThoughtProcessOutputSection { range: start..*end },
617 ThoughtProcessStatus::Completed,
618 )],
619 window,
620 cx,
621 );
622 }
623 }
624 ContextEvent::StreamedCompletion => {
625 self.editor.update(cx, |editor, cx| {
626 if let Some(scroll_position) = self.scroll_position {
627 let snapshot = editor.snapshot(window, cx);
628 let cursor_point = scroll_position.cursor.to_display_point(&snapshot);
629 let scroll_top =
630 cursor_point.row().as_f32() - scroll_position.offset_before_cursor.y;
631 editor.set_scroll_position(
632 point(scroll_position.offset_before_cursor.x, scroll_top),
633 window,
634 cx,
635 );
636 }
637 });
638 }
639 ContextEvent::ParsedSlashCommandsUpdated { removed, updated } => {
640 self.editor.update(cx, |editor, cx| {
641 let buffer = editor.buffer().read(cx).snapshot(cx);
642 let (&excerpt_id, _, _) = buffer.as_singleton().unwrap();
643
644 editor.remove_creases(
645 removed
646 .iter()
647 .filter_map(|range| self.pending_slash_command_creases.remove(range)),
648 cx,
649 );
650
651 let crease_ids = editor.insert_creases(
652 updated.iter().map(|command| {
653 let workspace = self.workspace.clone();
654 let confirm_command = Arc::new({
655 let context_editor = context_editor.clone();
656 let command = command.clone();
657 move |window: &mut Window, cx: &mut App| {
658 context_editor
659 .update(cx, |context_editor, cx| {
660 context_editor.run_command(
661 command.source_range.clone(),
662 &command.name,
663 &command.arguments,
664 false,
665 workspace.clone(),
666 window,
667 cx,
668 );
669 })
670 .ok();
671 }
672 });
673 let placeholder = FoldPlaceholder {
674 render: Arc::new(move |_, _, _| Empty.into_any()),
675 ..Default::default()
676 };
677 let render_toggle = {
678 let confirm_command = confirm_command.clone();
679 let command = command.clone();
680 move |row, _, _, _window: &mut Window, _cx: &mut App| {
681 render_pending_slash_command_gutter_decoration(
682 row,
683 &command.status,
684 confirm_command.clone(),
685 )
686 }
687 };
688 let render_trailer = {
689 let command = command.clone();
690 move |row, _unfold, _window: &mut Window, cx: &mut App| {
691 // TODO: In the future we should investigate how we can expose
692 // this as a hook on the `SlashCommand` trait so that we don't
693 // need to special-case it here.
694 if command.name == DocsSlashCommand::NAME {
695 return render_docs_slash_command_trailer(
696 row,
697 command.clone(),
698 cx,
699 );
700 }
701
702 Empty.into_any()
703 }
704 };
705
706 let start = buffer
707 .anchor_in_excerpt(excerpt_id, command.source_range.start)
708 .unwrap();
709 let end = buffer
710 .anchor_in_excerpt(excerpt_id, command.source_range.end)
711 .unwrap();
712 Crease::inline(start..end, placeholder, render_toggle, render_trailer)
713 }),
714 cx,
715 );
716
717 self.pending_slash_command_creases.extend(
718 updated
719 .iter()
720 .map(|command| command.source_range.clone())
721 .zip(crease_ids),
722 );
723 })
724 }
725 ContextEvent::InvokedSlashCommandChanged { command_id } => {
726 self.update_invoked_slash_command(*command_id, window, cx);
727 }
728 ContextEvent::SlashCommandOutputSectionAdded { section } => {
729 self.insert_slash_command_output_sections([section.clone()], false, window, cx);
730 }
731 ContextEvent::Operation(_) => {}
732 ContextEvent::ShowAssistError(error_message) => {
733 self.last_error = Some(AssistError::Message(error_message.clone()));
734 }
735 ContextEvent::ShowPaymentRequiredError => {
736 self.last_error = Some(AssistError::PaymentRequired);
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 (mut 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
1650 // If selection is empty, we want to copy the entire line
1651 if selection.range().is_empty() {
1652 let snapshot = context.buffer().read(cx).snapshot();
1653 let point = snapshot.offset_to_point(selection.range().start);
1654 selection.start = snapshot.point_to_offset(Point::new(point.row, 0));
1655 selection.end = snapshot
1656 .point_to_offset(cmp::min(Point::new(point.row + 1, 0), snapshot.max_point()));
1657 for chunk in context.buffer().read(cx).text_for_range(selection.range()) {
1658 text.push_str(chunk);
1659 }
1660 } else {
1661 for message in context.messages(cx) {
1662 if message.offset_range.start >= selection.range().end {
1663 break;
1664 } else if message.offset_range.end >= selection.range().start {
1665 let range = cmp::max(message.offset_range.start, selection.range().start)
1666 ..cmp::min(message.offset_range.end, selection.range().end);
1667 if !range.is_empty() {
1668 for chunk in context.buffer().read(cx).text_for_range(range) {
1669 text.push_str(chunk);
1670 }
1671 if message.offset_range.end < selection.range().end {
1672 text.push('\n');
1673 }
1674 }
1675 }
1676 }
1677 }
1678 (text, CopyMetadata { creases }, vec![selection])
1679 }
1680
1681 fn paste(
1682 &mut self,
1683 action: &editor::actions::Paste,
1684 window: &mut Window,
1685 cx: &mut Context<Self>,
1686 ) {
1687 cx.stop_propagation();
1688
1689 let images = if let Some(item) = cx.read_from_clipboard() {
1690 item.into_entries()
1691 .filter_map(|entry| {
1692 if let ClipboardEntry::Image(image) = entry {
1693 Some(image)
1694 } else {
1695 None
1696 }
1697 })
1698 .collect()
1699 } else {
1700 Vec::new()
1701 };
1702
1703 let metadata = if let Some(item) = cx.read_from_clipboard() {
1704 item.entries().first().and_then(|entry| {
1705 if let ClipboardEntry::String(text) = entry {
1706 text.metadata_json::<CopyMetadata>()
1707 } else {
1708 None
1709 }
1710 })
1711 } else {
1712 None
1713 };
1714
1715 if images.is_empty() {
1716 self.editor.update(cx, |editor, cx| {
1717 let paste_position = editor.selections.newest::<usize>(cx).head();
1718 editor.paste(action, window, cx);
1719
1720 if let Some(metadata) = metadata {
1721 let buffer = editor.buffer().read(cx).snapshot(cx);
1722
1723 let mut buffer_rows_to_fold = BTreeSet::new();
1724 let weak_editor = cx.entity().downgrade();
1725 editor.insert_creases(
1726 metadata.creases.into_iter().map(|metadata| {
1727 let start = buffer.anchor_after(
1728 paste_position + metadata.range_relative_to_selection.start,
1729 );
1730 let end = buffer.anchor_before(
1731 paste_position + metadata.range_relative_to_selection.end,
1732 );
1733
1734 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1735 buffer_rows_to_fold.insert(buffer_row);
1736 Crease::inline(
1737 start..end,
1738 FoldPlaceholder {
1739 render: render_fold_icon_button(
1740 weak_editor.clone(),
1741 metadata.crease.icon_path.clone(),
1742 metadata.crease.label.clone(),
1743 ),
1744 ..Default::default()
1745 },
1746 render_slash_command_output_toggle,
1747 |_, _, _, _| Empty.into_any(),
1748 )
1749 .with_metadata(metadata.crease.clone())
1750 }),
1751 cx,
1752 );
1753 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1754 editor.fold_at(buffer_row, window, cx);
1755 }
1756 }
1757 });
1758 } else {
1759 let mut image_positions = Vec::new();
1760 self.editor.update(cx, |editor, cx| {
1761 editor.transact(window, cx, |editor, _window, cx| {
1762 let edits = editor
1763 .selections
1764 .all::<usize>(cx)
1765 .into_iter()
1766 .map(|selection| (selection.start..selection.end, "\n"));
1767 editor.edit(edits, cx);
1768
1769 let snapshot = editor.buffer().read(cx).snapshot(cx);
1770 for selection in editor.selections.all::<usize>(cx) {
1771 image_positions.push(snapshot.anchor_before(selection.end));
1772 }
1773 });
1774 });
1775
1776 self.context.update(cx, |context, cx| {
1777 for image in images {
1778 let Some(render_image) = image.to_image_data(cx.svg_renderer()).log_err()
1779 else {
1780 continue;
1781 };
1782 let image_id = image.id();
1783 let image_task = LanguageModelImage::from_image(Arc::new(image), cx).shared();
1784
1785 for image_position in image_positions.iter() {
1786 context.insert_content(
1787 Content::Image {
1788 anchor: image_position.text_anchor,
1789 image_id,
1790 image: image_task.clone(),
1791 render_image: render_image.clone(),
1792 },
1793 cx,
1794 );
1795 }
1796 }
1797 });
1798 }
1799 }
1800
1801 fn update_image_blocks(&mut self, cx: &mut Context<Self>) {
1802 self.editor.update(cx, |editor, cx| {
1803 let buffer = editor.buffer().read(cx).snapshot(cx);
1804 let excerpt_id = *buffer.as_singleton().unwrap().0;
1805 let old_blocks = std::mem::take(&mut self.image_blocks);
1806 let new_blocks = self
1807 .context
1808 .read(cx)
1809 .contents(cx)
1810 .map(
1811 |Content::Image {
1812 anchor,
1813 render_image,
1814 ..
1815 }| (anchor, render_image),
1816 )
1817 .filter_map(|(anchor, render_image)| {
1818 const MAX_HEIGHT_IN_LINES: u32 = 8;
1819 let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
1820 let image = render_image.clone();
1821 anchor.is_valid(&buffer).then(|| BlockProperties {
1822 placement: BlockPlacement::Above(anchor),
1823 height: Some(MAX_HEIGHT_IN_LINES),
1824 style: BlockStyle::Sticky,
1825 render: Arc::new(move |cx| {
1826 let image_size = size_for_image(
1827 &image,
1828 size(
1829 cx.max_width - cx.margins.gutter.full_width(),
1830 MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
1831 ),
1832 );
1833 h_flex()
1834 .pl(cx.margins.gutter.full_width())
1835 .child(
1836 img(image.clone())
1837 .object_fit(gpui::ObjectFit::ScaleDown)
1838 .w(image_size.width)
1839 .h(image_size.height),
1840 )
1841 .into_any_element()
1842 }),
1843 priority: 0,
1844 render_in_minimap: false,
1845 })
1846 })
1847 .collect::<Vec<_>>();
1848
1849 editor.remove_blocks(old_blocks, None, cx);
1850 let ids = editor.insert_blocks(new_blocks, None, cx);
1851 self.image_blocks = HashSet::from_iter(ids);
1852 });
1853 }
1854
1855 fn split(&mut self, _: &Split, _window: &mut Window, cx: &mut Context<Self>) {
1856 self.context.update(cx, |context, cx| {
1857 let selections = self.editor.read(cx).selections.disjoint_anchors();
1858 for selection in selections.as_ref() {
1859 let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
1860 let range = selection
1861 .map(|endpoint| endpoint.to_offset(&buffer))
1862 .range();
1863 context.split_message(range, cx);
1864 }
1865 });
1866 }
1867
1868 fn save(&mut self, _: &Save, _window: &mut Window, cx: &mut Context<Self>) {
1869 self.context.update(cx, |context, cx| {
1870 context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
1871 });
1872 }
1873
1874 pub fn title(&self, cx: &App) -> SharedString {
1875 self.context.read(cx).summary().or_default()
1876 }
1877
1878 pub fn regenerate_summary(&mut self, cx: &mut Context<Self>) {
1879 self.context
1880 .update(cx, |context, cx| context.summarize(true, cx));
1881 }
1882
1883 fn render_notice(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
1884 // This was previously gated behind the `zed-pro` feature flag. Since we
1885 // aren't planning to ship that right now, we're just hard-coding this
1886 // value to not show the nudge.
1887 let nudge = Some(false);
1888
1889 if nudge.map_or(false, |value| value) {
1890 Some(
1891 h_flex()
1892 .p_3()
1893 .border_b_1()
1894 .border_color(cx.theme().colors().border_variant)
1895 .bg(cx.theme().colors().editor_background)
1896 .justify_between()
1897 .child(
1898 h_flex()
1899 .gap_3()
1900 .child(Icon::new(IconName::ZedAssistant).color(Color::Accent))
1901 .child(Label::new("Zed AI is here! Get started by signing in →")),
1902 )
1903 .child(
1904 Button::new("sign-in", "Sign in")
1905 .size(ButtonSize::Compact)
1906 .style(ButtonStyle::Filled)
1907 .on_click(cx.listener(|this, _event, _window, cx| {
1908 let client = this
1909 .workspace
1910 .read_with(cx, |workspace, _| workspace.client().clone())
1911 .log_err();
1912
1913 if let Some(client) = client {
1914 cx.spawn(async move |context_editor, cx| {
1915 match client.authenticate_and_connect(true, cx).await {
1916 util::ConnectionResult::Timeout => {
1917 log::error!("Authentication timeout")
1918 }
1919 util::ConnectionResult::ConnectionReset => {
1920 log::error!("Connection reset")
1921 }
1922 util::ConnectionResult::Result(r) => {
1923 if r.log_err().is_some() {
1924 context_editor
1925 .update(cx, |_, cx| cx.notify())
1926 .ok();
1927 }
1928 }
1929 }
1930 })
1931 .detach()
1932 }
1933 })),
1934 )
1935 .into_any_element(),
1936 )
1937 } else if let Some(configuration_error) = configuration_error(cx) {
1938 let label = match configuration_error {
1939 ConfigurationError::NoProvider => "No LLM provider selected.",
1940 ConfigurationError::ProviderNotAuthenticated => "LLM provider is not configured.",
1941 ConfigurationError::ProviderPendingTermsAcceptance(_) => {
1942 "LLM provider requires accepting the Terms of Service."
1943 }
1944 };
1945 Some(
1946 h_flex()
1947 .px_3()
1948 .py_2()
1949 .border_b_1()
1950 .border_color(cx.theme().colors().border_variant)
1951 .bg(cx.theme().colors().editor_background)
1952 .justify_between()
1953 .child(
1954 h_flex()
1955 .gap_3()
1956 .child(
1957 Icon::new(IconName::Warning)
1958 .size(IconSize::Small)
1959 .color(Color::Warning),
1960 )
1961 .child(Label::new(label)),
1962 )
1963 .child(
1964 Button::new("open-configuration", "Configure Providers")
1965 .size(ButtonSize::Compact)
1966 .icon(Some(IconName::SlidersVertical))
1967 .icon_size(IconSize::Small)
1968 .icon_position(IconPosition::Start)
1969 .style(ButtonStyle::Filled)
1970 .on_click({
1971 let focus_handle = self.focus_handle(cx).clone();
1972 move |_event, window, cx| {
1973 focus_handle.dispatch_action(
1974 &zed_actions::agent::OpenConfiguration,
1975 window,
1976 cx,
1977 );
1978 }
1979 }),
1980 )
1981 .into_any_element(),
1982 )
1983 } else {
1984 None
1985 }
1986 }
1987
1988 fn render_send_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1989 let focus_handle = self.focus_handle(cx).clone();
1990
1991 let (style, tooltip) = match token_state(&self.context, cx) {
1992 Some(TokenState::NoTokensLeft { .. }) => (
1993 ButtonStyle::Tinted(TintColor::Error),
1994 Some(Tooltip::text("Token limit reached")(window, cx)),
1995 ),
1996 Some(TokenState::HasMoreTokens {
1997 over_warn_threshold,
1998 ..
1999 }) => {
2000 let (style, tooltip) = if over_warn_threshold {
2001 (
2002 ButtonStyle::Tinted(TintColor::Warning),
2003 Some(Tooltip::text("Token limit is close to exhaustion")(
2004 window, cx,
2005 )),
2006 )
2007 } else {
2008 (ButtonStyle::Filled, None)
2009 };
2010 (style, tooltip)
2011 }
2012 None => (ButtonStyle::Filled, None),
2013 };
2014
2015 Button::new("send_button", "Send")
2016 .label_size(LabelSize::Small)
2017 .disabled(self.sending_disabled(cx))
2018 .style(style)
2019 .when_some(tooltip, |button, tooltip| {
2020 button.tooltip(move |_, _| tooltip.clone())
2021 })
2022 .layer(ElevationIndex::ModalSurface)
2023 .key_binding(
2024 KeyBinding::for_action_in(&Assist, &focus_handle, window, cx)
2025 .map(|kb| kb.size(rems_from_px(12.))),
2026 )
2027 .on_click(move |_event, window, cx| {
2028 focus_handle.dispatch_action(&Assist, window, cx);
2029 })
2030 }
2031
2032 /// Whether or not we should allow messages to be sent.
2033 /// Will return false if the selected provided has a configuration error or
2034 /// if the user has not accepted the terms of service for this provider.
2035 fn sending_disabled(&self, cx: &mut Context<'_, ContextEditor>) -> bool {
2036 let model = LanguageModelRegistry::read_global(cx).default_model();
2037
2038 let has_configuration_error = configuration_error(cx).is_some();
2039 let needs_to_accept_terms = self.show_accept_terms
2040 && model
2041 .as_ref()
2042 .map_or(false, |model| model.provider.must_accept_terms(cx));
2043 has_configuration_error || needs_to_accept_terms
2044 }
2045
2046 fn render_inject_context_menu(&self, cx: &mut Context<Self>) -> impl IntoElement {
2047 slash_command_picker::SlashCommandSelector::new(
2048 self.slash_commands.clone(),
2049 cx.entity().downgrade(),
2050 IconButton::new("trigger", IconName::Plus)
2051 .icon_size(IconSize::Small)
2052 .icon_color(Color::Muted),
2053 move |window, cx| {
2054 Tooltip::with_meta(
2055 "Add Context",
2056 None,
2057 "Type / to insert via keyboard",
2058 window,
2059 cx,
2060 )
2061 },
2062 )
2063 }
2064
2065 fn render_max_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2066 let context = self.context().read(cx);
2067 let active_model = LanguageModelRegistry::read_global(cx)
2068 .default_model()
2069 .map(|default| default.model)?;
2070 if !active_model.supports_max_mode() {
2071 return None;
2072 }
2073
2074 let active_completion_mode = context.completion_mode();
2075 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
2076 let icon = if burn_mode_enabled {
2077 IconName::ZedBurnModeOn
2078 } else {
2079 IconName::ZedBurnMode
2080 };
2081
2082 Some(
2083 IconButton::new("burn-mode", icon)
2084 .icon_size(IconSize::Small)
2085 .icon_color(Color::Muted)
2086 .toggle_state(burn_mode_enabled)
2087 .selected_icon_color(Color::Error)
2088 .on_click(cx.listener(move |this, _event, _window, cx| {
2089 this.context().update(cx, |context, _cx| {
2090 context.set_completion_mode(match active_completion_mode {
2091 CompletionMode::Burn => CompletionMode::Normal,
2092 CompletionMode::Normal => CompletionMode::Burn,
2093 });
2094 });
2095 }))
2096 .tooltip(move |_window, cx| {
2097 cx.new(|_| MaxModeTooltip::new().selected(burn_mode_enabled))
2098 .into()
2099 })
2100 .into_any_element(),
2101 )
2102 }
2103
2104 fn render_language_model_selector(
2105 &self,
2106 window: &mut Window,
2107 cx: &mut Context<Self>,
2108 ) -> impl IntoElement {
2109 let active_model = LanguageModelRegistry::read_global(cx)
2110 .default_model()
2111 .map(|default| default.model);
2112 let focus_handle = self.editor().focus_handle(cx).clone();
2113 let model_name = match active_model {
2114 Some(model) => model.name().0,
2115 None => SharedString::from("No model selected"),
2116 };
2117
2118 PickerPopoverMenu::new(
2119 self.language_model_selector.clone(),
2120 ButtonLike::new("active-model")
2121 .style(ButtonStyle::Subtle)
2122 .child(
2123 h_flex()
2124 .gap_0p5()
2125 .child(
2126 Label::new(model_name)
2127 .size(LabelSize::Small)
2128 .color(Color::Muted),
2129 )
2130 .child(
2131 Icon::new(IconName::ChevronDown)
2132 .color(Color::Muted)
2133 .size(IconSize::XSmall),
2134 ),
2135 ),
2136 move |window, cx| {
2137 Tooltip::for_action_in(
2138 "Change Model",
2139 &ToggleModelSelector,
2140 &focus_handle,
2141 window,
2142 cx,
2143 )
2144 },
2145 gpui::Corner::BottomLeft,
2146 cx,
2147 )
2148 .with_handle(self.language_model_selector_menu_handle.clone())
2149 .render(window, cx)
2150 }
2151
2152 fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2153 let last_error = self.last_error.as_ref()?;
2154
2155 Some(
2156 div()
2157 .absolute()
2158 .right_3()
2159 .bottom_12()
2160 .max_w_96()
2161 .py_2()
2162 .px_3()
2163 .elevation_2(cx)
2164 .occlude()
2165 .child(match last_error {
2166 AssistError::PaymentRequired => self.render_payment_required_error(cx),
2167 AssistError::Message(error_message) => {
2168 self.render_assist_error(error_message, cx)
2169 }
2170 })
2171 .into_any(),
2172 )
2173 }
2174
2175 fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2176 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.";
2177
2178 v_flex()
2179 .gap_0p5()
2180 .child(
2181 h_flex()
2182 .gap_1p5()
2183 .items_center()
2184 .child(Icon::new(IconName::XCircle).color(Color::Error))
2185 .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2186 )
2187 .child(
2188 div()
2189 .id("error-message")
2190 .max_h_24()
2191 .overflow_y_scroll()
2192 .child(Label::new(ERROR_MESSAGE)),
2193 )
2194 .child(
2195 h_flex()
2196 .justify_end()
2197 .mt_1()
2198 .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
2199 |this, _, _window, cx| {
2200 this.last_error = None;
2201 cx.open_url(&zed_urls::account_url(cx));
2202 cx.notify();
2203 },
2204 )))
2205 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2206 |this, _, _window, cx| {
2207 this.last_error = None;
2208 cx.notify();
2209 },
2210 ))),
2211 )
2212 .into_any()
2213 }
2214
2215 fn render_assist_error(
2216 &self,
2217 error_message: &SharedString,
2218 cx: &mut Context<Self>,
2219 ) -> AnyElement {
2220 v_flex()
2221 .gap_0p5()
2222 .child(
2223 h_flex()
2224 .gap_1p5()
2225 .items_center()
2226 .child(Icon::new(IconName::XCircle).color(Color::Error))
2227 .child(
2228 Label::new("Error interacting with language model")
2229 .weight(FontWeight::MEDIUM),
2230 ),
2231 )
2232 .child(
2233 div()
2234 .id("error-message")
2235 .max_h_32()
2236 .overflow_y_scroll()
2237 .child(Label::new(error_message.clone())),
2238 )
2239 .child(
2240 h_flex()
2241 .justify_end()
2242 .mt_1()
2243 .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2244 |this, _, _window, cx| {
2245 this.last_error = None;
2246 cx.notify();
2247 },
2248 ))),
2249 )
2250 .into_any()
2251 }
2252}
2253
2254/// Returns the contents of the *outermost* fenced code block that contains the given offset.
2255fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
2256 const CODE_BLOCK_NODE: &'static str = "fenced_code_block";
2257 const CODE_BLOCK_CONTENT: &'static str = "code_fence_content";
2258
2259 let layer = snapshot.syntax_layers().next()?;
2260
2261 let root_node = layer.node();
2262 let mut cursor = root_node.walk();
2263
2264 // Go to the first child for the given offset
2265 while cursor.goto_first_child_for_byte(offset).is_some() {
2266 // If we're at the end of the node, go to the next one.
2267 // Example: if you have a fenced-code-block, and you're on the start of the line
2268 // right after the closing ```, you want to skip the fenced-code-block and
2269 // go to the next sibling.
2270 if cursor.node().end_byte() == offset {
2271 cursor.goto_next_sibling();
2272 }
2273
2274 if cursor.node().start_byte() > offset {
2275 break;
2276 }
2277
2278 // We found the fenced code block.
2279 if cursor.node().kind() == CODE_BLOCK_NODE {
2280 // Now we need to find the child node that contains the code.
2281 cursor.goto_first_child();
2282 loop {
2283 if cursor.node().kind() == CODE_BLOCK_CONTENT {
2284 return Some(cursor.node().byte_range());
2285 }
2286 if !cursor.goto_next_sibling() {
2287 break;
2288 }
2289 }
2290 }
2291 }
2292
2293 None
2294}
2295
2296fn render_thought_process_fold_icon_button(
2297 editor: WeakEntity<Editor>,
2298 status: ThoughtProcessStatus,
2299) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2300 Arc::new(move |fold_id, fold_range, _cx| {
2301 let editor = editor.clone();
2302
2303 let button = ButtonLike::new(fold_id).layer(ElevationIndex::ElevatedSurface);
2304 let button = match status {
2305 ThoughtProcessStatus::Pending => button
2306 .child(
2307 Icon::new(IconName::LightBulb)
2308 .size(IconSize::Small)
2309 .color(Color::Muted),
2310 )
2311 .child(
2312 Label::new("Thinking…").color(Color::Muted).with_animation(
2313 "pulsating-label",
2314 Animation::new(Duration::from_secs(2))
2315 .repeat()
2316 .with_easing(pulsating_between(0.4, 0.8)),
2317 |label, delta| label.alpha(delta),
2318 ),
2319 ),
2320 ThoughtProcessStatus::Completed => button
2321 .style(ButtonStyle::Filled)
2322 .child(Icon::new(IconName::LightBulb).size(IconSize::Small))
2323 .child(Label::new("Thought Process").single_line()),
2324 };
2325
2326 button
2327 .on_click(move |_, window, cx| {
2328 editor
2329 .update(cx, |editor, cx| {
2330 let buffer_start = fold_range
2331 .start
2332 .to_point(&editor.buffer().read(cx).read(cx));
2333 let buffer_row = MultiBufferRow(buffer_start.row);
2334 editor.unfold_at(buffer_row, window, cx);
2335 })
2336 .ok();
2337 })
2338 .into_any_element()
2339 })
2340}
2341
2342fn render_fold_icon_button(
2343 editor: WeakEntity<Editor>,
2344 icon_path: SharedString,
2345 label: SharedString,
2346) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2347 Arc::new(move |fold_id, fold_range, _cx| {
2348 let editor = editor.clone();
2349 ButtonLike::new(fold_id)
2350 .style(ButtonStyle::Filled)
2351 .layer(ElevationIndex::ElevatedSurface)
2352 .child(Icon::from_path(icon_path.clone()))
2353 .child(Label::new(label.clone()).single_line())
2354 .on_click(move |_, window, cx| {
2355 editor
2356 .update(cx, |editor, cx| {
2357 let buffer_start = fold_range
2358 .start
2359 .to_point(&editor.buffer().read(cx).read(cx));
2360 let buffer_row = MultiBufferRow(buffer_start.row);
2361 editor.unfold_at(buffer_row, window, cx);
2362 })
2363 .ok();
2364 })
2365 .into_any_element()
2366 })
2367}
2368
2369type ToggleFold = Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>;
2370
2371fn render_slash_command_output_toggle(
2372 row: MultiBufferRow,
2373 is_folded: bool,
2374 fold: ToggleFold,
2375 _window: &mut Window,
2376 _cx: &mut App,
2377) -> AnyElement {
2378 Disclosure::new(
2379 ("slash-command-output-fold-indicator", row.0 as u64),
2380 !is_folded,
2381 )
2382 .toggle_state(is_folded)
2383 .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2384 .into_any_element()
2385}
2386
2387pub fn fold_toggle(
2388 name: &'static str,
2389) -> impl Fn(
2390 MultiBufferRow,
2391 bool,
2392 Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
2393 &mut Window,
2394 &mut App,
2395) -> AnyElement {
2396 move |row, is_folded, fold, _window, _cx| {
2397 Disclosure::new((name, row.0 as u64), !is_folded)
2398 .toggle_state(is_folded)
2399 .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2400 .into_any_element()
2401 }
2402}
2403
2404fn quote_selection_fold_placeholder(title: String, editor: WeakEntity<Editor>) -> FoldPlaceholder {
2405 FoldPlaceholder {
2406 render: Arc::new({
2407 move |fold_id, fold_range, _cx| {
2408 let editor = editor.clone();
2409 ButtonLike::new(fold_id)
2410 .style(ButtonStyle::Filled)
2411 .layer(ElevationIndex::ElevatedSurface)
2412 .child(Icon::new(IconName::TextSnippet))
2413 .child(Label::new(title.clone()).single_line())
2414 .on_click(move |_, window, cx| {
2415 editor
2416 .update(cx, |editor, cx| {
2417 let buffer_start = fold_range
2418 .start
2419 .to_point(&editor.buffer().read(cx).read(cx));
2420 let buffer_row = MultiBufferRow(buffer_start.row);
2421 editor.unfold_at(buffer_row, window, cx);
2422 })
2423 .ok();
2424 })
2425 .into_any_element()
2426 }
2427 }),
2428 merge_adjacent: false,
2429 ..Default::default()
2430 }
2431}
2432
2433fn render_quote_selection_output_toggle(
2434 row: MultiBufferRow,
2435 is_folded: bool,
2436 fold: ToggleFold,
2437 _window: &mut Window,
2438 _cx: &mut App,
2439) -> AnyElement {
2440 Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
2441 .toggle_state(is_folded)
2442 .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2443 .into_any_element()
2444}
2445
2446fn render_pending_slash_command_gutter_decoration(
2447 row: MultiBufferRow,
2448 status: &PendingSlashCommandStatus,
2449 confirm_command: Arc<dyn Fn(&mut Window, &mut App)>,
2450) -> AnyElement {
2451 let mut icon = IconButton::new(
2452 ("slash-command-gutter-decoration", row.0),
2453 ui::IconName::TriangleRight,
2454 )
2455 .on_click(move |_e, window, cx| confirm_command(window, cx))
2456 .icon_size(ui::IconSize::Small)
2457 .size(ui::ButtonSize::None);
2458
2459 match status {
2460 PendingSlashCommandStatus::Idle => {
2461 icon = icon.icon_color(Color::Muted);
2462 }
2463 PendingSlashCommandStatus::Running { .. } => {
2464 icon = icon.toggle_state(true);
2465 }
2466 PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
2467 }
2468
2469 icon.into_any_element()
2470}
2471
2472fn render_docs_slash_command_trailer(
2473 row: MultiBufferRow,
2474 command: ParsedSlashCommand,
2475 cx: &mut App,
2476) -> AnyElement {
2477 if command.arguments.is_empty() {
2478 return Empty.into_any();
2479 }
2480 let args = DocsSlashCommandArgs::parse(&command.arguments);
2481
2482 let Some(store) = args
2483 .provider()
2484 .and_then(|provider| IndexedDocsStore::try_global(provider, cx).ok())
2485 else {
2486 return Empty.into_any();
2487 };
2488
2489 let Some(package) = args.package() else {
2490 return Empty.into_any();
2491 };
2492
2493 let mut children = Vec::new();
2494
2495 if store.is_indexing(&package) {
2496 children.push(
2497 div()
2498 .id(("crates-being-indexed", row.0))
2499 .child(Icon::new(IconName::ArrowCircle).with_animation(
2500 "arrow-circle",
2501 Animation::new(Duration::from_secs(4)).repeat(),
2502 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2503 ))
2504 .tooltip({
2505 let package = package.clone();
2506 Tooltip::text(format!("Indexing {package}…"))
2507 })
2508 .into_any_element(),
2509 );
2510 }
2511
2512 if let Some(latest_error) = store.latest_error_for_package(&package) {
2513 children.push(
2514 div()
2515 .id(("latest-error", row.0))
2516 .child(
2517 Icon::new(IconName::Warning)
2518 .size(IconSize::Small)
2519 .color(Color::Warning),
2520 )
2521 .tooltip(Tooltip::text(format!("Failed to index: {latest_error}")))
2522 .into_any_element(),
2523 )
2524 }
2525
2526 let is_indexing = store.is_indexing(&package);
2527 let latest_error = store.latest_error_for_package(&package);
2528
2529 if !is_indexing && latest_error.is_none() {
2530 return Empty.into_any();
2531 }
2532
2533 h_flex().gap_2().children(children).into_any_element()
2534}
2535
2536#[derive(Debug, Clone, Serialize, Deserialize)]
2537struct CopyMetadata {
2538 creases: Vec<SelectedCreaseMetadata>,
2539}
2540
2541#[derive(Debug, Clone, Serialize, Deserialize)]
2542struct SelectedCreaseMetadata {
2543 range_relative_to_selection: Range<usize>,
2544 crease: CreaseMetadata,
2545}
2546
2547impl EventEmitter<EditorEvent> for ContextEditor {}
2548impl EventEmitter<SearchEvent> for ContextEditor {}
2549
2550impl Render for ContextEditor {
2551 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2552 let provider = LanguageModelRegistry::read_global(cx)
2553 .default_model()
2554 .map(|default| default.provider);
2555
2556 let accept_terms = if self.show_accept_terms {
2557 provider.as_ref().and_then(|provider| {
2558 provider.render_accept_terms(LanguageModelProviderTosView::PromptEditorPopup, cx)
2559 })
2560 } else {
2561 None
2562 };
2563
2564 let language_model_selector = self.language_model_selector_menu_handle.clone();
2565 let max_mode_toggle = self.render_max_mode_toggle(cx);
2566
2567 v_flex()
2568 .key_context("ContextEditor")
2569 .capture_action(cx.listener(ContextEditor::cancel))
2570 .capture_action(cx.listener(ContextEditor::save))
2571 .capture_action(cx.listener(ContextEditor::copy))
2572 .capture_action(cx.listener(ContextEditor::cut))
2573 .capture_action(cx.listener(ContextEditor::paste))
2574 .capture_action(cx.listener(ContextEditor::cycle_message_role))
2575 .capture_action(cx.listener(ContextEditor::confirm_command))
2576 .on_action(cx.listener(ContextEditor::assist))
2577 .on_action(cx.listener(ContextEditor::split))
2578 .on_action(move |_: &ToggleModelSelector, window, cx| {
2579 language_model_selector.toggle(window, cx);
2580 })
2581 .size_full()
2582 .children(self.render_notice(cx))
2583 .child(
2584 div()
2585 .flex_grow()
2586 .bg(cx.theme().colors().editor_background)
2587 .child(self.editor.clone()),
2588 )
2589 .when_some(accept_terms, |this, element| {
2590 this.child(
2591 div()
2592 .absolute()
2593 .right_3()
2594 .bottom_12()
2595 .max_w_96()
2596 .py_2()
2597 .px_3()
2598 .elevation_2(cx)
2599 .bg(cx.theme().colors().surface_background)
2600 .occlude()
2601 .child(element),
2602 )
2603 })
2604 .children(self.render_last_error(cx))
2605 .child(
2606 h_flex()
2607 .relative()
2608 .py_2()
2609 .pl_1p5()
2610 .pr_2()
2611 .w_full()
2612 .justify_between()
2613 .border_t_1()
2614 .border_color(cx.theme().colors().border_variant)
2615 .bg(cx.theme().colors().editor_background)
2616 .child(
2617 h_flex()
2618 .gap_0p5()
2619 .child(self.render_inject_context_menu(cx))
2620 .when_some(max_mode_toggle, |this, element| this.child(element)),
2621 )
2622 .child(
2623 h_flex()
2624 .gap_1()
2625 .child(self.render_language_model_selector(window, cx))
2626 .child(self.render_send_button(window, cx)),
2627 ),
2628 )
2629 }
2630}
2631
2632impl Focusable for ContextEditor {
2633 fn focus_handle(&self, cx: &App) -> FocusHandle {
2634 self.editor.focus_handle(cx)
2635 }
2636}
2637
2638impl Item for ContextEditor {
2639 type Event = editor::EditorEvent;
2640
2641 fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
2642 util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into()
2643 }
2644
2645 fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
2646 match event {
2647 EditorEvent::Edited { .. } => {
2648 f(item::ItemEvent::Edit);
2649 }
2650 EditorEvent::TitleChanged => {
2651 f(item::ItemEvent::UpdateTab);
2652 }
2653 _ => {}
2654 }
2655 }
2656
2657 fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
2658 Some(self.title(cx).to_string().into())
2659 }
2660
2661 fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
2662 Some(Box::new(handle.clone()))
2663 }
2664
2665 fn set_nav_history(
2666 &mut self,
2667 nav_history: pane::ItemNavHistory,
2668 window: &mut Window,
2669 cx: &mut Context<Self>,
2670 ) {
2671 self.editor.update(cx, |editor, cx| {
2672 Item::set_nav_history(editor, nav_history, window, cx)
2673 })
2674 }
2675
2676 fn navigate(
2677 &mut self,
2678 data: Box<dyn std::any::Any>,
2679 window: &mut Window,
2680 cx: &mut Context<Self>,
2681 ) -> bool {
2682 self.editor
2683 .update(cx, |editor, cx| Item::navigate(editor, data, window, cx))
2684 }
2685
2686 fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2687 self.editor
2688 .update(cx, |editor, cx| Item::deactivated(editor, window, cx))
2689 }
2690
2691 fn act_as_type<'a>(
2692 &'a self,
2693 type_id: TypeId,
2694 self_handle: &'a Entity<Self>,
2695 _: &'a App,
2696 ) -> Option<AnyView> {
2697 if type_id == TypeId::of::<Self>() {
2698 Some(self_handle.to_any())
2699 } else if type_id == TypeId::of::<Editor>() {
2700 Some(self.editor.to_any())
2701 } else {
2702 None
2703 }
2704 }
2705
2706 fn include_in_nav_history() -> bool {
2707 false
2708 }
2709}
2710
2711impl SearchableItem for ContextEditor {
2712 type Match = <Editor as SearchableItem>::Match;
2713
2714 fn clear_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2715 self.editor.update(cx, |editor, cx| {
2716 editor.clear_matches(window, cx);
2717 });
2718 }
2719
2720 fn update_matches(
2721 &mut self,
2722 matches: &[Self::Match],
2723 window: &mut Window,
2724 cx: &mut Context<Self>,
2725 ) {
2726 self.editor
2727 .update(cx, |editor, cx| editor.update_matches(matches, window, cx));
2728 }
2729
2730 fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
2731 self.editor
2732 .update(cx, |editor, cx| editor.query_suggestion(window, cx))
2733 }
2734
2735 fn activate_match(
2736 &mut self,
2737 index: usize,
2738 matches: &[Self::Match],
2739 window: &mut Window,
2740 cx: &mut Context<Self>,
2741 ) {
2742 self.editor.update(cx, |editor, cx| {
2743 editor.activate_match(index, matches, window, cx);
2744 });
2745 }
2746
2747 fn select_matches(
2748 &mut self,
2749 matches: &[Self::Match],
2750 window: &mut Window,
2751 cx: &mut Context<Self>,
2752 ) {
2753 self.editor
2754 .update(cx, |editor, cx| editor.select_matches(matches, window, cx));
2755 }
2756
2757 fn replace(
2758 &mut self,
2759 identifier: &Self::Match,
2760 query: &project::search::SearchQuery,
2761 window: &mut Window,
2762 cx: &mut Context<Self>,
2763 ) {
2764 self.editor.update(cx, |editor, cx| {
2765 editor.replace(identifier, query, window, cx)
2766 });
2767 }
2768
2769 fn find_matches(
2770 &mut self,
2771 query: Arc<project::search::SearchQuery>,
2772 window: &mut Window,
2773 cx: &mut Context<Self>,
2774 ) -> Task<Vec<Self::Match>> {
2775 self.editor
2776 .update(cx, |editor, cx| editor.find_matches(query, window, cx))
2777 }
2778
2779 fn active_match_index(
2780 &mut self,
2781 direction: Direction,
2782 matches: &[Self::Match],
2783 window: &mut Window,
2784 cx: &mut Context<Self>,
2785 ) -> Option<usize> {
2786 self.editor.update(cx, |editor, cx| {
2787 editor.active_match_index(direction, matches, window, cx)
2788 })
2789 }
2790}
2791
2792impl FollowableItem for ContextEditor {
2793 fn remote_id(&self) -> Option<workspace::ViewId> {
2794 self.remote_id
2795 }
2796
2797 fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant> {
2798 let context = self.context.read(cx);
2799 Some(proto::view::Variant::ContextEditor(
2800 proto::view::ContextEditor {
2801 context_id: context.id().to_proto(),
2802 editor: if let Some(proto::view::Variant::Editor(proto)) =
2803 self.editor.read(cx).to_state_proto(window, cx)
2804 {
2805 Some(proto)
2806 } else {
2807 None
2808 },
2809 },
2810 ))
2811 }
2812
2813 fn from_state_proto(
2814 workspace: Entity<Workspace>,
2815 id: workspace::ViewId,
2816 state: &mut Option<proto::view::Variant>,
2817 window: &mut Window,
2818 cx: &mut App,
2819 ) -> Option<Task<Result<Entity<Self>>>> {
2820 let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
2821 return None;
2822 };
2823 let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
2824 unreachable!()
2825 };
2826
2827 let context_id = ContextId::from_proto(state.context_id);
2828 let editor_state = state.editor?;
2829
2830 let project = workspace.read(cx).project().clone();
2831 let agent_panel_delegate = <dyn AgentPanelDelegate>::try_global(cx)?;
2832
2833 let context_editor_task = workspace.update(cx, |workspace, cx| {
2834 agent_panel_delegate.open_remote_context(workspace, context_id, window, cx)
2835 });
2836
2837 Some(window.spawn(cx, async move |cx| {
2838 let context_editor = context_editor_task.await?;
2839 context_editor
2840 .update_in(cx, |context_editor, window, cx| {
2841 context_editor.remote_id = Some(id);
2842 context_editor.editor.update(cx, |editor, cx| {
2843 editor.apply_update_proto(
2844 &project,
2845 proto::update_view::Variant::Editor(proto::update_view::Editor {
2846 selections: editor_state.selections,
2847 pending_selection: editor_state.pending_selection,
2848 scroll_top_anchor: editor_state.scroll_top_anchor,
2849 scroll_x: editor_state.scroll_y,
2850 scroll_y: editor_state.scroll_y,
2851 ..Default::default()
2852 }),
2853 window,
2854 cx,
2855 )
2856 })
2857 })?
2858 .await?;
2859 Ok(context_editor)
2860 }))
2861 }
2862
2863 fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
2864 Editor::to_follow_event(event)
2865 }
2866
2867 fn add_event_to_update_proto(
2868 &self,
2869 event: &Self::Event,
2870 update: &mut Option<proto::update_view::Variant>,
2871 window: &Window,
2872 cx: &App,
2873 ) -> bool {
2874 self.editor
2875 .read(cx)
2876 .add_event_to_update_proto(event, update, window, cx)
2877 }
2878
2879 fn apply_update_proto(
2880 &mut self,
2881 project: &Entity<Project>,
2882 message: proto::update_view::Variant,
2883 window: &mut Window,
2884 cx: &mut Context<Self>,
2885 ) -> Task<Result<()>> {
2886 self.editor.update(cx, |editor, cx| {
2887 editor.apply_update_proto(project, message, window, cx)
2888 })
2889 }
2890
2891 fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
2892 true
2893 }
2894
2895 fn set_leader_id(
2896 &mut self,
2897 leader_id: Option<CollaboratorId>,
2898 window: &mut Window,
2899 cx: &mut Context<Self>,
2900 ) {
2901 self.editor
2902 .update(cx, |editor, cx| editor.set_leader_id(leader_id, window, cx))
2903 }
2904
2905 fn dedup(&self, existing: &Self, _window: &Window, cx: &App) -> Option<item::Dedup> {
2906 if existing.context.read(cx).id() == self.context.read(cx).id() {
2907 Some(item::Dedup::KeepExisting)
2908 } else {
2909 None
2910 }
2911 }
2912}
2913
2914pub struct ContextEditorToolbarItem {
2915 active_context_editor: Option<WeakEntity<ContextEditor>>,
2916 model_summary_editor: Entity<Editor>,
2917}
2918
2919impl ContextEditorToolbarItem {
2920 pub fn new(model_summary_editor: Entity<Editor>) -> Self {
2921 Self {
2922 active_context_editor: None,
2923 model_summary_editor,
2924 }
2925 }
2926}
2927
2928pub fn render_remaining_tokens(
2929 context_editor: &Entity<ContextEditor>,
2930 cx: &App,
2931) -> Option<impl IntoElement + use<>> {
2932 let context = &context_editor.read(cx).context;
2933
2934 let (token_count_color, token_count, max_token_count, tooltip) = match token_state(context, cx)?
2935 {
2936 TokenState::NoTokensLeft {
2937 max_token_count,
2938 token_count,
2939 } => (
2940 Color::Error,
2941 token_count,
2942 max_token_count,
2943 Some("Token Limit Reached"),
2944 ),
2945 TokenState::HasMoreTokens {
2946 max_token_count,
2947 token_count,
2948 over_warn_threshold,
2949 } => {
2950 let (color, tooltip) = if over_warn_threshold {
2951 (Color::Warning, Some("Token Limit is Close to Exhaustion"))
2952 } else {
2953 (Color::Muted, None)
2954 };
2955 (color, token_count, max_token_count, tooltip)
2956 }
2957 };
2958
2959 Some(
2960 h_flex()
2961 .id("token-count")
2962 .gap_0p5()
2963 .child(
2964 Label::new(humanize_token_count(token_count))
2965 .size(LabelSize::Small)
2966 .color(token_count_color),
2967 )
2968 .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
2969 .child(
2970 Label::new(humanize_token_count(max_token_count))
2971 .size(LabelSize::Small)
2972 .color(Color::Muted),
2973 )
2974 .when_some(tooltip, |element, tooltip| {
2975 element.tooltip(Tooltip::text(tooltip))
2976 }),
2977 )
2978}
2979
2980impl Render for ContextEditorToolbarItem {
2981 fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2982 let left_side = h_flex()
2983 .group("chat-title-group")
2984 .gap_1()
2985 .items_center()
2986 .flex_grow()
2987 .child(
2988 div()
2989 .w_full()
2990 .when(self.active_context_editor.is_some(), |left_side| {
2991 left_side.child(self.model_summary_editor.clone())
2992 }),
2993 )
2994 .child(
2995 div().visible_on_hover("chat-title-group").child(
2996 IconButton::new("regenerate-context", IconName::RefreshTitle)
2997 .shape(ui::IconButtonShape::Square)
2998 .tooltip(Tooltip::text("Regenerate Title"))
2999 .on_click(cx.listener(move |_, _, _window, cx| {
3000 cx.emit(ContextEditorToolbarItemEvent::RegenerateSummary)
3001 })),
3002 ),
3003 );
3004
3005 let right_side = h_flex()
3006 .gap_2()
3007 // TODO display this in a nicer way, once we have a design for it.
3008 // .children({
3009 // let project = self
3010 // .workspace
3011 // .upgrade()
3012 // .map(|workspace| workspace.read(cx).project().downgrade());
3013 //
3014 // let scan_items_remaining = cx.update_global(|db: &mut SemanticDb, cx| {
3015 // project.and_then(|project| db.remaining_summaries(&project, cx))
3016 // });
3017 // scan_items_remaining
3018 // .map(|remaining_items| format!("Files to scan: {}", remaining_items))
3019 // })
3020 .children(
3021 self.active_context_editor
3022 .as_ref()
3023 .and_then(|editor| editor.upgrade())
3024 .and_then(|editor| render_remaining_tokens(&editor, cx)),
3025 );
3026
3027 h_flex()
3028 .px_0p5()
3029 .size_full()
3030 .gap_2()
3031 .justify_between()
3032 .child(left_side)
3033 .child(right_side)
3034 }
3035}
3036
3037impl ToolbarItemView for ContextEditorToolbarItem {
3038 fn set_active_pane_item(
3039 &mut self,
3040 active_pane_item: Option<&dyn ItemHandle>,
3041 _window: &mut Window,
3042 cx: &mut Context<Self>,
3043 ) -> ToolbarItemLocation {
3044 self.active_context_editor = active_pane_item
3045 .and_then(|item| item.act_as::<ContextEditor>(cx))
3046 .map(|editor| editor.downgrade());
3047 cx.notify();
3048 if self.active_context_editor.is_none() {
3049 ToolbarItemLocation::Hidden
3050 } else {
3051 ToolbarItemLocation::PrimaryRight
3052 }
3053 }
3054
3055 fn pane_focus_update(
3056 &mut self,
3057 _pane_focused: bool,
3058 _window: &mut Window,
3059 cx: &mut Context<Self>,
3060 ) {
3061 cx.notify();
3062 }
3063}
3064
3065impl EventEmitter<ToolbarItemEvent> for ContextEditorToolbarItem {}
3066
3067pub enum ContextEditorToolbarItemEvent {
3068 RegenerateSummary,
3069}
3070impl EventEmitter<ContextEditorToolbarItemEvent> for ContextEditorToolbarItem {}
3071
3072enum PendingSlashCommand {}
3073
3074fn invoked_slash_command_fold_placeholder(
3075 command_id: InvokedSlashCommandId,
3076 context: WeakEntity<AssistantContext>,
3077) -> FoldPlaceholder {
3078 FoldPlaceholder {
3079 constrain_width: false,
3080 merge_adjacent: false,
3081 render: Arc::new(move |fold_id, _, cx| {
3082 let Some(context) = context.upgrade() else {
3083 return Empty.into_any();
3084 };
3085
3086 let Some(command) = context.read(cx).invoked_slash_command(&command_id) else {
3087 return Empty.into_any();
3088 };
3089
3090 h_flex()
3091 .id(fold_id)
3092 .px_1()
3093 .ml_6()
3094 .gap_2()
3095 .bg(cx.theme().colors().surface_background)
3096 .rounded_sm()
3097 .child(Label::new(format!("/{}", command.name)))
3098 .map(|parent| match &command.status {
3099 InvokedSlashCommandStatus::Running(_) => {
3100 parent.child(Icon::new(IconName::ArrowCircle).with_animation(
3101 "arrow-circle",
3102 Animation::new(Duration::from_secs(4)).repeat(),
3103 |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
3104 ))
3105 }
3106 InvokedSlashCommandStatus::Error(message) => parent.child(
3107 Label::new(format!("error: {message}"))
3108 .single_line()
3109 .color(Color::Error),
3110 ),
3111 InvokedSlashCommandStatus::Finished => parent,
3112 })
3113 .into_any_element()
3114 }),
3115 type_tag: Some(TypeId::of::<PendingSlashCommand>()),
3116 }
3117}
3118
3119enum TokenState {
3120 NoTokensLeft {
3121 max_token_count: usize,
3122 token_count: usize,
3123 },
3124 HasMoreTokens {
3125 max_token_count: usize,
3126 token_count: usize,
3127 over_warn_threshold: bool,
3128 },
3129}
3130
3131fn token_state(context: &Entity<AssistantContext>, cx: &App) -> Option<TokenState> {
3132 const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
3133
3134 let model = LanguageModelRegistry::read_global(cx)
3135 .default_model()?
3136 .model;
3137 let token_count = context.read(cx).token_count()?;
3138 let max_token_count = model.max_token_count();
3139
3140 let remaining_tokens = max_token_count as isize - token_count as isize;
3141 let token_state = if remaining_tokens <= 0 {
3142 TokenState::NoTokensLeft {
3143 max_token_count,
3144 token_count,
3145 }
3146 } else {
3147 let over_warn_threshold =
3148 token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
3149 TokenState::HasMoreTokens {
3150 max_token_count,
3151 token_count,
3152 over_warn_threshold,
3153 }
3154 };
3155 Some(token_state)
3156}
3157
3158fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
3159 let image_size = data
3160 .size(0)
3161 .map(|dimension| Pixels::from(u32::from(dimension)));
3162 let image_ratio = image_size.width / image_size.height;
3163 let bounds_ratio = max_size.width / max_size.height;
3164
3165 if image_size.width > max_size.width || image_size.height > max_size.height {
3166 if bounds_ratio > image_ratio {
3167 size(
3168 image_size.width * (max_size.height / image_size.height),
3169 max_size.height,
3170 )
3171 } else {
3172 size(
3173 max_size.width,
3174 image_size.height * (max_size.width / image_size.width),
3175 )
3176 }
3177 } else {
3178 size(image_size.width, image_size.height)
3179 }
3180}
3181
3182pub enum ConfigurationError {
3183 NoProvider,
3184 ProviderNotAuthenticated,
3185 ProviderPendingTermsAcceptance(Arc<dyn LanguageModelProvider>),
3186}
3187
3188fn configuration_error(cx: &App) -> Option<ConfigurationError> {
3189 let model = LanguageModelRegistry::read_global(cx).default_model();
3190 let is_authenticated = model
3191 .as_ref()
3192 .map_or(false, |model| model.provider.is_authenticated(cx));
3193
3194 if model.is_some() && is_authenticated {
3195 return None;
3196 }
3197
3198 if model.is_none() {
3199 return Some(ConfigurationError::NoProvider);
3200 }
3201
3202 if !is_authenticated {
3203 return Some(ConfigurationError::ProviderNotAuthenticated);
3204 }
3205
3206 None
3207}
3208
3209pub fn humanize_token_count(count: usize) -> String {
3210 match count {
3211 0..=999 => count.to_string(),
3212 1000..=9999 => {
3213 let thousands = count / 1000;
3214 let hundreds = (count % 1000 + 50) / 100;
3215 if hundreds == 0 {
3216 format!("{}k", thousands)
3217 } else if hundreds == 10 {
3218 format!("{}k", thousands + 1)
3219 } else {
3220 format!("{}.{}k", thousands, hundreds)
3221 }
3222 }
3223 1_000_000..=9_999_999 => {
3224 let millions = count / 1_000_000;
3225 let hundred_thousands = (count % 1_000_000 + 50_000) / 100_000;
3226 if hundred_thousands == 0 {
3227 format!("{}M", millions)
3228 } else if hundred_thousands == 10 {
3229 format!("{}M", millions + 1)
3230 } else {
3231 format!("{}.{}M", millions, hundred_thousands)
3232 }
3233 }
3234 10_000_000.. => format!("{}M", (count + 500_000) / 1_000_000),
3235 _ => format!("{}k", (count + 500) / 1000),
3236 }
3237}
3238
3239pub fn make_lsp_adapter_delegate(
3240 project: &Entity<Project>,
3241 cx: &mut App,
3242) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
3243 project.update(cx, |project, cx| {
3244 // TODO: Find the right worktree.
3245 let Some(worktree) = project.worktrees(cx).next() else {
3246 return Ok(None::<Arc<dyn LspAdapterDelegate>>);
3247 };
3248 let http_client = project.client().http_client();
3249 project.lsp_store().update(cx, |_, cx| {
3250 Ok(Some(LocalLspAdapterDelegate::new(
3251 project.languages().clone(),
3252 project.environment(),
3253 cx.weak_entity(),
3254 &worktree,
3255 http_client,
3256 project.fs().clone(),
3257 cx,
3258 ) as Arc<dyn LspAdapterDelegate>))
3259 })
3260 })
3261}
3262
3263#[cfg(test)]
3264mod tests {
3265 use super::*;
3266 use fs::FakeFs;
3267 use gpui::{App, TestAppContext, VisualTestContext};
3268 use indoc::indoc;
3269 use language::{Buffer, LanguageRegistry};
3270 use pretty_assertions::assert_eq;
3271 use prompt_store::PromptBuilder;
3272 use text::OffsetRangeExt;
3273 use unindent::Unindent;
3274 use util::path;
3275
3276 #[gpui::test]
3277 async fn test_copy_paste_whole_message(cx: &mut TestAppContext) {
3278 let (context, context_editor, mut cx) = setup_context_editor_text(vec![
3279 (Role::User, "What is the Zed editor?"),
3280 (
3281 Role::Assistant,
3282 "Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.",
3283 ),
3284 (Role::User, ""),
3285 ],cx).await;
3286
3287 // Select & Copy whole user message
3288 assert_copy_paste_context_editor(
3289 &context_editor,
3290 message_range(&context, 0, &mut cx),
3291 indoc! {"
3292 What is the Zed editor?
3293 Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
3294 What is the Zed editor?
3295 "},
3296 &mut cx,
3297 );
3298
3299 // Select & Copy whole assistant message
3300 assert_copy_paste_context_editor(
3301 &context_editor,
3302 message_range(&context, 1, &mut cx),
3303 indoc! {"
3304 What is the Zed editor?
3305 Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
3306 What is the Zed editor?
3307 Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
3308 "},
3309 &mut cx,
3310 );
3311 }
3312
3313 #[gpui::test]
3314 async fn test_copy_paste_no_selection(cx: &mut TestAppContext) {
3315 let (context, context_editor, mut cx) = setup_context_editor_text(
3316 vec![
3317 (Role::User, "user1"),
3318 (Role::Assistant, "assistant1"),
3319 (Role::Assistant, "assistant2"),
3320 (Role::User, ""),
3321 ],
3322 cx,
3323 )
3324 .await;
3325
3326 // Copy and paste first assistant message
3327 let message_2_range = message_range(&context, 1, &mut cx);
3328 assert_copy_paste_context_editor(
3329 &context_editor,
3330 message_2_range.start..message_2_range.start,
3331 indoc! {"
3332 user1
3333 assistant1
3334 assistant2
3335 assistant1
3336 "},
3337 &mut cx,
3338 );
3339
3340 // Copy and cut second assistant message
3341 let message_3_range = message_range(&context, 2, &mut cx);
3342 assert_copy_paste_context_editor(
3343 &context_editor,
3344 message_3_range.start..message_3_range.start,
3345 indoc! {"
3346 user1
3347 assistant1
3348 assistant2
3349 assistant1
3350 assistant2
3351 "},
3352 &mut cx,
3353 );
3354 }
3355
3356 #[gpui::test]
3357 fn test_find_code_blocks(cx: &mut App) {
3358 let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
3359
3360 let buffer = cx.new(|cx| {
3361 let text = r#"
3362 line 0
3363 line 1
3364 ```rust
3365 fn main() {}
3366 ```
3367 line 5
3368 line 6
3369 line 7
3370 ```go
3371 func main() {}
3372 ```
3373 line 11
3374 ```
3375 this is plain text code block
3376 ```
3377
3378 ```go
3379 func another() {}
3380 ```
3381 line 19
3382 "#
3383 .unindent();
3384 let mut buffer = Buffer::local(text, cx);
3385 buffer.set_language(Some(markdown.clone()), cx);
3386 buffer
3387 });
3388 let snapshot = buffer.read(cx).snapshot();
3389
3390 let code_blocks = vec![
3391 Point::new(3, 0)..Point::new(4, 0),
3392 Point::new(9, 0)..Point::new(10, 0),
3393 Point::new(13, 0)..Point::new(14, 0),
3394 Point::new(17, 0)..Point::new(18, 0),
3395 ]
3396 .into_iter()
3397 .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
3398 .collect::<Vec<_>>();
3399
3400 let expected_results = vec![
3401 (0, None),
3402 (1, None),
3403 (2, Some(code_blocks[0].clone())),
3404 (3, Some(code_blocks[0].clone())),
3405 (4, Some(code_blocks[0].clone())),
3406 (5, None),
3407 (6, None),
3408 (7, None),
3409 (8, Some(code_blocks[1].clone())),
3410 (9, Some(code_blocks[1].clone())),
3411 (10, Some(code_blocks[1].clone())),
3412 (11, None),
3413 (12, Some(code_blocks[2].clone())),
3414 (13, Some(code_blocks[2].clone())),
3415 (14, Some(code_blocks[2].clone())),
3416 (15, None),
3417 (16, Some(code_blocks[3].clone())),
3418 (17, Some(code_blocks[3].clone())),
3419 (18, Some(code_blocks[3].clone())),
3420 (19, None),
3421 ];
3422
3423 for (row, expected) in expected_results {
3424 let offset = snapshot.point_to_offset(Point::new(row, 0));
3425 let range = find_surrounding_code_block(&snapshot, offset);
3426 assert_eq!(range, expected, "unexpected result on row {:?}", row);
3427 }
3428 }
3429
3430 async fn setup_context_editor_text(
3431 messages: Vec<(Role, &str)>,
3432 cx: &mut TestAppContext,
3433 ) -> (
3434 Entity<AssistantContext>,
3435 Entity<ContextEditor>,
3436 VisualTestContext,
3437 ) {
3438 cx.update(init_test);
3439
3440 let fs = FakeFs::new(cx.executor());
3441 let context = create_context_with_messages(messages, cx);
3442
3443 let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
3444 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
3445 let workspace = window.root(cx).unwrap();
3446 let mut cx = VisualTestContext::from_window(*window, cx);
3447
3448 let context_editor = window
3449 .update(&mut cx, |_, window, cx| {
3450 cx.new(|cx| {
3451 let editor = ContextEditor::for_context(
3452 context.clone(),
3453 fs,
3454 workspace.downgrade(),
3455 project,
3456 None,
3457 window,
3458 cx,
3459 );
3460 editor
3461 })
3462 })
3463 .unwrap();
3464
3465 (context, context_editor, cx)
3466 }
3467
3468 fn message_range(
3469 context: &Entity<AssistantContext>,
3470 message_ix: usize,
3471 cx: &mut TestAppContext,
3472 ) -> Range<usize> {
3473 context.update(cx, |context, cx| {
3474 context
3475 .messages(cx)
3476 .nth(message_ix)
3477 .unwrap()
3478 .anchor_range
3479 .to_offset(&context.buffer().read(cx).snapshot())
3480 })
3481 }
3482
3483 fn assert_copy_paste_context_editor<T: editor::ToOffset>(
3484 context_editor: &Entity<ContextEditor>,
3485 range: Range<T>,
3486 expected_text: &str,
3487 cx: &mut VisualTestContext,
3488 ) {
3489 context_editor.update_in(cx, |context_editor, window, cx| {
3490 context_editor.editor.update(cx, |editor, cx| {
3491 editor.change_selections(None, window, cx, |s| s.select_ranges([range]));
3492 });
3493
3494 context_editor.copy(&Default::default(), window, cx);
3495
3496 context_editor.editor.update(cx, |editor, cx| {
3497 editor.move_to_end(&Default::default(), window, cx);
3498 });
3499
3500 context_editor.paste(&Default::default(), window, cx);
3501
3502 context_editor.editor.update(cx, |editor, cx| {
3503 assert_eq!(editor.text(cx), expected_text);
3504 });
3505 });
3506 }
3507
3508 fn create_context_with_messages(
3509 mut messages: Vec<(Role, &str)>,
3510 cx: &mut TestAppContext,
3511 ) -> Entity<AssistantContext> {
3512 let registry = Arc::new(LanguageRegistry::test(cx.executor()));
3513 let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3514 cx.new(|cx| {
3515 let mut context = AssistantContext::local(
3516 registry,
3517 None,
3518 None,
3519 prompt_builder.clone(),
3520 Arc::new(SlashCommandWorkingSet::default()),
3521 cx,
3522 );
3523 let mut message_1 = context.messages(cx).next().unwrap();
3524 let (role, text) = messages.remove(0);
3525
3526 loop {
3527 if role == message_1.role {
3528 context.buffer().update(cx, |buffer, cx| {
3529 buffer.edit([(message_1.offset_range, text)], None, cx);
3530 });
3531 break;
3532 }
3533 let mut ids = HashSet::default();
3534 ids.insert(message_1.id);
3535 context.cycle_message_roles(ids, cx);
3536 message_1 = context.messages(cx).next().unwrap();
3537 }
3538
3539 let mut last_message_id = message_1.id;
3540 for (role, text) in messages {
3541 context.insert_message_after(last_message_id, role, MessageStatus::Done, cx);
3542 let message = context.messages(cx).last().unwrap();
3543 last_message_id = message.id;
3544 context.buffer().update(cx, |buffer, cx| {
3545 buffer.edit([(message.offset_range, text)], None, cx);
3546 })
3547 }
3548
3549 context
3550 })
3551 }
3552
3553 fn init_test(cx: &mut App) {
3554 let settings_store = SettingsStore::test(cx);
3555 prompt_store::init(cx);
3556 LanguageModelRegistry::test(cx);
3557 cx.set_global(settings_store);
3558 language::init(cx);
3559 agent_settings::init(cx);
3560 Project::init_settings(cx);
3561 theme::init(theme::LoadThemes::JustBase, cx);
3562 workspace::init_settings(cx);
3563 editor::init_settings(cx);
3564 }
3565}