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