1use crate::{
2 language_model_selector::{LanguageModelSelector, language_model_selector},
3 ui::BurnModeTooltip,
4};
5use agent_settings::CompletionMode;
6use anyhow::Result;
7use assistant_slash_command::{SlashCommand, SlashCommandOutputSection, SlashCommandWorkingSet};
8use assistant_slash_commands::{DefaultSlashCommand, FileSlashCommand, selections_creases};
9use client::{proto, zed_urls};
10use collections::{BTreeSet, HashMap, HashSet, hash_map};
11use editor::{
12 Anchor, Editor, EditorEvent, MenuEditPredictionsPolicy, MultiBuffer, MultiBufferSnapshot,
13 RowExt, ToOffset as _, ToPoint,
14 actions::{MoveToEndOfLine, Newline, ShowCompletions},
15 display_map::{
16 BlockPlacement, BlockProperties, BlockStyle, Crease, CreaseMetadata, CustomBlockId, FoldId,
17 RenderBlock, ToDisplayPoint,
18 },
19 scroll::ScrollOffset,
20};
21use editor::{FoldPlaceholder, display_map::CreaseId};
22use fs::Fs;
23use futures::FutureExt;
24use gpui::{
25 Action, Animation, AnimationExt, AnyElement, AnyView, App, ClipboardEntry, ClipboardItem,
26 Empty, Entity, EventEmitter, FocusHandle, Focusable, FontWeight, Global, InteractiveElement,
27 IntoElement, ParentElement, Pixels, Render, RenderImage, SharedString, Size,
28 StatefulInteractiveElement, Styled, Subscription, Task, WeakEntity, actions, div, img, point,
29 prelude::*, pulsating_between, size,
30};
31use language::{
32 BufferSnapshot, LspAdapterDelegate, ToOffset,
33 language_settings::{SoftWrap, all_language_settings},
34};
35use language_model::{
36 ConfigurationError, LanguageModelExt, LanguageModelImage, LanguageModelRegistry, Role,
37};
38use multi_buffer::MultiBufferRow;
39use picker::{Picker, popover_menu::PickerPopoverMenu};
40use project::{Project, Worktree};
41use project::{ProjectPath, lsp_store::LocalLspAdapterDelegate};
42use rope::Point;
43use serde::{Deserialize, Serialize};
44use settings::{
45 LanguageModelProviderSetting, LanguageModelSelection, Settings, SettingsStore,
46 update_settings_file,
47};
48use std::{
49 any::TypeId,
50 cmp,
51 ops::Range,
52 path::{Path, PathBuf},
53 rc::Rc,
54 sync::Arc,
55 time::Duration,
56};
57use text::SelectionGoal;
58use ui::{
59 ButtonLike, CommonAnimationExt, Disclosure, ElevationIndex, KeyBinding, PopoverMenuHandle,
60 TintColor, Tooltip, prelude::*,
61};
62use util::{ResultExt, maybe};
63use workspace::{
64 CollaboratorId,
65 searchable::{Direction, SearchableItemHandle},
66};
67use workspace::{
68 Save, Toast, Workspace,
69 item::{self, FollowableItem, Item, ItemHandle},
70 notifications::NotificationId,
71 pane,
72 searchable::{SearchEvent, SearchableItem},
73};
74use zed_actions::agent::{AddSelectionToThread, ToggleModelSelector};
75
76use crate::{slash_command::SlashCommandCompletionProvider, slash_command_picker};
77use assistant_text_thread::{
78 CacheStatus, Content, InvokedSlashCommandId, InvokedSlashCommandStatus, Message, MessageId,
79 MessageMetadata, MessageStatus, PendingSlashCommandStatus, TextThread, TextThreadEvent,
80 TextThreadId, ThoughtProcessOutputSection,
81};
82
83actions!(
84 assistant,
85 [
86 /// Sends the current message to the assistant.
87 Assist,
88 /// Confirms and executes the entered slash command.
89 ConfirmCommand,
90 /// Copies code from the assistant's response to the clipboard.
91 CopyCode,
92 /// Cycles between user and assistant message roles.
93 CycleMessageRole,
94 /// Inserts the selected text into the active editor.
95 InsertIntoEditor,
96 /// Splits the conversation at the current cursor position.
97 Split,
98 ]
99);
100
101/// Inserts files that were dragged and dropped into the assistant conversation.
102#[derive(PartialEq, Clone, Action)]
103#[action(namespace = assistant, no_json, no_register)]
104pub enum InsertDraggedFiles {
105 ProjectPaths(Vec<ProjectPath>),
106 ExternalFiles(Vec<PathBuf>),
107}
108
109#[derive(Copy, Clone, Debug, PartialEq)]
110struct ScrollPosition {
111 offset_before_cursor: gpui::Point<ScrollOffset>,
112 cursor: Anchor,
113}
114
115type MessageHeader = MessageMetadata;
116
117#[derive(Clone)]
118enum AssistError {
119 PaymentRequired,
120 Message(SharedString),
121}
122
123pub enum ThoughtProcessStatus {
124 Pending,
125 Completed,
126}
127
128pub trait AgentPanelDelegate {
129 fn active_text_thread_editor(
130 &self,
131 workspace: &mut Workspace,
132 window: &mut Window,
133 cx: &mut Context<Workspace>,
134 ) -> Option<Entity<TextThreadEditor>>;
135
136 fn open_local_text_thread(
137 &self,
138 workspace: &mut Workspace,
139 path: Arc<Path>,
140 window: &mut Window,
141 cx: &mut Context<Workspace>,
142 ) -> Task<Result<()>>;
143
144 fn open_remote_text_thread(
145 &self,
146 workspace: &mut Workspace,
147 text_thread_id: TextThreadId,
148 window: &mut Window,
149 cx: &mut Context<Workspace>,
150 ) -> Task<Result<Entity<TextThreadEditor>>>;
151
152 fn quote_selection(
153 &self,
154 workspace: &mut Workspace,
155 selection_ranges: Vec<Range<Anchor>>,
156 buffer: Entity<MultiBuffer>,
157 window: &mut Window,
158 cx: &mut Context<Workspace>,
159 );
160}
161
162impl dyn AgentPanelDelegate {
163 /// Returns the global [`AssistantPanelDelegate`], if it exists.
164 pub fn try_global(cx: &App) -> Option<Arc<Self>> {
165 cx.try_global::<GlobalAssistantPanelDelegate>()
166 .map(|global| global.0.clone())
167 }
168
169 /// Sets the global [`AssistantPanelDelegate`].
170 pub fn set_global(delegate: Arc<Self>, cx: &mut App) {
171 cx.set_global(GlobalAssistantPanelDelegate(delegate));
172 }
173}
174
175struct GlobalAssistantPanelDelegate(Arc<dyn AgentPanelDelegate>);
176
177impl Global for GlobalAssistantPanelDelegate {}
178
179pub struct TextThreadEditor {
180 text_thread: Entity<TextThread>,
181 fs: Arc<dyn Fs>,
182 slash_commands: Arc<SlashCommandWorkingSet>,
183 workspace: WeakEntity<Workspace>,
184 project: Entity<Project>,
185 lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
186 editor: Entity<Editor>,
187 pending_thought_process: Option<(CreaseId, language::Anchor)>,
188 blocks: HashMap<MessageId, (MessageHeader, CustomBlockId)>,
189 image_blocks: HashSet<CustomBlockId>,
190 scroll_position: Option<ScrollPosition>,
191 remote_id: Option<workspace::ViewId>,
192 pending_slash_command_creases: HashMap<Range<language::Anchor>, CreaseId>,
193 invoked_slash_command_creases: HashMap<InvokedSlashCommandId, CreaseId>,
194 _subscriptions: Vec<Subscription>,
195 last_error: Option<AssistError>,
196 pub(crate) slash_menu_handle:
197 PopoverMenuHandle<Picker<slash_command_picker::SlashCommandDelegate>>,
198 // dragged_file_worktrees is used to keep references to worktrees that were added
199 // when the user drag/dropped an external file onto the context editor. Since
200 // the worktree is not part of the project panel, it would be dropped as soon as
201 // the file is opened. In order to keep the worktree alive for the duration of the
202 // context editor, we keep a reference here.
203 dragged_file_worktrees: Vec<Entity<Worktree>>,
204 language_model_selector: Entity<LanguageModelSelector>,
205 language_model_selector_menu_handle: PopoverMenuHandle<LanguageModelSelector>,
206}
207
208const MAX_TAB_TITLE_LEN: usize = 16;
209
210impl TextThreadEditor {
211 pub fn init(cx: &mut App) {
212 workspace::FollowableViewRegistry::register::<TextThreadEditor>(cx);
213
214 cx.observe_new(
215 |workspace: &mut Workspace, _window, _cx: &mut Context<Workspace>| {
216 workspace
217 .register_action(TextThreadEditor::quote_selection)
218 .register_action(TextThreadEditor::insert_selection)
219 .register_action(TextThreadEditor::copy_code)
220 .register_action(TextThreadEditor::handle_insert_dragged_files);
221 },
222 )
223 .detach();
224 }
225
226 pub fn for_text_thread(
227 text_thread: Entity<TextThread>,
228 fs: Arc<dyn Fs>,
229 workspace: WeakEntity<Workspace>,
230 project: Entity<Project>,
231 lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
232 window: &mut Window,
233 cx: &mut Context<Self>,
234 ) -> Self {
235 let completion_provider = SlashCommandCompletionProvider::new(
236 text_thread.read(cx).slash_commands().clone(),
237 Some(cx.entity().downgrade()),
238 Some(workspace.clone()),
239 );
240
241 let editor = cx.new(|cx| {
242 let mut editor =
243 Editor::for_buffer(text_thread.read(cx).buffer().clone(), None, window, cx);
244 editor.disable_scrollbars_and_minimap(window, cx);
245 editor.set_soft_wrap_mode(SoftWrap::EditorWidth, cx);
246 editor.set_show_line_numbers(false, cx);
247 editor.set_show_git_diff_gutter(false, cx);
248 editor.set_show_code_actions(false, cx);
249 editor.set_show_runnables(false, cx);
250 editor.set_show_breakpoints(false, cx);
251 editor.set_show_wrap_guides(false, cx);
252 editor.set_show_indent_guides(false, cx);
253 editor.set_completion_provider(Some(Rc::new(completion_provider)));
254 editor.set_menu_edit_predictions_policy(MenuEditPredictionsPolicy::Never);
255 editor.set_collaboration_hub(Box::new(project.clone()));
256
257 let show_edit_predictions = all_language_settings(None, cx)
258 .edit_predictions
259 .enabled_in_text_threads;
260
261 editor.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
262
263 editor
264 });
265
266 let _subscriptions = vec![
267 cx.observe(&text_thread, |_, _, cx| cx.notify()),
268 cx.subscribe_in(&text_thread, window, Self::handle_text_thread_event),
269 cx.subscribe_in(&editor, window, Self::handle_editor_event),
270 cx.subscribe_in(&editor, window, Self::handle_editor_search_event),
271 cx.observe_global_in::<SettingsStore>(window, Self::settings_changed),
272 ];
273
274 let slash_command_sections = text_thread
275 .read(cx)
276 .slash_command_output_sections()
277 .to_vec();
278 let thought_process_sections = text_thread
279 .read(cx)
280 .thought_process_output_sections()
281 .to_vec();
282 let slash_commands = text_thread.read(cx).slash_commands().clone();
283 let mut this = Self {
284 text_thread,
285 slash_commands,
286 editor,
287 lsp_adapter_delegate,
288 blocks: Default::default(),
289 image_blocks: Default::default(),
290 scroll_position: None,
291 remote_id: None,
292 pending_thought_process: None,
293 fs: fs.clone(),
294 workspace,
295 project,
296 pending_slash_command_creases: HashMap::default(),
297 invoked_slash_command_creases: HashMap::default(),
298 _subscriptions,
299 last_error: None,
300 slash_menu_handle: Default::default(),
301 dragged_file_worktrees: Vec::new(),
302 language_model_selector: cx.new(|cx| {
303 language_model_selector(
304 |cx| LanguageModelRegistry::read_global(cx).default_model(),
305 move |model, cx| {
306 update_settings_file(fs.clone(), cx, move |settings, _| {
307 let provider = model.provider_id().0.to_string();
308 let model = model.id().0.to_string();
309 settings.agent.get_or_insert_default().set_model(
310 LanguageModelSelection {
311 provider: LanguageModelProviderSetting(provider),
312 model,
313 },
314 )
315 });
316 },
317 window,
318 cx,
319 )
320 }),
321 language_model_selector_menu_handle: PopoverMenuHandle::default(),
322 };
323 this.update_message_headers(cx);
324 this.update_image_blocks(cx);
325 this.insert_slash_command_output_sections(slash_command_sections, false, window, cx);
326 this.insert_thought_process_output_sections(
327 thought_process_sections
328 .into_iter()
329 .map(|section| (section, ThoughtProcessStatus::Completed)),
330 window,
331 cx,
332 );
333 this
334 }
335
336 fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
337 self.editor.update(cx, |editor, cx| {
338 let show_edit_predictions = all_language_settings(None, cx)
339 .edit_predictions
340 .enabled_in_text_threads;
341
342 editor.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
343 });
344 }
345
346 pub fn text_thread(&self) -> &Entity<TextThread> {
347 &self.text_thread
348 }
349
350 pub fn editor(&self) -> &Entity<Editor> {
351 &self.editor
352 }
353
354 pub fn insert_default_prompt(&mut self, window: &mut Window, cx: &mut Context<Self>) {
355 let command_name = DefaultSlashCommand.name();
356 self.editor.update(cx, |editor, cx| {
357 editor.insert(&format!("/{command_name}\n\n"), window, cx)
358 });
359 let command = self.text_thread.update(cx, |text_thread, cx| {
360 text_thread.reparse(cx);
361 text_thread.parsed_slash_commands()[0].clone()
362 });
363 self.run_command(
364 command.source_range,
365 &command.name,
366 &command.arguments,
367 false,
368 self.workspace.clone(),
369 window,
370 cx,
371 );
372 }
373
374 fn assist(&mut self, _: &Assist, window: &mut Window, cx: &mut Context<Self>) {
375 if self.sending_disabled(cx) {
376 return;
377 }
378 telemetry::event!("Agent Message Sent", agent = "zed-text");
379 self.send_to_model(window, cx);
380 }
381
382 fn send_to_model(&mut self, window: &mut Window, cx: &mut Context<Self>) {
383 self.last_error = None;
384 if let Some(user_message) = self
385 .text_thread
386 .update(cx, |text_thread, cx| text_thread.assist(cx))
387 {
388 let new_selection = {
389 let cursor = user_message
390 .start
391 .to_offset(self.text_thread.read(cx).buffer().read(cx));
392 cursor..cursor
393 };
394 self.editor.update(cx, |editor, cx| {
395 editor.change_selections(Default::default(), window, cx, |selections| {
396 selections.select_ranges([new_selection])
397 });
398 });
399 // Avoid scrolling to the new cursor position so the assistant's output is stable.
400 cx.defer_in(window, |this, _, _| this.scroll_position = None);
401 }
402
403 cx.notify();
404 }
405
406 fn cancel(
407 &mut self,
408 _: &editor::actions::Cancel,
409 _window: &mut Window,
410 cx: &mut Context<Self>,
411 ) {
412 self.last_error = None;
413
414 if self
415 .text_thread
416 .update(cx, |text_thread, cx| text_thread.cancel_last_assist(cx))
417 {
418 return;
419 }
420
421 cx.propagate();
422 }
423
424 fn cycle_message_role(
425 &mut self,
426 _: &CycleMessageRole,
427 _window: &mut Window,
428 cx: &mut Context<Self>,
429 ) {
430 let cursors = self.cursors(cx);
431 self.text_thread.update(cx, |text_thread, cx| {
432 let messages = text_thread
433 .messages_for_offsets(cursors, cx)
434 .into_iter()
435 .map(|message| message.id)
436 .collect();
437 text_thread.cycle_message_roles(messages, cx)
438 });
439 }
440
441 fn cursors(&self, cx: &mut App) -> Vec<usize> {
442 let selections = self.editor.update(cx, |editor, cx| {
443 editor.selections.all::<usize>(&editor.display_snapshot(cx))
444 });
445 selections
446 .into_iter()
447 .map(|selection| selection.head())
448 .collect()
449 }
450
451 pub fn insert_command(&mut self, name: &str, window: &mut Window, cx: &mut Context<Self>) {
452 if let Some(command) = self.slash_commands.command(name, cx) {
453 self.editor.update(cx, |editor, cx| {
454 editor.transact(window, cx, |editor, window, cx| {
455 editor.change_selections(Default::default(), window, cx, |s| s.try_cancel());
456 let snapshot = editor.buffer().read(cx).snapshot(cx);
457 let newest_cursor = editor
458 .selections
459 .newest::<Point>(&editor.display_snapshot(cx))
460 .head();
461 if newest_cursor.column > 0
462 || snapshot
463 .chars_at(newest_cursor)
464 .next()
465 .is_some_and(|ch| ch != '\n')
466 {
467 editor.move_to_end_of_line(
468 &MoveToEndOfLine {
469 stop_at_soft_wraps: false,
470 },
471 window,
472 cx,
473 );
474 editor.newline(&Newline, window, cx);
475 }
476
477 editor.insert(&format!("/{name}"), window, cx);
478 if command.accepts_arguments() {
479 editor.insert(" ", window, cx);
480 editor.show_completions(&ShowCompletions::default(), window, cx);
481 }
482 });
483 });
484 if !command.requires_argument() {
485 self.confirm_command(&ConfirmCommand, window, cx);
486 }
487 }
488 }
489
490 pub fn confirm_command(
491 &mut self,
492 _: &ConfirmCommand,
493 window: &mut Window,
494 cx: &mut Context<Self>,
495 ) {
496 if self.editor.read(cx).has_visible_completions_menu() {
497 return;
498 }
499
500 let selections = self.editor.read(cx).selections.disjoint_anchors_arc();
501 let mut commands_by_range = HashMap::default();
502 let workspace = self.workspace.clone();
503 self.text_thread.update(cx, |text_thread, cx| {
504 text_thread.reparse(cx);
505 for selection in selections.iter() {
506 if let Some(command) =
507 text_thread.pending_command_for_position(selection.head().text_anchor, cx)
508 {
509 commands_by_range
510 .entry(command.source_range.clone())
511 .or_insert_with(|| command.clone());
512 }
513 }
514 });
515
516 if commands_by_range.is_empty() {
517 cx.propagate();
518 } else {
519 for command in commands_by_range.into_values() {
520 self.run_command(
521 command.source_range,
522 &command.name,
523 &command.arguments,
524 true,
525 workspace.clone(),
526 window,
527 cx,
528 );
529 }
530 cx.stop_propagation();
531 }
532 }
533
534 pub fn run_command(
535 &mut self,
536 command_range: Range<language::Anchor>,
537 name: &str,
538 arguments: &[String],
539 ensure_trailing_newline: bool,
540 workspace: WeakEntity<Workspace>,
541 window: &mut Window,
542 cx: &mut Context<Self>,
543 ) {
544 if let Some(command) = self.slash_commands.command(name, cx) {
545 let text_thread = self.text_thread.read(cx);
546 let sections = text_thread
547 .slash_command_output_sections()
548 .iter()
549 .filter(|section| section.is_valid(text_thread.buffer().read(cx)))
550 .cloned()
551 .collect::<Vec<_>>();
552 let snapshot = text_thread.buffer().read(cx).snapshot();
553 let output = command.run(
554 arguments,
555 §ions,
556 snapshot,
557 workspace,
558 self.lsp_adapter_delegate.clone(),
559 window,
560 cx,
561 );
562 self.text_thread.update(cx, |text_thread, cx| {
563 text_thread.insert_command_output(
564 command_range,
565 name,
566 output,
567 ensure_trailing_newline,
568 cx,
569 )
570 });
571 }
572 }
573
574 fn handle_text_thread_event(
575 &mut self,
576 _: &Entity<TextThread>,
577 event: &TextThreadEvent,
578 window: &mut Window,
579 cx: &mut Context<Self>,
580 ) {
581 let text_thread_editor = cx.entity().downgrade();
582
583 match event {
584 TextThreadEvent::MessagesEdited => {
585 self.update_message_headers(cx);
586 self.update_image_blocks(cx);
587 self.text_thread.update(cx, |text_thread, cx| {
588 text_thread.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
589 });
590 }
591 TextThreadEvent::SummaryChanged => {
592 cx.emit(EditorEvent::TitleChanged);
593 self.text_thread.update(cx, |text_thread, cx| {
594 text_thread.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
595 });
596 }
597 TextThreadEvent::SummaryGenerated => {}
598 TextThreadEvent::PathChanged { .. } => {}
599 TextThreadEvent::StartedThoughtProcess(range) => {
600 let creases = self.insert_thought_process_output_sections(
601 [(
602 ThoughtProcessOutputSection {
603 range: range.clone(),
604 },
605 ThoughtProcessStatus::Pending,
606 )],
607 window,
608 cx,
609 );
610 self.pending_thought_process = Some((creases[0], range.start));
611 }
612 TextThreadEvent::EndedThoughtProcess(end) => {
613 if let Some((crease_id, start)) = self.pending_thought_process.take() {
614 self.editor.update(cx, |editor, cx| {
615 let multi_buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
616 let start_anchor =
617 multi_buffer_snapshot.as_singleton_anchor(start).unwrap();
618
619 editor.display_map.update(cx, |display_map, cx| {
620 display_map.unfold_intersecting(
621 vec![start_anchor..start_anchor],
622 true,
623 cx,
624 );
625 });
626 editor.remove_creases(vec![crease_id], cx);
627 });
628 self.insert_thought_process_output_sections(
629 [(
630 ThoughtProcessOutputSection { range: start..*end },
631 ThoughtProcessStatus::Completed,
632 )],
633 window,
634 cx,
635 );
636 }
637 }
638 TextThreadEvent::StreamedCompletion => {
639 self.editor.update(cx, |editor, cx| {
640 if let Some(scroll_position) = self.scroll_position {
641 let snapshot = editor.snapshot(window, cx);
642 let cursor_point = scroll_position.cursor.to_display_point(&snapshot);
643 let scroll_top =
644 cursor_point.row().as_f64() - scroll_position.offset_before_cursor.y;
645 editor.set_scroll_position(
646 point(scroll_position.offset_before_cursor.x, scroll_top),
647 window,
648 cx,
649 );
650 }
651 });
652 }
653 TextThreadEvent::ParsedSlashCommandsUpdated { removed, updated } => {
654 self.editor.update(cx, |editor, cx| {
655 let buffer = editor.buffer().read(cx).snapshot(cx);
656 let (&excerpt_id, _, _) = buffer.as_singleton().unwrap();
657
658 editor.remove_creases(
659 removed
660 .iter()
661 .filter_map(|range| self.pending_slash_command_creases.remove(range)),
662 cx,
663 );
664
665 let crease_ids = editor.insert_creases(
666 updated.iter().map(|command| {
667 let workspace = self.workspace.clone();
668 let confirm_command = Arc::new({
669 let text_thread_editor = text_thread_editor.clone();
670 let command = command.clone();
671 move |window: &mut Window, cx: &mut App| {
672 text_thread_editor
673 .update(cx, |text_thread_editor, cx| {
674 text_thread_editor.run_command(
675 command.source_range.clone(),
676 &command.name,
677 &command.arguments,
678 false,
679 workspace.clone(),
680 window,
681 cx,
682 );
683 })
684 .ok();
685 }
686 });
687 let placeholder = FoldPlaceholder {
688 render: Arc::new(move |_, _, _| Empty.into_any()),
689 ..Default::default()
690 };
691 let render_toggle = {
692 let confirm_command = confirm_command.clone();
693 let command = command.clone();
694 move |row, _, _, _window: &mut Window, _cx: &mut App| {
695 render_pending_slash_command_gutter_decoration(
696 row,
697 &command.status,
698 confirm_command.clone(),
699 )
700 }
701 };
702 let render_trailer = {
703 move |_row, _unfold, _window: &mut Window, _cx: &mut App| {
704 Empty.into_any()
705 }
706 };
707
708 let range = buffer
709 .anchor_range_in_excerpt(excerpt_id, command.source_range.clone())
710 .unwrap();
711 Crease::inline(range, placeholder, render_toggle, render_trailer)
712 }),
713 cx,
714 );
715
716 self.pending_slash_command_creases.extend(
717 updated
718 .iter()
719 .map(|command| command.source_range.clone())
720 .zip(crease_ids),
721 );
722 })
723 }
724 TextThreadEvent::InvokedSlashCommandChanged { command_id } => {
725 self.update_invoked_slash_command(*command_id, window, cx);
726 }
727 TextThreadEvent::SlashCommandOutputSectionAdded { section } => {
728 self.insert_slash_command_output_sections([section.clone()], false, window, cx);
729 }
730 TextThreadEvent::Operation(_) => {}
731 TextThreadEvent::ShowAssistError(error_message) => {
732 self.last_error = Some(AssistError::Message(error_message.clone()));
733 }
734 TextThreadEvent::ShowPaymentRequiredError => {
735 self.last_error = Some(AssistError::PaymentRequired);
736 }
737 }
738 }
739
740 fn update_invoked_slash_command(
741 &mut self,
742 command_id: InvokedSlashCommandId,
743 window: &mut Window,
744 cx: &mut Context<Self>,
745 ) {
746 if let Some(invoked_slash_command) =
747 self.text_thread.read(cx).invoked_slash_command(&command_id)
748 && let InvokedSlashCommandStatus::Finished = invoked_slash_command.status
749 {
750 let run_commands_in_ranges = invoked_slash_command.run_commands_in_ranges.clone();
751 for range in run_commands_in_ranges {
752 let commands = self.text_thread.update(cx, |text_thread, cx| {
753 text_thread.reparse(cx);
754 text_thread
755 .pending_commands_for_range(range.clone(), cx)
756 .to_vec()
757 });
758
759 for command in commands {
760 self.run_command(
761 command.source_range,
762 &command.name,
763 &command.arguments,
764 false,
765 self.workspace.clone(),
766 window,
767 cx,
768 );
769 }
770 }
771 }
772
773 self.editor.update(cx, |editor, cx| {
774 if let Some(invoked_slash_command) =
775 self.text_thread.read(cx).invoked_slash_command(&command_id)
776 {
777 if let InvokedSlashCommandStatus::Finished = invoked_slash_command.status {
778 let buffer = editor.buffer().read(cx).snapshot(cx);
779 let (&excerpt_id, _buffer_id, _buffer_snapshot) =
780 buffer.as_singleton().unwrap();
781
782 let range = buffer
783 .anchor_range_in_excerpt(excerpt_id, invoked_slash_command.range.clone())
784 .unwrap();
785 editor.remove_folds_with_type(
786 &[range],
787 TypeId::of::<PendingSlashCommand>(),
788 false,
789 cx,
790 );
791
792 editor.remove_creases(
793 HashSet::from_iter(self.invoked_slash_command_creases.remove(&command_id)),
794 cx,
795 );
796 } else if let hash_map::Entry::Vacant(entry) =
797 self.invoked_slash_command_creases.entry(command_id)
798 {
799 let buffer = editor.buffer().read(cx).snapshot(cx);
800 let (&excerpt_id, _buffer_id, _buffer_snapshot) =
801 buffer.as_singleton().unwrap();
802 let context = self.text_thread.downgrade();
803 let range = buffer
804 .anchor_range_in_excerpt(excerpt_id, invoked_slash_command.range.clone())
805 .unwrap();
806 let crease = Crease::inline(
807 range,
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 range = buffer
846 .anchor_range_in_excerpt(excerpt_id, section.range)
847 .unwrap();
848 let buffer_row = MultiBufferRow(range.start.to_point(&buffer).row);
849 buffer_rows_to_fold.insert(buffer_row);
850 creases.push(
851 Crease::inline(
852 range,
853 FoldPlaceholder {
854 render: render_thought_process_fold_icon_button(
855 cx.entity().downgrade(),
856 status,
857 ),
858 merge_adjacent: false,
859 ..Default::default()
860 },
861 render_slash_command_output_toggle,
862 |_, _, _, _| Empty.into_any_element(),
863 )
864 .with_metadata(CreaseMetadata {
865 icon_path: SharedString::from(IconName::Ai.path()),
866 label: "Thinking Process".into(),
867 }),
868 );
869 }
870
871 let creases = editor.insert_creases(creases, cx);
872
873 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
874 editor.fold_at(buffer_row, window, cx);
875 }
876
877 creases
878 })
879 }
880
881 fn insert_slash_command_output_sections(
882 &mut self,
883 sections: impl IntoIterator<Item = SlashCommandOutputSection<language::Anchor>>,
884 expand_result: bool,
885 window: &mut Window,
886 cx: &mut Context<Self>,
887 ) {
888 self.editor.update(cx, |editor, cx| {
889 let buffer = editor.buffer().read(cx).snapshot(cx);
890 let excerpt_id = *buffer.as_singleton().unwrap().0;
891 let mut buffer_rows_to_fold = BTreeSet::new();
892 let mut creases = Vec::new();
893 for section in sections {
894 let range = buffer
895 .anchor_range_in_excerpt(excerpt_id, section.range)
896 .unwrap();
897 let buffer_row = MultiBufferRow(range.start.to_point(&buffer).row);
898 buffer_rows_to_fold.insert(buffer_row);
899 creases.push(
900 Crease::inline(
901 range,
902 FoldPlaceholder {
903 render: render_fold_icon_button(
904 cx.entity().downgrade(),
905 section.icon.path().into(),
906 section.label.clone(),
907 ),
908 merge_adjacent: false,
909 ..Default::default()
910 },
911 render_slash_command_output_toggle,
912 |_, _, _, _| Empty.into_any_element(),
913 )
914 .with_metadata(CreaseMetadata {
915 icon_path: section.icon.path().into(),
916 label: section.label,
917 }),
918 );
919 }
920
921 editor.insert_creases(creases, cx);
922
923 if expand_result {
924 buffer_rows_to_fold.clear();
925 }
926 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
927 editor.fold_at(buffer_row, window, cx);
928 }
929 });
930 }
931
932 fn handle_editor_event(
933 &mut self,
934 _: &Entity<Editor>,
935 event: &EditorEvent,
936 window: &mut Window,
937 cx: &mut Context<Self>,
938 ) {
939 match event {
940 EditorEvent::ScrollPositionChanged { autoscroll, .. } => {
941 let cursor_scroll_position = self.cursor_scroll_position(window, cx);
942 if *autoscroll {
943 self.scroll_position = cursor_scroll_position;
944 } else if self.scroll_position != cursor_scroll_position {
945 self.scroll_position = None;
946 }
947 }
948 EditorEvent::SelectionsChanged { .. } => {
949 self.scroll_position = self.cursor_scroll_position(window, cx);
950 }
951 _ => {}
952 }
953 cx.emit(event.clone());
954 }
955
956 fn handle_editor_search_event(
957 &mut self,
958 _: &Entity<Editor>,
959 event: &SearchEvent,
960 _window: &mut Window,
961 cx: &mut Context<Self>,
962 ) {
963 cx.emit(event.clone());
964 }
965
966 fn cursor_scroll_position(
967 &self,
968 window: &mut Window,
969 cx: &mut Context<Self>,
970 ) -> Option<ScrollPosition> {
971 self.editor.update(cx, |editor, cx| {
972 let snapshot = editor.snapshot(window, cx);
973 let cursor = editor.selections.newest_anchor().head();
974 let cursor_row = cursor
975 .to_display_point(&snapshot.display_snapshot)
976 .row()
977 .as_f64();
978 let scroll_position = editor
979 .scroll_manager
980 .anchor()
981 .scroll_position(&snapshot.display_snapshot);
982
983 let scroll_bottom = scroll_position.y + editor.visible_line_count().unwrap_or(0.);
984 if (scroll_position.y..scroll_bottom).contains(&cursor_row) {
985 Some(ScrollPosition {
986 cursor,
987 offset_before_cursor: point(scroll_position.x, cursor_row - scroll_position.y),
988 })
989 } else {
990 None
991 }
992 })
993 }
994
995 fn esc_kbd(cx: &App) -> Div {
996 let colors = cx.theme().colors().clone();
997
998 h_flex()
999 .items_center()
1000 .gap_1()
1001 .font(theme::ThemeSettings::get_global(cx).buffer_font.clone())
1002 .text_size(TextSize::XSmall.rems(cx))
1003 .text_color(colors.text_muted)
1004 .child("Press")
1005 .child(
1006 h_flex()
1007 .rounded_sm()
1008 .px_1()
1009 .mr_0p5()
1010 .border_1()
1011 .border_color(colors.border_variant.alpha(0.6))
1012 .bg(colors.element_background.alpha(0.6))
1013 .child("esc"),
1014 )
1015 .child("to cancel")
1016 }
1017
1018 fn update_message_headers(&mut self, cx: &mut Context<Self>) {
1019 self.editor.update(cx, |editor, cx| {
1020 let buffer = editor.buffer().read(cx).snapshot(cx);
1021
1022 let excerpt_id = *buffer.as_singleton().unwrap().0;
1023 let mut old_blocks = std::mem::take(&mut self.blocks);
1024 let mut blocks_to_remove: HashMap<_, _> = old_blocks
1025 .iter()
1026 .map(|(message_id, (_, block_id))| (*message_id, *block_id))
1027 .collect();
1028 let mut blocks_to_replace: HashMap<_, RenderBlock> = Default::default();
1029
1030 let render_block = |message: MessageMetadata| -> RenderBlock {
1031 Arc::new({
1032 let text_thread = self.text_thread.clone();
1033
1034 move |cx| {
1035 let message_id = MessageId(message.timestamp);
1036 let llm_loading = message.role == Role::Assistant
1037 && message.status == MessageStatus::Pending;
1038
1039 let (label, spinner, note) = match message.role {
1040 Role::User => (
1041 Label::new("You").color(Color::Default).into_any_element(),
1042 None,
1043 None,
1044 ),
1045 Role::Assistant => {
1046 let base_label = Label::new("Agent").color(Color::Info);
1047 let mut spinner = None;
1048 let mut note = None;
1049 let animated_label = if llm_loading {
1050 base_label
1051 .with_animation(
1052 "pulsating-label",
1053 Animation::new(Duration::from_secs(2))
1054 .repeat()
1055 .with_easing(pulsating_between(0.4, 0.8)),
1056 |label, delta| label.alpha(delta),
1057 )
1058 .into_any_element()
1059 } else {
1060 base_label.into_any_element()
1061 };
1062 if llm_loading {
1063 spinner = Some(
1064 Icon::new(IconName::ArrowCircle)
1065 .size(IconSize::XSmall)
1066 .color(Color::Info)
1067 .with_rotate_animation(2)
1068 .into_any_element(),
1069 );
1070 note = Some(Self::esc_kbd(cx).into_any_element());
1071 }
1072 (animated_label, spinner, note)
1073 }
1074 Role::System => (
1075 Label::new("System")
1076 .color(Color::Warning)
1077 .into_any_element(),
1078 None,
1079 None,
1080 ),
1081 };
1082
1083 let sender = h_flex()
1084 .items_center()
1085 .gap_2p5()
1086 .child(
1087 ButtonLike::new("role")
1088 .style(ButtonStyle::Filled)
1089 .child(
1090 h_flex()
1091 .items_center()
1092 .gap_1p5()
1093 .child(label)
1094 .children(spinner),
1095 )
1096 .tooltip(|_window, cx| {
1097 Tooltip::with_meta(
1098 "Toggle message role",
1099 None,
1100 "Available roles: You (User), Agent, System",
1101 cx,
1102 )
1103 })
1104 .on_click({
1105 let text_thread = text_thread.clone();
1106 move |_, _window, cx| {
1107 text_thread.update(cx, |text_thread, cx| {
1108 text_thread.cycle_message_roles(
1109 HashSet::from_iter(Some(message_id)),
1110 cx,
1111 )
1112 })
1113 }
1114 }),
1115 )
1116 .children(note);
1117
1118 h_flex()
1119 .id(("message_header", message_id.as_u64()))
1120 .pl(cx.margins.gutter.full_width())
1121 .h_11()
1122 .w_full()
1123 .relative()
1124 .gap_1p5()
1125 .child(sender)
1126 .children(match &message.cache {
1127 Some(cache) if cache.is_final_anchor => match cache.status {
1128 CacheStatus::Cached => Some(
1129 div()
1130 .id("cached")
1131 .child(
1132 Icon::new(IconName::DatabaseZap)
1133 .size(IconSize::XSmall)
1134 .color(Color::Hint),
1135 )
1136 .tooltip(|_window, cx| {
1137 Tooltip::with_meta(
1138 "Context Cached",
1139 None,
1140 "Large messages cached to optimize performance",
1141 cx,
1142 )
1143 })
1144 .into_any_element(),
1145 ),
1146 CacheStatus::Pending => Some(
1147 div()
1148 .child(
1149 Icon::new(IconName::Ellipsis)
1150 .size(IconSize::XSmall)
1151 .color(Color::Hint),
1152 )
1153 .into_any_element(),
1154 ),
1155 },
1156 _ => None,
1157 })
1158 .children(match &message.status {
1159 MessageStatus::Error(error) => Some(
1160 Button::new("show-error", "Error")
1161 .color(Color::Error)
1162 .selected_label_color(Color::Error)
1163 .selected_icon_color(Color::Error)
1164 .icon(IconName::XCircle)
1165 .icon_color(Color::Error)
1166 .icon_size(IconSize::XSmall)
1167 .icon_position(IconPosition::Start)
1168 .tooltip(Tooltip::text("View Details"))
1169 .on_click({
1170 let text_thread = text_thread.clone();
1171 let error = error.clone();
1172 move |_, _window, cx| {
1173 text_thread.update(cx, |_, cx| {
1174 cx.emit(TextThreadEvent::ShowAssistError(
1175 error.clone(),
1176 ));
1177 });
1178 }
1179 })
1180 .into_any_element(),
1181 ),
1182 MessageStatus::Canceled => Some(
1183 h_flex()
1184 .gap_1()
1185 .items_center()
1186 .child(
1187 Icon::new(IconName::XCircle)
1188 .color(Color::Disabled)
1189 .size(IconSize::XSmall),
1190 )
1191 .child(
1192 Label::new("Canceled")
1193 .size(LabelSize::Small)
1194 .color(Color::Disabled),
1195 )
1196 .into_any_element(),
1197 ),
1198 _ => None,
1199 })
1200 .into_any_element()
1201 }
1202 })
1203 };
1204 let create_block_properties = |message: &Message| BlockProperties {
1205 height: Some(2),
1206 style: BlockStyle::Sticky,
1207 placement: BlockPlacement::Above(
1208 buffer
1209 .anchor_in_excerpt(excerpt_id, message.anchor_range.start)
1210 .unwrap(),
1211 ),
1212 priority: usize::MAX,
1213 render: render_block(MessageMetadata::from(message)),
1214 };
1215 let mut new_blocks = vec![];
1216 let mut block_index_to_message = vec![];
1217 for message in self.text_thread.read(cx).messages(cx) {
1218 if blocks_to_remove.remove(&message.id).is_some() {
1219 // This is an old message that we might modify.
1220 let Some((meta, block_id)) = old_blocks.get_mut(&message.id) else {
1221 debug_assert!(
1222 false,
1223 "old_blocks should contain a message_id we've just removed."
1224 );
1225 continue;
1226 };
1227 // Should we modify it?
1228 let message_meta = MessageMetadata::from(&message);
1229 if meta != &message_meta {
1230 blocks_to_replace.insert(*block_id, render_block(message_meta.clone()));
1231 *meta = message_meta;
1232 }
1233 } else {
1234 // This is a new message.
1235 new_blocks.push(create_block_properties(&message));
1236 block_index_to_message.push((message.id, MessageMetadata::from(&message)));
1237 }
1238 }
1239 editor.replace_blocks(blocks_to_replace, None, cx);
1240 editor.remove_blocks(blocks_to_remove.into_values().collect(), None, cx);
1241
1242 let ids = editor.insert_blocks(new_blocks, None, cx);
1243 old_blocks.extend(ids.into_iter().zip(block_index_to_message).map(
1244 |(block_id, (message_id, message_meta))| (message_id, (message_meta, block_id)),
1245 ));
1246 self.blocks = old_blocks;
1247 });
1248 }
1249
1250 /// Returns either the selected text, or the content of the Markdown code
1251 /// block surrounding the cursor.
1252 fn get_selection_or_code_block(
1253 context_editor_view: &Entity<TextThreadEditor>,
1254 cx: &mut Context<Workspace>,
1255 ) -> Option<(String, bool)> {
1256 const CODE_FENCE_DELIMITER: &str = "```";
1257
1258 let text_thread_editor = context_editor_view.read(cx).editor.clone();
1259 text_thread_editor.update(cx, |text_thread_editor, cx| {
1260 let display_map = text_thread_editor.display_snapshot(cx);
1261 if text_thread_editor
1262 .selections
1263 .newest::<Point>(&display_map)
1264 .is_empty()
1265 {
1266 let snapshot = text_thread_editor.buffer().read(cx).snapshot(cx);
1267 let (_, _, snapshot) = snapshot.as_singleton()?;
1268
1269 let head = text_thread_editor
1270 .selections
1271 .newest::<Point>(&display_map)
1272 .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 = text_thread_editor.selections.newest_adjusted(&display_map);
1290 let buffer = text_thread_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_text_thread_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_text_thread_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_text_thread_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 _: &AddSelectionToThread,
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(&editor.display_snapshot(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
1510 .selections
1511 .newest::<Point>(&editor.display_snapshot(cx))
1512 .head();
1513 let start_row = MultiBufferRow(point.row);
1514
1515 editor.insert(&text, window, cx);
1516
1517 let snapshot = editor.buffer().read(cx).snapshot(cx);
1518 let anchor_before = snapshot.anchor_after(point);
1519 let anchor_after = editor
1520 .selections
1521 .newest_anchor()
1522 .head()
1523 .bias_left(&snapshot);
1524
1525 editor.insert("\n", window, cx);
1526
1527 let fold_placeholder =
1528 quote_selection_fold_placeholder(crease_title, cx.entity().downgrade());
1529 let crease = Crease::inline(
1530 anchor_before..anchor_after,
1531 fold_placeholder,
1532 render_quote_selection_output_toggle,
1533 |_, _, _, _| Empty.into_any(),
1534 );
1535 editor.insert_creases(vec![crease], cx);
1536 editor.fold_at(start_row, window, cx);
1537 }
1538 })
1539 }
1540
1541 fn copy(&mut self, _: &editor::actions::Copy, _window: &mut Window, cx: &mut Context<Self>) {
1542 if self.editor.read(cx).selections.count() == 1 {
1543 let (copied_text, metadata, _) = self.get_clipboard_contents(cx);
1544 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1545 copied_text,
1546 metadata,
1547 ));
1548 cx.stop_propagation();
1549 return;
1550 }
1551
1552 cx.propagate();
1553 }
1554
1555 fn cut(&mut self, _: &editor::actions::Cut, window: &mut Window, cx: &mut Context<Self>) {
1556 if self.editor.read(cx).selections.count() == 1 {
1557 let (copied_text, metadata, selections) = self.get_clipboard_contents(cx);
1558
1559 self.editor.update(cx, |editor, cx| {
1560 editor.transact(window, cx, |this, window, cx| {
1561 this.change_selections(Default::default(), window, cx, |s| {
1562 s.select(selections);
1563 });
1564 this.insert("", window, cx);
1565 cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1566 copied_text,
1567 metadata,
1568 ));
1569 });
1570 });
1571
1572 cx.stop_propagation();
1573 return;
1574 }
1575
1576 cx.propagate();
1577 }
1578
1579 fn get_clipboard_contents(
1580 &mut self,
1581 cx: &mut Context<Self>,
1582 ) -> (String, CopyMetadata, Vec<text::Selection<usize>>) {
1583 let (mut selection, creases) = self.editor.update(cx, |editor, cx| {
1584 let mut selection = editor
1585 .selections
1586 .newest_adjusted(&editor.display_snapshot(cx));
1587 let snapshot = editor.buffer().read(cx).snapshot(cx);
1588
1589 selection.goal = SelectionGoal::None;
1590
1591 let selection_start = snapshot.point_to_offset(selection.start);
1592
1593 (
1594 selection.map(|point| snapshot.point_to_offset(point)),
1595 editor.display_map.update(cx, |display_map, cx| {
1596 display_map
1597 .snapshot(cx)
1598 .crease_snapshot
1599 .creases_in_range(
1600 MultiBufferRow(selection.start.row)
1601 ..MultiBufferRow(selection.end.row + 1),
1602 &snapshot,
1603 )
1604 .filter_map(|crease| {
1605 if let Crease::Inline {
1606 range, metadata, ..
1607 } = &crease
1608 {
1609 let metadata = metadata.as_ref()?;
1610 let start = range
1611 .start
1612 .to_offset(&snapshot)
1613 .saturating_sub(selection_start);
1614 let end = range
1615 .end
1616 .to_offset(&snapshot)
1617 .saturating_sub(selection_start);
1618
1619 let range_relative_to_selection = start..end;
1620 if !range_relative_to_selection.is_empty() {
1621 return Some(SelectedCreaseMetadata {
1622 range_relative_to_selection,
1623 crease: metadata.clone(),
1624 });
1625 }
1626 }
1627 None
1628 })
1629 .collect::<Vec<_>>()
1630 }),
1631 )
1632 });
1633
1634 let text_thread = self.text_thread.read(cx);
1635
1636 let mut text = String::new();
1637
1638 // If selection is empty, we want to copy the entire line
1639 if selection.range().is_empty() {
1640 let snapshot = text_thread.buffer().read(cx).snapshot();
1641 let point = snapshot.offset_to_point(selection.range().start);
1642 selection.start = snapshot.point_to_offset(Point::new(point.row, 0));
1643 selection.end = snapshot
1644 .point_to_offset(cmp::min(Point::new(point.row + 1, 0), snapshot.max_point()));
1645 for chunk in text_thread
1646 .buffer()
1647 .read(cx)
1648 .text_for_range(selection.range())
1649 {
1650 text.push_str(chunk);
1651 }
1652 } else {
1653 for message in text_thread.messages(cx) {
1654 if message.offset_range.start >= selection.range().end {
1655 break;
1656 } else if message.offset_range.end >= selection.range().start {
1657 let range = cmp::max(message.offset_range.start, selection.range().start)
1658 ..cmp::min(message.offset_range.end, selection.range().end);
1659 if !range.is_empty() {
1660 for chunk in text_thread.buffer().read(cx).text_for_range(range) {
1661 text.push_str(chunk);
1662 }
1663 if message.offset_range.end < selection.range().end {
1664 text.push('\n');
1665 }
1666 }
1667 }
1668 }
1669 }
1670 (text, CopyMetadata { creases }, vec![selection])
1671 }
1672
1673 fn paste(
1674 &mut self,
1675 action: &editor::actions::Paste,
1676 window: &mut Window,
1677 cx: &mut Context<Self>,
1678 ) {
1679 cx.stop_propagation();
1680
1681 let images = if let Some(item) = cx.read_from_clipboard() {
1682 item.into_entries()
1683 .filter_map(|entry| {
1684 if let ClipboardEntry::Image(image) = entry {
1685 Some(image)
1686 } else {
1687 None
1688 }
1689 })
1690 .collect()
1691 } else {
1692 Vec::new()
1693 };
1694
1695 let metadata = if let Some(item) = cx.read_from_clipboard() {
1696 item.entries().first().and_then(|entry| {
1697 if let ClipboardEntry::String(text) = entry {
1698 text.metadata_json::<CopyMetadata>()
1699 } else {
1700 None
1701 }
1702 })
1703 } else {
1704 None
1705 };
1706
1707 if images.is_empty() {
1708 self.editor.update(cx, |editor, cx| {
1709 let paste_position = editor
1710 .selections
1711 .newest::<usize>(&editor.display_snapshot(cx))
1712 .head();
1713 editor.paste(action, window, cx);
1714
1715 if let Some(metadata) = metadata {
1716 let buffer = editor.buffer().read(cx).snapshot(cx);
1717
1718 let mut buffer_rows_to_fold = BTreeSet::new();
1719 let weak_editor = cx.entity().downgrade();
1720 editor.insert_creases(
1721 metadata.creases.into_iter().map(|metadata| {
1722 let start = buffer.anchor_after(
1723 paste_position + metadata.range_relative_to_selection.start,
1724 );
1725 let end = buffer.anchor_before(
1726 paste_position + metadata.range_relative_to_selection.end,
1727 );
1728
1729 let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1730 buffer_rows_to_fold.insert(buffer_row);
1731 Crease::inline(
1732 start..end,
1733 FoldPlaceholder {
1734 render: render_fold_icon_button(
1735 weak_editor.clone(),
1736 metadata.crease.icon_path.clone(),
1737 metadata.crease.label.clone(),
1738 ),
1739 ..Default::default()
1740 },
1741 render_slash_command_output_toggle,
1742 |_, _, _, _| Empty.into_any(),
1743 )
1744 .with_metadata(metadata.crease)
1745 }),
1746 cx,
1747 );
1748 for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1749 editor.fold_at(buffer_row, window, cx);
1750 }
1751 }
1752 });
1753 } else {
1754 let mut image_positions = Vec::new();
1755 self.editor.update(cx, |editor, cx| {
1756 editor.transact(window, cx, |editor, _window, cx| {
1757 let edits = editor
1758 .selections
1759 .all::<usize>(&editor.display_snapshot(cx))
1760 .into_iter()
1761 .map(|selection| (selection.start..selection.end, "\n"));
1762 editor.edit(edits, cx);
1763
1764 let snapshot = editor.buffer().read(cx).snapshot(cx);
1765 for selection in editor.selections.all::<usize>(&editor.display_snapshot(cx)) {
1766 image_positions.push(snapshot.anchor_before(selection.end));
1767 }
1768 });
1769 });
1770
1771 self.text_thread.update(cx, |text_thread, cx| {
1772 for image in images {
1773 let Some(render_image) = image.to_image_data(cx.svg_renderer()).log_err()
1774 else {
1775 continue;
1776 };
1777 let image_id = image.id();
1778 let image_task = LanguageModelImage::from_image(Arc::new(image), cx).shared();
1779
1780 for image_position in image_positions.iter() {
1781 text_thread.insert_content(
1782 Content::Image {
1783 anchor: image_position.text_anchor,
1784 image_id,
1785 image: image_task.clone(),
1786 render_image: render_image.clone(),
1787 },
1788 cx,
1789 );
1790 }
1791 }
1792 });
1793 }
1794 }
1795
1796 fn update_image_blocks(&mut self, cx: &mut Context<Self>) {
1797 self.editor.update(cx, |editor, cx| {
1798 let buffer = editor.buffer().read(cx).snapshot(cx);
1799 let excerpt_id = *buffer.as_singleton().unwrap().0;
1800 let old_blocks = std::mem::take(&mut self.image_blocks);
1801 let new_blocks = self
1802 .text_thread
1803 .read(cx)
1804 .contents(cx)
1805 .map(
1806 |Content::Image {
1807 anchor,
1808 render_image,
1809 ..
1810 }| (anchor, render_image),
1811 )
1812 .filter_map(|(anchor, render_image)| {
1813 const MAX_HEIGHT_IN_LINES: u32 = 8;
1814 let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
1815 let image = render_image;
1816 anchor.is_valid(&buffer).then(|| BlockProperties {
1817 placement: BlockPlacement::Above(anchor),
1818 height: Some(MAX_HEIGHT_IN_LINES),
1819 style: BlockStyle::Sticky,
1820 render: Arc::new(move |cx| {
1821 let image_size = size_for_image(
1822 &image,
1823 size(
1824 cx.max_width - cx.margins.gutter.full_width(),
1825 MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
1826 ),
1827 );
1828 h_flex()
1829 .pl(cx.margins.gutter.full_width())
1830 .child(
1831 img(image.clone())
1832 .object_fit(gpui::ObjectFit::ScaleDown)
1833 .w(image_size.width)
1834 .h(image_size.height),
1835 )
1836 .into_any_element()
1837 }),
1838 priority: 0,
1839 })
1840 })
1841 .collect::<Vec<_>>();
1842
1843 editor.remove_blocks(old_blocks, None, cx);
1844 let ids = editor.insert_blocks(new_blocks, None, cx);
1845 self.image_blocks = HashSet::from_iter(ids);
1846 });
1847 }
1848
1849 fn split(&mut self, _: &Split, _window: &mut Window, cx: &mut Context<Self>) {
1850 self.text_thread.update(cx, |text_thread, cx| {
1851 let selections = self.editor.read(cx).selections.disjoint_anchors_arc();
1852 for selection in selections.as_ref() {
1853 let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
1854 let range = selection
1855 .map(|endpoint| endpoint.to_offset(&buffer))
1856 .range();
1857 text_thread.split_message(range, cx);
1858 }
1859 });
1860 }
1861
1862 fn save(&mut self, _: &Save, _window: &mut Window, cx: &mut Context<Self>) {
1863 self.text_thread.update(cx, |text_thread, cx| {
1864 text_thread.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
1865 });
1866 }
1867
1868 pub fn title(&self, cx: &App) -> SharedString {
1869 self.text_thread.read(cx).summary().or_default()
1870 }
1871
1872 pub fn regenerate_summary(&mut self, cx: &mut Context<Self>) {
1873 self.text_thread
1874 .update(cx, |text_thread, cx| text_thread.summarize(true, cx));
1875 }
1876
1877 fn render_remaining_tokens(&self, cx: &App) -> Option<impl IntoElement + use<>> {
1878 let (token_count_color, token_count, max_token_count, tooltip) =
1879 match token_state(&self.text_thread, cx)? {
1880 TokenState::NoTokensLeft {
1881 max_token_count,
1882 token_count,
1883 } => (
1884 Color::Error,
1885 token_count,
1886 max_token_count,
1887 Some("Token Limit Reached"),
1888 ),
1889 TokenState::HasMoreTokens {
1890 max_token_count,
1891 token_count,
1892 over_warn_threshold,
1893 } => {
1894 let (color, tooltip) = if over_warn_threshold {
1895 (Color::Warning, Some("Token Limit is Close to Exhaustion"))
1896 } else {
1897 (Color::Muted, None)
1898 };
1899 (color, token_count, max_token_count, tooltip)
1900 }
1901 };
1902
1903 Some(
1904 h_flex()
1905 .id("token-count")
1906 .gap_0p5()
1907 .child(
1908 Label::new(humanize_token_count(token_count))
1909 .size(LabelSize::Small)
1910 .color(token_count_color),
1911 )
1912 .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
1913 .child(
1914 Label::new(humanize_token_count(max_token_count))
1915 .size(LabelSize::Small)
1916 .color(Color::Muted),
1917 )
1918 .when_some(tooltip, |element, tooltip| {
1919 element.tooltip(Tooltip::text(tooltip))
1920 }),
1921 )
1922 }
1923
1924 fn render_send_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1925 let focus_handle = self.focus_handle(cx);
1926
1927 let (style, tooltip) = match token_state(&self.text_thread, cx) {
1928 Some(TokenState::NoTokensLeft { .. }) => (
1929 ButtonStyle::Tinted(TintColor::Error),
1930 Some(Tooltip::text("Token limit reached")(window, cx)),
1931 ),
1932 Some(TokenState::HasMoreTokens {
1933 over_warn_threshold,
1934 ..
1935 }) => {
1936 let (style, tooltip) = if over_warn_threshold {
1937 (
1938 ButtonStyle::Tinted(TintColor::Warning),
1939 Some(Tooltip::text("Token limit is close to exhaustion")(
1940 window, cx,
1941 )),
1942 )
1943 } else {
1944 (ButtonStyle::Filled, None)
1945 };
1946 (style, tooltip)
1947 }
1948 None => (ButtonStyle::Filled, None),
1949 };
1950
1951 Button::new("send_button", "Send")
1952 .label_size(LabelSize::Small)
1953 .disabled(self.sending_disabled(cx))
1954 .style(style)
1955 .when_some(tooltip, |button, tooltip| {
1956 button.tooltip(move |_, _| tooltip.clone())
1957 })
1958 .layer(ElevationIndex::ModalSurface)
1959 .key_binding(
1960 KeyBinding::for_action_in(&Assist, &focus_handle, cx)
1961 .map(|kb| kb.size(rems_from_px(12.))),
1962 )
1963 .on_click(move |_event, window, cx| {
1964 focus_handle.dispatch_action(&Assist, window, cx);
1965 })
1966 }
1967
1968 /// Whether or not we should allow messages to be sent.
1969 /// Will return false if the selected provided has a configuration error or
1970 /// if the user has not accepted the terms of service for this provider.
1971 fn sending_disabled(&self, cx: &mut Context<'_, TextThreadEditor>) -> bool {
1972 let model_registry = LanguageModelRegistry::read_global(cx);
1973 let Some(configuration_error) =
1974 model_registry.configuration_error(model_registry.default_model(), cx)
1975 else {
1976 return false;
1977 };
1978
1979 match configuration_error {
1980 ConfigurationError::NoProvider
1981 | ConfigurationError::ModelNotFound
1982 | ConfigurationError::ProviderNotAuthenticated(_) => true,
1983 }
1984 }
1985
1986 fn render_inject_context_menu(&self, cx: &mut Context<Self>) -> impl IntoElement {
1987 slash_command_picker::SlashCommandSelector::new(
1988 self.slash_commands.clone(),
1989 cx.entity().downgrade(),
1990 IconButton::new("trigger", IconName::Plus)
1991 .icon_size(IconSize::Small)
1992 .icon_color(Color::Muted)
1993 .selected_icon_color(Color::Accent)
1994 .selected_style(ButtonStyle::Filled),
1995 move |_window, cx| {
1996 Tooltip::with_meta("Add Context", None, "Type / to insert via keyboard", cx)
1997 },
1998 )
1999 }
2000
2001 fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2002 let text_thread = self.text_thread().read(cx);
2003 let active_model = LanguageModelRegistry::read_global(cx)
2004 .default_model()
2005 .map(|default| default.model)?;
2006 if !active_model.supports_burn_mode() {
2007 return None;
2008 }
2009
2010 let active_completion_mode = text_thread.completion_mode();
2011 let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
2012 let icon = if burn_mode_enabled {
2013 IconName::ZedBurnModeOn
2014 } else {
2015 IconName::ZedBurnMode
2016 };
2017
2018 Some(
2019 IconButton::new("burn-mode", icon)
2020 .icon_size(IconSize::Small)
2021 .icon_color(Color::Muted)
2022 .toggle_state(burn_mode_enabled)
2023 .selected_icon_color(Color::Error)
2024 .on_click(cx.listener(move |this, _event, _window, cx| {
2025 this.text_thread().update(cx, |text_thread, _cx| {
2026 text_thread.set_completion_mode(match active_completion_mode {
2027 CompletionMode::Burn => CompletionMode::Normal,
2028 CompletionMode::Normal => CompletionMode::Burn,
2029 });
2030 });
2031 }))
2032 .tooltip(move |_window, cx| {
2033 cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
2034 .into()
2035 })
2036 .into_any_element(),
2037 )
2038 }
2039
2040 fn render_language_model_selector(
2041 &self,
2042 window: &mut Window,
2043 cx: &mut Context<Self>,
2044 ) -> impl IntoElement {
2045 let active_model = LanguageModelRegistry::read_global(cx)
2046 .default_model()
2047 .map(|default| default.model);
2048 let model_name = match active_model {
2049 Some(model) => model.name().0,
2050 None => SharedString::from("Select Model"),
2051 };
2052
2053 let active_provider = LanguageModelRegistry::read_global(cx)
2054 .default_model()
2055 .map(|default| default.provider);
2056
2057 let provider_icon = match active_provider {
2058 Some(provider) => provider.icon(),
2059 None => IconName::Ai,
2060 };
2061
2062 let focus_handle = self.editor().focus_handle(cx);
2063 let (color, icon) = if self.language_model_selector_menu_handle.is_deployed() {
2064 (Color::Accent, IconName::ChevronUp)
2065 } else {
2066 (Color::Muted, IconName::ChevronDown)
2067 };
2068
2069 PickerPopoverMenu::new(
2070 self.language_model_selector.clone(),
2071 ButtonLike::new("active-model")
2072 .selected_style(ButtonStyle::Tinted(TintColor::Accent))
2073 .child(
2074 h_flex()
2075 .gap_0p5()
2076 .child(Icon::new(provider_icon).color(color).size(IconSize::XSmall))
2077 .child(
2078 Label::new(model_name)
2079 .color(color)
2080 .size(LabelSize::Small)
2081 .ml_0p5(),
2082 )
2083 .child(Icon::new(icon).color(color).size(IconSize::XSmall)),
2084 ),
2085 move |_window, cx| {
2086 Tooltip::for_action_in("Change Model", &ToggleModelSelector, &focus_handle, cx)
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 text_thread = self.text_thread.read(cx);
2654 Some(proto::view::Variant::ContextEditor(
2655 proto::view::ContextEditor {
2656 context_id: text_thread.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 text_thread_id = TextThreadId::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 text_thread_editor_task = workspace.update(cx, |workspace, cx| {
2689 agent_panel_delegate.open_remote_text_thread(workspace, text_thread_id, window, cx)
2690 });
2691
2692 Some(window.spawn(cx, async move |cx| {
2693 let text_thread_editor = text_thread_editor_task.await?;
2694 text_thread_editor
2695 .update_in(cx, |text_thread_editor, window, cx| {
2696 text_thread_editor.remote_id = Some(id);
2697 text_thread_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(text_thread_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.text_thread.read(cx).id() == self.text_thread.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 text_thread: WeakEntity<TextThread>,
2774) -> FoldPlaceholder {
2775 FoldPlaceholder {
2776 constrain_width: false,
2777 merge_adjacent: false,
2778 render: Arc::new(move |fold_id, _, cx| {
2779 let Some(text_thread) = text_thread.upgrade() else {
2780 return Empty.into_any();
2781 };
2782
2783 let Some(command) = text_thread.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(text_thread: &Entity<TextThread>, 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 = text_thread.read(cx).token_count()?;
2831 let max_token_count =
2832 model.max_token_count_for_mode(text_thread.read(cx).completion_mode().into());
2833 let token_state = if max_token_count.saturating_sub(token_count) == 0 {
2834 TokenState::NoTokensLeft {
2835 max_token_count,
2836 token_count,
2837 }
2838 } else {
2839 let over_warn_threshold =
2840 token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
2841 TokenState::HasMoreTokens {
2842 max_token_count,
2843 token_count,
2844 over_warn_threshold,
2845 }
2846 };
2847 Some(token_state)
2848}
2849
2850fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
2851 let image_size = data
2852 .size(0)
2853 .map(|dimension| Pixels::from(u32::from(dimension)));
2854 let image_ratio = image_size.width / image_size.height;
2855 let bounds_ratio = max_size.width / max_size.height;
2856
2857 if image_size.width > max_size.width || image_size.height > max_size.height {
2858 if bounds_ratio > image_ratio {
2859 size(
2860 image_size.width * (max_size.height / image_size.height),
2861 max_size.height,
2862 )
2863 } else {
2864 size(
2865 max_size.width,
2866 image_size.height * (max_size.width / image_size.width),
2867 )
2868 }
2869 } else {
2870 size(image_size.width, image_size.height)
2871 }
2872}
2873
2874pub fn humanize_token_count(count: u64) -> String {
2875 match count {
2876 0..=999 => count.to_string(),
2877 1000..=9999 => {
2878 let thousands = count / 1000;
2879 let hundreds = (count % 1000 + 50) / 100;
2880 if hundreds == 0 {
2881 format!("{}k", thousands)
2882 } else if hundreds == 10 {
2883 format!("{}k", thousands + 1)
2884 } else {
2885 format!("{}.{}k", thousands, hundreds)
2886 }
2887 }
2888 1_000_000..=9_999_999 => {
2889 let millions = count / 1_000_000;
2890 let hundred_thousands = (count % 1_000_000 + 50_000) / 100_000;
2891 if hundred_thousands == 0 {
2892 format!("{}M", millions)
2893 } else if hundred_thousands == 10 {
2894 format!("{}M", millions + 1)
2895 } else {
2896 format!("{}.{}M", millions, hundred_thousands)
2897 }
2898 }
2899 10_000_000.. => format!("{}M", (count + 500_000) / 1_000_000),
2900 _ => format!("{}k", (count + 500) / 1000),
2901 }
2902}
2903
2904pub fn make_lsp_adapter_delegate(
2905 project: &Entity<Project>,
2906 cx: &mut App,
2907) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
2908 project.update(cx, |project, cx| {
2909 // TODO: Find the right worktree.
2910 let Some(worktree) = project.worktrees(cx).next() else {
2911 return Ok(None::<Arc<dyn LspAdapterDelegate>>);
2912 };
2913 let http_client = project.client().http_client();
2914 project.lsp_store().update(cx, |_, cx| {
2915 Ok(Some(LocalLspAdapterDelegate::new(
2916 project.languages().clone(),
2917 project.environment(),
2918 cx.weak_entity(),
2919 &worktree,
2920 http_client,
2921 project.fs().clone(),
2922 cx,
2923 ) as Arc<dyn LspAdapterDelegate>))
2924 })
2925 })
2926}
2927
2928#[cfg(test)]
2929mod tests {
2930 use super::*;
2931 use editor::SelectionEffects;
2932 use fs::FakeFs;
2933 use gpui::{App, TestAppContext, VisualTestContext};
2934 use indoc::indoc;
2935 use language::{Buffer, LanguageRegistry};
2936 use pretty_assertions::assert_eq;
2937 use prompt_store::PromptBuilder;
2938 use text::OffsetRangeExt;
2939 use unindent::Unindent;
2940 use util::path;
2941
2942 #[gpui::test]
2943 async fn test_copy_paste_whole_message(cx: &mut TestAppContext) {
2944 let (context, text_thread_editor, mut cx) = setup_text_thread_editor_text(vec![
2945 (Role::User, "What is the Zed editor?"),
2946 (
2947 Role::Assistant,
2948 "Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.",
2949 ),
2950 (Role::User, ""),
2951 ],cx).await;
2952
2953 // Select & Copy whole user message
2954 assert_copy_paste_text_thread_editor(
2955 &text_thread_editor,
2956 message_range(&context, 0, &mut cx),
2957 indoc! {"
2958 What is the Zed editor?
2959 Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
2960 What is the Zed editor?
2961 "},
2962 &mut cx,
2963 );
2964
2965 // Select & Copy whole assistant message
2966 assert_copy_paste_text_thread_editor(
2967 &text_thread_editor,
2968 message_range(&context, 1, &mut cx),
2969 indoc! {"
2970 What is the Zed editor?
2971 Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
2972 What is the Zed editor?
2973 Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
2974 "},
2975 &mut cx,
2976 );
2977 }
2978
2979 #[gpui::test]
2980 async fn test_copy_paste_no_selection(cx: &mut TestAppContext) {
2981 let (context, text_thread_editor, mut cx) = setup_text_thread_editor_text(
2982 vec![
2983 (Role::User, "user1"),
2984 (Role::Assistant, "assistant1"),
2985 (Role::Assistant, "assistant2"),
2986 (Role::User, ""),
2987 ],
2988 cx,
2989 )
2990 .await;
2991
2992 // Copy and paste first assistant message
2993 let message_2_range = message_range(&context, 1, &mut cx);
2994 assert_copy_paste_text_thread_editor(
2995 &text_thread_editor,
2996 message_2_range.start..message_2_range.start,
2997 indoc! {"
2998 user1
2999 assistant1
3000 assistant2
3001 assistant1
3002 "},
3003 &mut cx,
3004 );
3005
3006 // Copy and cut second assistant message
3007 let message_3_range = message_range(&context, 2, &mut cx);
3008 assert_copy_paste_text_thread_editor(
3009 &text_thread_editor,
3010 message_3_range.start..message_3_range.start,
3011 indoc! {"
3012 user1
3013 assistant1
3014 assistant2
3015 assistant1
3016 assistant2
3017 "},
3018 &mut cx,
3019 );
3020 }
3021
3022 #[gpui::test]
3023 fn test_find_code_blocks(cx: &mut App) {
3024 let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
3025
3026 let buffer = cx.new(|cx| {
3027 let text = r#"
3028 line 0
3029 line 1
3030 ```rust
3031 fn main() {}
3032 ```
3033 line 5
3034 line 6
3035 line 7
3036 ```go
3037 func main() {}
3038 ```
3039 line 11
3040 ```
3041 this is plain text code block
3042 ```
3043
3044 ```go
3045 func another() {}
3046 ```
3047 line 19
3048 "#
3049 .unindent();
3050 let mut buffer = Buffer::local(text, cx);
3051 buffer.set_language(Some(markdown.clone()), cx);
3052 buffer
3053 });
3054 let snapshot = buffer.read(cx).snapshot();
3055
3056 let code_blocks = vec![
3057 Point::new(3, 0)..Point::new(4, 0),
3058 Point::new(9, 0)..Point::new(10, 0),
3059 Point::new(13, 0)..Point::new(14, 0),
3060 Point::new(17, 0)..Point::new(18, 0),
3061 ]
3062 .into_iter()
3063 .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
3064 .collect::<Vec<_>>();
3065
3066 let expected_results = vec![
3067 (0, None),
3068 (1, None),
3069 (2, Some(code_blocks[0].clone())),
3070 (3, Some(code_blocks[0].clone())),
3071 (4, Some(code_blocks[0].clone())),
3072 (5, None),
3073 (6, None),
3074 (7, None),
3075 (8, Some(code_blocks[1].clone())),
3076 (9, Some(code_blocks[1].clone())),
3077 (10, Some(code_blocks[1].clone())),
3078 (11, None),
3079 (12, Some(code_blocks[2].clone())),
3080 (13, Some(code_blocks[2].clone())),
3081 (14, Some(code_blocks[2].clone())),
3082 (15, None),
3083 (16, Some(code_blocks[3].clone())),
3084 (17, Some(code_blocks[3].clone())),
3085 (18, Some(code_blocks[3].clone())),
3086 (19, None),
3087 ];
3088
3089 for (row, expected) in expected_results {
3090 let offset = snapshot.point_to_offset(Point::new(row, 0));
3091 let range = find_surrounding_code_block(&snapshot, offset);
3092 assert_eq!(range, expected, "unexpected result on row {:?}", row);
3093 }
3094 }
3095
3096 async fn setup_text_thread_editor_text(
3097 messages: Vec<(Role, &str)>,
3098 cx: &mut TestAppContext,
3099 ) -> (
3100 Entity<TextThread>,
3101 Entity<TextThreadEditor>,
3102 VisualTestContext,
3103 ) {
3104 cx.update(init_test);
3105
3106 let fs = FakeFs::new(cx.executor());
3107 let text_thread = create_text_thread_with_messages(messages, cx);
3108
3109 let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
3110 let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
3111 let workspace = window.root(cx).unwrap();
3112 let mut cx = VisualTestContext::from_window(*window, cx);
3113
3114 let text_thread_editor = window
3115 .update(&mut cx, |_, window, cx| {
3116 cx.new(|cx| {
3117 TextThreadEditor::for_text_thread(
3118 text_thread.clone(),
3119 fs,
3120 workspace.downgrade(),
3121 project,
3122 None,
3123 window,
3124 cx,
3125 )
3126 })
3127 })
3128 .unwrap();
3129
3130 (text_thread, text_thread_editor, cx)
3131 }
3132
3133 fn message_range(
3134 text_thread: &Entity<TextThread>,
3135 message_ix: usize,
3136 cx: &mut TestAppContext,
3137 ) -> Range<usize> {
3138 text_thread.update(cx, |text_thread, cx| {
3139 text_thread
3140 .messages(cx)
3141 .nth(message_ix)
3142 .unwrap()
3143 .anchor_range
3144 .to_offset(&text_thread.buffer().read(cx).snapshot())
3145 })
3146 }
3147
3148 fn assert_copy_paste_text_thread_editor<T: editor::ToOffset>(
3149 text_thread_editor: &Entity<TextThreadEditor>,
3150 range: Range<T>,
3151 expected_text: &str,
3152 cx: &mut VisualTestContext,
3153 ) {
3154 text_thread_editor.update_in(cx, |text_thread_editor, window, cx| {
3155 text_thread_editor.editor.update(cx, |editor, cx| {
3156 editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
3157 s.select_ranges([range])
3158 });
3159 });
3160
3161 text_thread_editor.copy(&Default::default(), window, cx);
3162
3163 text_thread_editor.editor.update(cx, |editor, cx| {
3164 editor.move_to_end(&Default::default(), window, cx);
3165 });
3166
3167 text_thread_editor.paste(&Default::default(), window, cx);
3168
3169 text_thread_editor.editor.update(cx, |editor, cx| {
3170 assert_eq!(editor.text(cx), expected_text);
3171 });
3172 });
3173 }
3174
3175 fn create_text_thread_with_messages(
3176 mut messages: Vec<(Role, &str)>,
3177 cx: &mut TestAppContext,
3178 ) -> Entity<TextThread> {
3179 let registry = Arc::new(LanguageRegistry::test(cx.executor()));
3180 let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3181 cx.new(|cx| {
3182 let mut text_thread = TextThread::local(
3183 registry,
3184 None,
3185 None,
3186 prompt_builder.clone(),
3187 Arc::new(SlashCommandWorkingSet::default()),
3188 cx,
3189 );
3190 let mut message_1 = text_thread.messages(cx).next().unwrap();
3191 let (role, text) = messages.remove(0);
3192
3193 loop {
3194 if role == message_1.role {
3195 text_thread.buffer().update(cx, |buffer, cx| {
3196 buffer.edit([(message_1.offset_range, text)], None, cx);
3197 });
3198 break;
3199 }
3200 let mut ids = HashSet::default();
3201 ids.insert(message_1.id);
3202 text_thread.cycle_message_roles(ids, cx);
3203 message_1 = text_thread.messages(cx).next().unwrap();
3204 }
3205
3206 let mut last_message_id = message_1.id;
3207 for (role, text) in messages {
3208 text_thread.insert_message_after(last_message_id, role, MessageStatus::Done, cx);
3209 let message = text_thread.messages(cx).last().unwrap();
3210 last_message_id = message.id;
3211 text_thread.buffer().update(cx, |buffer, cx| {
3212 buffer.edit([(message.offset_range, text)], None, cx);
3213 })
3214 }
3215
3216 text_thread
3217 })
3218 }
3219
3220 fn init_test(cx: &mut App) {
3221 let settings_store = SettingsStore::test(cx);
3222 prompt_store::init(cx);
3223 LanguageModelRegistry::test(cx);
3224 cx.set_global(settings_store);
3225 language::init(cx);
3226 agent_settings::init(cx);
3227 Project::init_settings(cx);
3228 theme::init(theme::LoadThemes::JustBase, cx);
3229 workspace::init_settings(cx);
3230 editor::init_settings(cx);
3231 }
3232}