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