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