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