text_thread_editor.rs

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