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