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