text_thread_editor.rs

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