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