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