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