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                                            window,
1093                                            cx,
1094                                        )
1095                                    })
1096                                    .on_click({
1097                                        let context = context.clone();
1098                                        move |_, _window, cx| {
1099                                            context.update(cx, |context, cx| {
1100                                                context.cycle_message_roles(
1101                                                    HashSet::from_iter(Some(message_id)),
1102                                                    cx,
1103                                                )
1104                                            })
1105                                        }
1106                                    }),
1107                            )
1108                            .children(note);
1109
1110                        h_flex()
1111                            .id(("message_header", message_id.as_u64()))
1112                            .pl(cx.margins.gutter.full_width())
1113                            .h_11()
1114                            .w_full()
1115                            .relative()
1116                            .gap_1p5()
1117                            .child(sender)
1118                            .children(match &message.cache {
1119                                Some(cache) if cache.is_final_anchor => match cache.status {
1120                                    CacheStatus::Cached => Some(
1121                                        div()
1122                                            .id("cached")
1123                                            .child(
1124                                                Icon::new(IconName::DatabaseZap)
1125                                                    .size(IconSize::XSmall)
1126                                                    .color(Color::Hint),
1127                                            )
1128                                            .tooltip(|window, cx| {
1129                                                Tooltip::with_meta(
1130                                                    "Context Cached",
1131                                                    None,
1132                                                    "Large messages cached to optimize performance",
1133                                                    window,
1134                                                    cx,
1135                                                )
1136                                            })
1137                                            .into_any_element(),
1138                                    ),
1139                                    CacheStatus::Pending => Some(
1140                                        div()
1141                                            .child(
1142                                                Icon::new(IconName::Ellipsis)
1143                                                    .size(IconSize::XSmall)
1144                                                    .color(Color::Hint),
1145                                            )
1146                                            .into_any_element(),
1147                                    ),
1148                                },
1149                                _ => None,
1150                            })
1151                            .children(match &message.status {
1152                                MessageStatus::Error(error) => Some(
1153                                    Button::new("show-error", "Error")
1154                                        .color(Color::Error)
1155                                        .selected_label_color(Color::Error)
1156                                        .selected_icon_color(Color::Error)
1157                                        .icon(IconName::XCircle)
1158                                        .icon_color(Color::Error)
1159                                        .icon_size(IconSize::XSmall)
1160                                        .icon_position(IconPosition::Start)
1161                                        .tooltip(Tooltip::text("View Details"))
1162                                        .on_click({
1163                                            let context = context.clone();
1164                                            let error = error.clone();
1165                                            move |_, _window, cx| {
1166                                                context.update(cx, |_, cx| {
1167                                                    cx.emit(ContextEvent::ShowAssistError(
1168                                                        error.clone(),
1169                                                    ));
1170                                                });
1171                                            }
1172                                        })
1173                                        .into_any_element(),
1174                                ),
1175                                MessageStatus::Canceled => Some(
1176                                    h_flex()
1177                                        .gap_1()
1178                                        .items_center()
1179                                        .child(
1180                                            Icon::new(IconName::XCircle)
1181                                                .color(Color::Disabled)
1182                                                .size(IconSize::XSmall),
1183                                        )
1184                                        .child(
1185                                            Label::new("Canceled")
1186                                                .size(LabelSize::Small)
1187                                                .color(Color::Disabled),
1188                                        )
1189                                        .into_any_element(),
1190                                ),
1191                                _ => None,
1192                            })
1193                            .into_any_element()
1194                    }
1195                })
1196            };
1197            let create_block_properties = |message: &Message| BlockProperties {
1198                height: Some(2),
1199                style: BlockStyle::Sticky,
1200                placement: BlockPlacement::Above(
1201                    buffer
1202                        .anchor_in_excerpt(excerpt_id, message.anchor_range.start)
1203                        .unwrap(),
1204                ),
1205                priority: usize::MAX,
1206                render: render_block(MessageMetadata::from(message)),
1207            };
1208            let mut new_blocks = vec![];
1209            let mut block_index_to_message = vec![];
1210            for message in self.context.read(cx).messages(cx) {
1211                if blocks_to_remove.remove(&message.id).is_some() {
1212                    // This is an old message that we might modify.
1213                    let Some((meta, block_id)) = old_blocks.get_mut(&message.id) else {
1214                        debug_assert!(
1215                            false,
1216                            "old_blocks should contain a message_id we've just removed."
1217                        );
1218                        continue;
1219                    };
1220                    // Should we modify it?
1221                    let message_meta = MessageMetadata::from(&message);
1222                    if meta != &message_meta {
1223                        blocks_to_replace.insert(*block_id, render_block(message_meta.clone()));
1224                        *meta = message_meta;
1225                    }
1226                } else {
1227                    // This is a new message.
1228                    new_blocks.push(create_block_properties(&message));
1229                    block_index_to_message.push((message.id, MessageMetadata::from(&message)));
1230                }
1231            }
1232            editor.replace_blocks(blocks_to_replace, None, cx);
1233            editor.remove_blocks(blocks_to_remove.into_values().collect(), None, cx);
1234
1235            let ids = editor.insert_blocks(new_blocks, None, cx);
1236            old_blocks.extend(ids.into_iter().zip(block_index_to_message).map(
1237                |(block_id, (message_id, message_meta))| (message_id, (message_meta, block_id)),
1238            ));
1239            self.blocks = old_blocks;
1240        });
1241    }
1242
1243    /// Returns either the selected text, or the content of the Markdown code
1244    /// block surrounding the cursor.
1245    fn get_selection_or_code_block(
1246        context_editor_view: &Entity<TextThreadEditor>,
1247        cx: &mut Context<Workspace>,
1248    ) -> Option<(String, bool)> {
1249        const CODE_FENCE_DELIMITER: &str = "```";
1250
1251        let context_editor = context_editor_view.read(cx).editor.clone();
1252        context_editor.update(cx, |context_editor, cx| {
1253            let display_map = context_editor.display_snapshot(cx);
1254            if context_editor
1255                .selections
1256                .newest::<Point>(&display_map)
1257                .is_empty()
1258            {
1259                let snapshot = context_editor.buffer().read(cx).snapshot(cx);
1260                let (_, _, snapshot) = snapshot.as_singleton()?;
1261
1262                let head = context_editor
1263                    .selections
1264                    .newest::<Point>(&display_map)
1265                    .head();
1266                let offset = snapshot.point_to_offset(head);
1267
1268                let surrounding_code_block_range = find_surrounding_code_block(snapshot, offset)?;
1269                let mut text = snapshot
1270                    .text_for_range(surrounding_code_block_range)
1271                    .collect::<String>();
1272
1273                // If there is no newline trailing the closing three-backticks, then
1274                // tree-sitter-md extends the range of the content node to include
1275                // the backticks.
1276                if text.ends_with(CODE_FENCE_DELIMITER) {
1277                    text.drain((text.len() - CODE_FENCE_DELIMITER.len())..);
1278                }
1279
1280                (!text.is_empty()).then_some((text, true))
1281            } else {
1282                let selection = context_editor.selections.newest_adjusted(&display_map);
1283                let buffer = context_editor.buffer().read(cx).snapshot(cx);
1284                let selected_text = buffer.text_for_range(selection.range()).collect::<String>();
1285
1286                (!selected_text.is_empty()).then_some((selected_text, false))
1287            }
1288        })
1289    }
1290
1291    pub fn insert_selection(
1292        workspace: &mut Workspace,
1293        _: &InsertIntoEditor,
1294        window: &mut Window,
1295        cx: &mut Context<Workspace>,
1296    ) {
1297        let Some(agent_panel_delegate) = <dyn AgentPanelDelegate>::try_global(cx) else {
1298            return;
1299        };
1300        let Some(context_editor_view) =
1301            agent_panel_delegate.active_context_editor(workspace, window, cx)
1302        else {
1303            return;
1304        };
1305        let Some(active_editor_view) = workspace
1306            .active_item(cx)
1307            .and_then(|item| item.act_as::<Editor>(cx))
1308        else {
1309            return;
1310        };
1311
1312        if let Some((text, _)) = Self::get_selection_or_code_block(&context_editor_view, cx) {
1313            active_editor_view.update(cx, |editor, cx| {
1314                editor.insert(&text, window, cx);
1315                editor.focus_handle(cx).focus(window);
1316            })
1317        }
1318    }
1319
1320    pub fn copy_code(
1321        workspace: &mut Workspace,
1322        _: &CopyCode,
1323        window: &mut Window,
1324        cx: &mut Context<Workspace>,
1325    ) {
1326        let result = maybe!({
1327            let agent_panel_delegate = <dyn AgentPanelDelegate>::try_global(cx)?;
1328            let context_editor_view =
1329                agent_panel_delegate.active_context_editor(workspace, window, cx)?;
1330            Self::get_selection_or_code_block(&context_editor_view, cx)
1331        });
1332        let Some((text, is_code_block)) = result else {
1333            return;
1334        };
1335
1336        cx.write_to_clipboard(ClipboardItem::new_string(text));
1337
1338        struct CopyToClipboardToast;
1339        workspace.show_toast(
1340            Toast::new(
1341                NotificationId::unique::<CopyToClipboardToast>(),
1342                format!(
1343                    "{} copied to clipboard.",
1344                    if is_code_block {
1345                        "Code block"
1346                    } else {
1347                        "Selection"
1348                    }
1349                ),
1350            )
1351            .autohide(),
1352            cx,
1353        );
1354    }
1355
1356    pub fn handle_insert_dragged_files(
1357        workspace: &mut Workspace,
1358        action: &InsertDraggedFiles,
1359        window: &mut Window,
1360        cx: &mut Context<Workspace>,
1361    ) {
1362        let Some(agent_panel_delegate) = <dyn AgentPanelDelegate>::try_global(cx) else {
1363            return;
1364        };
1365        let Some(context_editor_view) =
1366            agent_panel_delegate.active_context_editor(workspace, window, cx)
1367        else {
1368            return;
1369        };
1370
1371        let project = context_editor_view.read(cx).project.clone();
1372
1373        let paths = match action {
1374            InsertDraggedFiles::ProjectPaths(paths) => Task::ready((paths.clone(), vec![])),
1375            InsertDraggedFiles::ExternalFiles(paths) => {
1376                let tasks = paths
1377                    .clone()
1378                    .into_iter()
1379                    .map(|path| Workspace::project_path_for_path(project.clone(), &path, false, cx))
1380                    .collect::<Vec<_>>();
1381
1382                cx.background_spawn(async move {
1383                    let mut paths = vec![];
1384                    let mut worktrees = vec![];
1385
1386                    let opened_paths = futures::future::join_all(tasks).await;
1387
1388                    for entry in opened_paths {
1389                        if let Some((worktree, project_path)) = entry.log_err() {
1390                            worktrees.push(worktree);
1391                            paths.push(project_path);
1392                        }
1393                    }
1394
1395                    (paths, worktrees)
1396                })
1397            }
1398        };
1399
1400        context_editor_view.update(cx, |_, cx| {
1401            cx.spawn_in(window, async move |this, cx| {
1402                let (paths, dragged_file_worktrees) = paths.await;
1403                this.update_in(cx, |this, window, cx| {
1404                    this.insert_dragged_files(paths, dragged_file_worktrees, window, cx);
1405                })
1406                .ok();
1407            })
1408            .detach();
1409        })
1410    }
1411
1412    pub fn insert_dragged_files(
1413        &mut self,
1414        opened_paths: Vec<ProjectPath>,
1415        added_worktrees: Vec<Entity<Worktree>>,
1416        window: &mut Window,
1417        cx: &mut Context<Self>,
1418    ) {
1419        let mut file_slash_command_args = vec![];
1420        for project_path in opened_paths.into_iter() {
1421            let Some(worktree) = self
1422                .project
1423                .read(cx)
1424                .worktree_for_id(project_path.worktree_id, cx)
1425            else {
1426                continue;
1427            };
1428            let path_style = worktree.read(cx).path_style();
1429            let full_path = worktree
1430                .read(cx)
1431                .root_name()
1432                .join(&project_path.path)
1433                .display(path_style)
1434                .into_owned();
1435            file_slash_command_args.push(full_path);
1436        }
1437
1438        let cmd_name = FileSlashCommand.name();
1439
1440        let file_argument = file_slash_command_args.join(" ");
1441
1442        self.editor.update(cx, |editor, cx| {
1443            editor.insert("\n", window, cx);
1444            editor.insert(&format!("/{} {}", cmd_name, file_argument), window, cx);
1445        });
1446        self.confirm_command(&ConfirmCommand, window, cx);
1447        self.dragged_file_worktrees.extend(added_worktrees);
1448    }
1449
1450    pub fn quote_selection(
1451        workspace: &mut Workspace,
1452        _: &AddSelectionToThread,
1453        window: &mut Window,
1454        cx: &mut Context<Workspace>,
1455    ) {
1456        let Some(agent_panel_delegate) = <dyn AgentPanelDelegate>::try_global(cx) else {
1457            return;
1458        };
1459
1460        let Some((selections, buffer)) = maybe!({
1461            let editor = workspace
1462                .active_item(cx)
1463                .and_then(|item| item.act_as::<Editor>(cx))?;
1464
1465            let buffer = editor.read(cx).buffer().clone();
1466            let snapshot = buffer.read(cx).snapshot(cx);
1467            let selections = editor.update(cx, |editor, cx| {
1468                editor
1469                    .selections
1470                    .all_adjusted(&editor.display_snapshot(cx))
1471                    .into_iter()
1472                    .filter_map(|s| {
1473                        (!s.is_empty())
1474                            .then(|| snapshot.anchor_after(s.start)..snapshot.anchor_before(s.end))
1475                    })
1476                    .collect::<Vec<_>>()
1477            });
1478            Some((selections, buffer))
1479        }) else {
1480            return;
1481        };
1482
1483        if selections.is_empty() {
1484            return;
1485        }
1486
1487        agent_panel_delegate.quote_selection(workspace, selections, buffer, window, cx);
1488    }
1489
1490    pub fn quote_ranges(
1491        &mut self,
1492        ranges: Vec<Range<Point>>,
1493        snapshot: MultiBufferSnapshot,
1494        window: &mut Window,
1495        cx: &mut Context<Self>,
1496    ) {
1497        let creases = selections_creases(ranges, snapshot, cx);
1498
1499        self.editor.update(cx, |editor, cx| {
1500            editor.insert("\n", window, cx);
1501            for (text, crease_title) in creases {
1502                let point = editor
1503                    .selections
1504                    .newest::<Point>(&editor.display_snapshot(cx))
1505                    .head();
1506                let start_row = MultiBufferRow(point.row);
1507
1508                editor.insert(&text, window, cx);
1509
1510                let snapshot = editor.buffer().read(cx).snapshot(cx);
1511                let anchor_before = snapshot.anchor_after(point);
1512                let anchor_after = editor
1513                    .selections
1514                    .newest_anchor()
1515                    .head()
1516                    .bias_left(&snapshot);
1517
1518                editor.insert("\n", window, cx);
1519
1520                let fold_placeholder =
1521                    quote_selection_fold_placeholder(crease_title, cx.entity().downgrade());
1522                let crease = Crease::inline(
1523                    anchor_before..anchor_after,
1524                    fold_placeholder,
1525                    render_quote_selection_output_toggle,
1526                    |_, _, _, _| Empty.into_any(),
1527                );
1528                editor.insert_creases(vec![crease], cx);
1529                editor.fold_at(start_row, window, cx);
1530            }
1531        })
1532    }
1533
1534    fn copy(&mut self, _: &editor::actions::Copy, _window: &mut Window, cx: &mut Context<Self>) {
1535        if self.editor.read(cx).selections.count() == 1 {
1536            let (copied_text, metadata, _) = self.get_clipboard_contents(cx);
1537            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1538                copied_text,
1539                metadata,
1540            ));
1541            cx.stop_propagation();
1542            return;
1543        }
1544
1545        cx.propagate();
1546    }
1547
1548    fn cut(&mut self, _: &editor::actions::Cut, window: &mut Window, cx: &mut Context<Self>) {
1549        if self.editor.read(cx).selections.count() == 1 {
1550            let (copied_text, metadata, selections) = self.get_clipboard_contents(cx);
1551
1552            self.editor.update(cx, |editor, cx| {
1553                editor.transact(window, cx, |this, window, cx| {
1554                    this.change_selections(Default::default(), window, cx, |s| {
1555                        s.select(selections);
1556                    });
1557                    this.insert("", window, cx);
1558                    cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1559                        copied_text,
1560                        metadata,
1561                    ));
1562                });
1563            });
1564
1565            cx.stop_propagation();
1566            return;
1567        }
1568
1569        cx.propagate();
1570    }
1571
1572    fn get_clipboard_contents(
1573        &mut self,
1574        cx: &mut Context<Self>,
1575    ) -> (String, CopyMetadata, Vec<text::Selection<usize>>) {
1576        let (mut selection, creases) = self.editor.update(cx, |editor, cx| {
1577            let mut selection = editor
1578                .selections
1579                .newest_adjusted(&editor.display_snapshot(cx));
1580            let snapshot = editor.buffer().read(cx).snapshot(cx);
1581
1582            selection.goal = SelectionGoal::None;
1583
1584            let selection_start = snapshot.point_to_offset(selection.start);
1585
1586            (
1587                selection.map(|point| snapshot.point_to_offset(point)),
1588                editor.display_map.update(cx, |display_map, cx| {
1589                    display_map
1590                        .snapshot(cx)
1591                        .crease_snapshot
1592                        .creases_in_range(
1593                            MultiBufferRow(selection.start.row)
1594                                ..MultiBufferRow(selection.end.row + 1),
1595                            &snapshot,
1596                        )
1597                        .filter_map(|crease| {
1598                            if let Crease::Inline {
1599                                range, metadata, ..
1600                            } = &crease
1601                            {
1602                                let metadata = metadata.as_ref()?;
1603                                let start = range
1604                                    .start
1605                                    .to_offset(&snapshot)
1606                                    .saturating_sub(selection_start);
1607                                let end = range
1608                                    .end
1609                                    .to_offset(&snapshot)
1610                                    .saturating_sub(selection_start);
1611
1612                                let range_relative_to_selection = start..end;
1613                                if !range_relative_to_selection.is_empty() {
1614                                    return Some(SelectedCreaseMetadata {
1615                                        range_relative_to_selection,
1616                                        crease: metadata.clone(),
1617                                    });
1618                                }
1619                            }
1620                            None
1621                        })
1622                        .collect::<Vec<_>>()
1623                }),
1624            )
1625        });
1626
1627        let context = self.context.read(cx);
1628
1629        let mut text = String::new();
1630
1631        // If selection is empty, we want to copy the entire line
1632        if selection.range().is_empty() {
1633            let snapshot = context.buffer().read(cx).snapshot();
1634            let point = snapshot.offset_to_point(selection.range().start);
1635            selection.start = snapshot.point_to_offset(Point::new(point.row, 0));
1636            selection.end = snapshot
1637                .point_to_offset(cmp::min(Point::new(point.row + 1, 0), snapshot.max_point()));
1638            for chunk in context.buffer().read(cx).text_for_range(selection.range()) {
1639                text.push_str(chunk);
1640            }
1641        } else {
1642            for message in context.messages(cx) {
1643                if message.offset_range.start >= selection.range().end {
1644                    break;
1645                } else if message.offset_range.end >= selection.range().start {
1646                    let range = cmp::max(message.offset_range.start, selection.range().start)
1647                        ..cmp::min(message.offset_range.end, selection.range().end);
1648                    if !range.is_empty() {
1649                        for chunk in context.buffer().read(cx).text_for_range(range) {
1650                            text.push_str(chunk);
1651                        }
1652                        if message.offset_range.end < selection.range().end {
1653                            text.push('\n');
1654                        }
1655                    }
1656                }
1657            }
1658        }
1659        (text, CopyMetadata { creases }, vec![selection])
1660    }
1661
1662    fn paste(
1663        &mut self,
1664        action: &editor::actions::Paste,
1665        window: &mut Window,
1666        cx: &mut Context<Self>,
1667    ) {
1668        cx.stop_propagation();
1669
1670        let images = if let Some(item) = cx.read_from_clipboard() {
1671            item.into_entries()
1672                .filter_map(|entry| {
1673                    if let ClipboardEntry::Image(image) = entry {
1674                        Some(image)
1675                    } else {
1676                        None
1677                    }
1678                })
1679                .collect()
1680        } else {
1681            Vec::new()
1682        };
1683
1684        let metadata = if let Some(item) = cx.read_from_clipboard() {
1685            item.entries().first().and_then(|entry| {
1686                if let ClipboardEntry::String(text) = entry {
1687                    text.metadata_json::<CopyMetadata>()
1688                } else {
1689                    None
1690                }
1691            })
1692        } else {
1693            None
1694        };
1695
1696        if images.is_empty() {
1697            self.editor.update(cx, |editor, cx| {
1698                let paste_position = editor
1699                    .selections
1700                    .newest::<usize>(&editor.display_snapshot(cx))
1701                    .head();
1702                editor.paste(action, window, cx);
1703
1704                if let Some(metadata) = metadata {
1705                    let buffer = editor.buffer().read(cx).snapshot(cx);
1706
1707                    let mut buffer_rows_to_fold = BTreeSet::new();
1708                    let weak_editor = cx.entity().downgrade();
1709                    editor.insert_creases(
1710                        metadata.creases.into_iter().map(|metadata| {
1711                            let start = buffer.anchor_after(
1712                                paste_position + metadata.range_relative_to_selection.start,
1713                            );
1714                            let end = buffer.anchor_before(
1715                                paste_position + metadata.range_relative_to_selection.end,
1716                            );
1717
1718                            let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1719                            buffer_rows_to_fold.insert(buffer_row);
1720                            Crease::inline(
1721                                start..end,
1722                                FoldPlaceholder {
1723                                    render: render_fold_icon_button(
1724                                        weak_editor.clone(),
1725                                        metadata.crease.icon_path.clone(),
1726                                        metadata.crease.label.clone(),
1727                                    ),
1728                                    ..Default::default()
1729                                },
1730                                render_slash_command_output_toggle,
1731                                |_, _, _, _| Empty.into_any(),
1732                            )
1733                            .with_metadata(metadata.crease)
1734                        }),
1735                        cx,
1736                    );
1737                    for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1738                        editor.fold_at(buffer_row, window, cx);
1739                    }
1740                }
1741            });
1742        } else {
1743            let mut image_positions = Vec::new();
1744            self.editor.update(cx, |editor, cx| {
1745                editor.transact(window, cx, |editor, _window, cx| {
1746                    let edits = editor
1747                        .selections
1748                        .all::<usize>(&editor.display_snapshot(cx))
1749                        .into_iter()
1750                        .map(|selection| (selection.start..selection.end, "\n"));
1751                    editor.edit(edits, cx);
1752
1753                    let snapshot = editor.buffer().read(cx).snapshot(cx);
1754                    for selection in editor.selections.all::<usize>(&editor.display_snapshot(cx)) {
1755                        image_positions.push(snapshot.anchor_before(selection.end));
1756                    }
1757                });
1758            });
1759
1760            self.context.update(cx, |context, cx| {
1761                for image in images {
1762                    let Some(render_image) = image.to_image_data(cx.svg_renderer()).log_err()
1763                    else {
1764                        continue;
1765                    };
1766                    let image_id = image.id();
1767                    let image_task = LanguageModelImage::from_image(Arc::new(image), cx).shared();
1768
1769                    for image_position in image_positions.iter() {
1770                        context.insert_content(
1771                            Content::Image {
1772                                anchor: image_position.text_anchor,
1773                                image_id,
1774                                image: image_task.clone(),
1775                                render_image: render_image.clone(),
1776                            },
1777                            cx,
1778                        );
1779                    }
1780                }
1781            });
1782        }
1783    }
1784
1785    fn update_image_blocks(&mut self, cx: &mut Context<Self>) {
1786        self.editor.update(cx, |editor, cx| {
1787            let buffer = editor.buffer().read(cx).snapshot(cx);
1788            let excerpt_id = *buffer.as_singleton().unwrap().0;
1789            let old_blocks = std::mem::take(&mut self.image_blocks);
1790            let new_blocks = self
1791                .context
1792                .read(cx)
1793                .contents(cx)
1794                .map(
1795                    |Content::Image {
1796                         anchor,
1797                         render_image,
1798                         ..
1799                     }| (anchor, render_image),
1800                )
1801                .filter_map(|(anchor, render_image)| {
1802                    const MAX_HEIGHT_IN_LINES: u32 = 8;
1803                    let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
1804                    let image = render_image;
1805                    anchor.is_valid(&buffer).then(|| BlockProperties {
1806                        placement: BlockPlacement::Above(anchor),
1807                        height: Some(MAX_HEIGHT_IN_LINES),
1808                        style: BlockStyle::Sticky,
1809                        render: Arc::new(move |cx| {
1810                            let image_size = size_for_image(
1811                                &image,
1812                                size(
1813                                    cx.max_width - cx.margins.gutter.full_width(),
1814                                    MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
1815                                ),
1816                            );
1817                            h_flex()
1818                                .pl(cx.margins.gutter.full_width())
1819                                .child(
1820                                    img(image.clone())
1821                                        .object_fit(gpui::ObjectFit::ScaleDown)
1822                                        .w(image_size.width)
1823                                        .h(image_size.height),
1824                                )
1825                                .into_any_element()
1826                        }),
1827                        priority: 0,
1828                    })
1829                })
1830                .collect::<Vec<_>>();
1831
1832            editor.remove_blocks(old_blocks, None, cx);
1833            let ids = editor.insert_blocks(new_blocks, None, cx);
1834            self.image_blocks = HashSet::from_iter(ids);
1835        });
1836    }
1837
1838    fn split(&mut self, _: &Split, _window: &mut Window, cx: &mut Context<Self>) {
1839        self.context.update(cx, |context, cx| {
1840            let selections = self.editor.read(cx).selections.disjoint_anchors_arc();
1841            for selection in selections.as_ref() {
1842                let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
1843                let range = selection
1844                    .map(|endpoint| endpoint.to_offset(&buffer))
1845                    .range();
1846                context.split_message(range, cx);
1847            }
1848        });
1849    }
1850
1851    fn save(&mut self, _: &Save, _window: &mut Window, cx: &mut Context<Self>) {
1852        self.context.update(cx, |context, cx| {
1853            context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
1854        });
1855    }
1856
1857    pub fn title(&self, cx: &App) -> SharedString {
1858        self.context.read(cx).summary().or_default()
1859    }
1860
1861    pub fn regenerate_summary(&mut self, cx: &mut Context<Self>) {
1862        self.context
1863            .update(cx, |context, cx| context.summarize(true, cx));
1864    }
1865
1866    fn render_remaining_tokens(&self, cx: &App) -> Option<impl IntoElement + use<>> {
1867        let (token_count_color, token_count, max_token_count, tooltip) =
1868            match token_state(&self.context, cx)? {
1869                TokenState::NoTokensLeft {
1870                    max_token_count,
1871                    token_count,
1872                } => (
1873                    Color::Error,
1874                    token_count,
1875                    max_token_count,
1876                    Some("Token Limit Reached"),
1877                ),
1878                TokenState::HasMoreTokens {
1879                    max_token_count,
1880                    token_count,
1881                    over_warn_threshold,
1882                } => {
1883                    let (color, tooltip) = if over_warn_threshold {
1884                        (Color::Warning, Some("Token Limit is Close to Exhaustion"))
1885                    } else {
1886                        (Color::Muted, None)
1887                    };
1888                    (color, token_count, max_token_count, tooltip)
1889                }
1890            };
1891
1892        Some(
1893            h_flex()
1894                .id("token-count")
1895                .gap_0p5()
1896                .child(
1897                    Label::new(humanize_token_count(token_count))
1898                        .size(LabelSize::Small)
1899                        .color(token_count_color),
1900                )
1901                .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
1902                .child(
1903                    Label::new(humanize_token_count(max_token_count))
1904                        .size(LabelSize::Small)
1905                        .color(Color::Muted),
1906                )
1907                .when_some(tooltip, |element, tooltip| {
1908                    element.tooltip(Tooltip::text(tooltip))
1909                }),
1910        )
1911    }
1912
1913    fn render_send_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1914        let focus_handle = self.focus_handle(cx);
1915
1916        let (style, tooltip) = match token_state(&self.context, cx) {
1917            Some(TokenState::NoTokensLeft { .. }) => (
1918                ButtonStyle::Tinted(TintColor::Error),
1919                Some(Tooltip::text("Token limit reached")(window, cx)),
1920            ),
1921            Some(TokenState::HasMoreTokens {
1922                over_warn_threshold,
1923                ..
1924            }) => {
1925                let (style, tooltip) = if over_warn_threshold {
1926                    (
1927                        ButtonStyle::Tinted(TintColor::Warning),
1928                        Some(Tooltip::text("Token limit is close to exhaustion")(
1929                            window, cx,
1930                        )),
1931                    )
1932                } else {
1933                    (ButtonStyle::Filled, None)
1934                };
1935                (style, tooltip)
1936            }
1937            None => (ButtonStyle::Filled, None),
1938        };
1939
1940        Button::new("send_button", "Send")
1941            .label_size(LabelSize::Small)
1942            .disabled(self.sending_disabled(cx))
1943            .style(style)
1944            .when_some(tooltip, |button, tooltip| {
1945                button.tooltip(move |_, _| tooltip.clone())
1946            })
1947            .layer(ElevationIndex::ModalSurface)
1948            .key_binding(
1949                KeyBinding::for_action_in(&Assist, &focus_handle, window, cx)
1950                    .map(|kb| kb.size(rems_from_px(12.))),
1951            )
1952            .on_click(move |_event, window, cx| {
1953                focus_handle.dispatch_action(&Assist, window, cx);
1954            })
1955    }
1956
1957    /// Whether or not we should allow messages to be sent.
1958    /// Will return false if the selected provided has a configuration error or
1959    /// if the user has not accepted the terms of service for this provider.
1960    fn sending_disabled(&self, cx: &mut Context<'_, TextThreadEditor>) -> bool {
1961        let model_registry = LanguageModelRegistry::read_global(cx);
1962        let Some(configuration_error) =
1963            model_registry.configuration_error(model_registry.default_model(), cx)
1964        else {
1965            return false;
1966        };
1967
1968        match configuration_error {
1969            ConfigurationError::NoProvider
1970            | ConfigurationError::ModelNotFound
1971            | ConfigurationError::ProviderNotAuthenticated(_) => true,
1972        }
1973    }
1974
1975    fn render_inject_context_menu(&self, cx: &mut Context<Self>) -> impl IntoElement {
1976        slash_command_picker::SlashCommandSelector::new(
1977            self.slash_commands.clone(),
1978            cx.entity().downgrade(),
1979            IconButton::new("trigger", IconName::Plus)
1980                .icon_size(IconSize::Small)
1981                .icon_color(Color::Muted)
1982                .selected_icon_color(Color::Accent)
1983                .selected_style(ButtonStyle::Filled),
1984            move |window, cx| {
1985                Tooltip::with_meta(
1986                    "Add Context",
1987                    None,
1988                    "Type / to insert via keyboard",
1989                    window,
1990                    cx,
1991                )
1992            },
1993        )
1994    }
1995
1996    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
1997        let context = self.context().read(cx);
1998        let active_model = LanguageModelRegistry::read_global(cx)
1999            .default_model()
2000            .map(|default| default.model)?;
2001        if !active_model.supports_burn_mode() {
2002            return None;
2003        }
2004
2005        let active_completion_mode = context.completion_mode();
2006        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
2007        let icon = if burn_mode_enabled {
2008            IconName::ZedBurnModeOn
2009        } else {
2010            IconName::ZedBurnMode
2011        };
2012
2013        Some(
2014            IconButton::new("burn-mode", icon)
2015                .icon_size(IconSize::Small)
2016                .icon_color(Color::Muted)
2017                .toggle_state(burn_mode_enabled)
2018                .selected_icon_color(Color::Error)
2019                .on_click(cx.listener(move |this, _event, _window, cx| {
2020                    this.context().update(cx, |context, _cx| {
2021                        context.set_completion_mode(match active_completion_mode {
2022                            CompletionMode::Burn => CompletionMode::Normal,
2023                            CompletionMode::Normal => CompletionMode::Burn,
2024                        });
2025                    });
2026                }))
2027                .tooltip(move |_window, cx| {
2028                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
2029                        .into()
2030                })
2031                .into_any_element(),
2032        )
2033    }
2034
2035    fn render_language_model_selector(
2036        &self,
2037        window: &mut Window,
2038        cx: &mut Context<Self>,
2039    ) -> impl IntoElement {
2040        let active_model = LanguageModelRegistry::read_global(cx)
2041            .default_model()
2042            .map(|default| default.model);
2043        let model_name = match active_model {
2044            Some(model) => model.name().0,
2045            None => SharedString::from("Select Model"),
2046        };
2047
2048        let active_provider = LanguageModelRegistry::read_global(cx)
2049            .default_model()
2050            .map(|default| default.provider);
2051
2052        let provider_icon = match active_provider {
2053            Some(provider) => provider.icon(),
2054            None => IconName::Ai,
2055        };
2056
2057        let focus_handle = self.editor().focus_handle(cx);
2058        let (color, icon) = if self.language_model_selector_menu_handle.is_deployed() {
2059            (Color::Accent, IconName::ChevronUp)
2060        } else {
2061            (Color::Muted, IconName::ChevronDown)
2062        };
2063
2064        PickerPopoverMenu::new(
2065            self.language_model_selector.clone(),
2066            ButtonLike::new("active-model")
2067                .selected_style(ButtonStyle::Tinted(TintColor::Accent))
2068                .child(
2069                    h_flex()
2070                        .gap_0p5()
2071                        .child(Icon::new(provider_icon).color(color).size(IconSize::XSmall))
2072                        .child(
2073                            Label::new(model_name)
2074                                .color(color)
2075                                .size(LabelSize::Small)
2076                                .ml_0p5(),
2077                        )
2078                        .child(Icon::new(icon).color(color).size(IconSize::XSmall)),
2079                ),
2080            move |window, cx| {
2081                Tooltip::for_action_in(
2082                    "Change Model",
2083                    &ToggleModelSelector,
2084                    &focus_handle,
2085                    window,
2086                    cx,
2087                )
2088            },
2089            gpui::Corner::BottomRight,
2090            cx,
2091        )
2092        .with_handle(self.language_model_selector_menu_handle.clone())
2093        .render(window, cx)
2094    }
2095
2096    fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2097        let last_error = self.last_error.as_ref()?;
2098
2099        Some(
2100            div()
2101                .absolute()
2102                .right_3()
2103                .bottom_12()
2104                .max_w_96()
2105                .py_2()
2106                .px_3()
2107                .elevation_2(cx)
2108                .occlude()
2109                .child(match last_error {
2110                    AssistError::PaymentRequired => self.render_payment_required_error(cx),
2111                    AssistError::Message(error_message) => {
2112                        self.render_assist_error(error_message, cx)
2113                    }
2114                })
2115                .into_any(),
2116        )
2117    }
2118
2119    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2120        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.";
2121
2122        v_flex()
2123            .gap_0p5()
2124            .child(
2125                h_flex()
2126                    .gap_1p5()
2127                    .items_center()
2128                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2129                    .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2130            )
2131            .child(
2132                div()
2133                    .id("error-message")
2134                    .max_h_24()
2135                    .overflow_y_scroll()
2136                    .child(Label::new(ERROR_MESSAGE)),
2137            )
2138            .child(
2139                h_flex()
2140                    .justify_end()
2141                    .mt_1()
2142                    .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
2143                        |this, _, _window, cx| {
2144                            this.last_error = None;
2145                            cx.open_url(&zed_urls::account_url(cx));
2146                            cx.notify();
2147                        },
2148                    )))
2149                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2150                        |this, _, _window, cx| {
2151                            this.last_error = None;
2152                            cx.notify();
2153                        },
2154                    ))),
2155            )
2156            .into_any()
2157    }
2158
2159    fn render_assist_error(
2160        &self,
2161        error_message: &SharedString,
2162        cx: &mut Context<Self>,
2163    ) -> AnyElement {
2164        v_flex()
2165            .gap_0p5()
2166            .child(
2167                h_flex()
2168                    .gap_1p5()
2169                    .items_center()
2170                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2171                    .child(
2172                        Label::new("Error interacting with language model")
2173                            .weight(FontWeight::MEDIUM),
2174                    ),
2175            )
2176            .child(
2177                div()
2178                    .id("error-message")
2179                    .max_h_32()
2180                    .overflow_y_scroll()
2181                    .child(Label::new(error_message.clone())),
2182            )
2183            .child(
2184                h_flex()
2185                    .justify_end()
2186                    .mt_1()
2187                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2188                        |this, _, _window, cx| {
2189                            this.last_error = None;
2190                            cx.notify();
2191                        },
2192                    ))),
2193            )
2194            .into_any()
2195    }
2196}
2197
2198/// Returns the contents of the *outermost* fenced code block that contains the given offset.
2199fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
2200    const CODE_BLOCK_NODE: &str = "fenced_code_block";
2201    const CODE_BLOCK_CONTENT: &str = "code_fence_content";
2202
2203    let layer = snapshot.syntax_layers().next()?;
2204
2205    let root_node = layer.node();
2206    let mut cursor = root_node.walk();
2207
2208    // Go to the first child for the given offset
2209    while cursor.goto_first_child_for_byte(offset).is_some() {
2210        // If we're at the end of the node, go to the next one.
2211        // Example: if you have a fenced-code-block, and you're on the start of the line
2212        // right after the closing ```, you want to skip the fenced-code-block and
2213        // go to the next sibling.
2214        if cursor.node().end_byte() == offset {
2215            cursor.goto_next_sibling();
2216        }
2217
2218        if cursor.node().start_byte() > offset {
2219            break;
2220        }
2221
2222        // We found the fenced code block.
2223        if cursor.node().kind() == CODE_BLOCK_NODE {
2224            // Now we need to find the child node that contains the code.
2225            cursor.goto_first_child();
2226            loop {
2227                if cursor.node().kind() == CODE_BLOCK_CONTENT {
2228                    return Some(cursor.node().byte_range());
2229                }
2230                if !cursor.goto_next_sibling() {
2231                    break;
2232                }
2233            }
2234        }
2235    }
2236
2237    None
2238}
2239
2240fn render_thought_process_fold_icon_button(
2241    editor: WeakEntity<Editor>,
2242    status: ThoughtProcessStatus,
2243) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2244    Arc::new(move |fold_id, fold_range, _cx| {
2245        let editor = editor.clone();
2246
2247        let button = ButtonLike::new(fold_id).layer(ElevationIndex::ElevatedSurface);
2248        let button = match status {
2249            ThoughtProcessStatus::Pending => button
2250                .child(
2251                    Icon::new(IconName::ToolThink)
2252                        .size(IconSize::Small)
2253                        .color(Color::Muted),
2254                )
2255                .child(
2256                    Label::new("Thinking…").color(Color::Muted).with_animation(
2257                        "pulsating-label",
2258                        Animation::new(Duration::from_secs(2))
2259                            .repeat()
2260                            .with_easing(pulsating_between(0.4, 0.8)),
2261                        |label, delta| label.alpha(delta),
2262                    ),
2263                ),
2264            ThoughtProcessStatus::Completed => button
2265                .style(ButtonStyle::Filled)
2266                .child(Icon::new(IconName::ToolThink).size(IconSize::Small))
2267                .child(Label::new("Thought Process").single_line()),
2268        };
2269
2270        button
2271            .on_click(move |_, window, cx| {
2272                editor
2273                    .update(cx, |editor, cx| {
2274                        let buffer_start = fold_range
2275                            .start
2276                            .to_point(&editor.buffer().read(cx).read(cx));
2277                        let buffer_row = MultiBufferRow(buffer_start.row);
2278                        editor.unfold_at(buffer_row, window, cx);
2279                    })
2280                    .ok();
2281            })
2282            .into_any_element()
2283    })
2284}
2285
2286fn render_fold_icon_button(
2287    editor: WeakEntity<Editor>,
2288    icon_path: SharedString,
2289    label: SharedString,
2290) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2291    Arc::new(move |fold_id, fold_range, _cx| {
2292        let editor = editor.clone();
2293        ButtonLike::new(fold_id)
2294            .style(ButtonStyle::Filled)
2295            .layer(ElevationIndex::ElevatedSurface)
2296            .child(Icon::from_path(icon_path.clone()))
2297            .child(Label::new(label.clone()).single_line())
2298            .on_click(move |_, window, cx| {
2299                editor
2300                    .update(cx, |editor, cx| {
2301                        let buffer_start = fold_range
2302                            .start
2303                            .to_point(&editor.buffer().read(cx).read(cx));
2304                        let buffer_row = MultiBufferRow(buffer_start.row);
2305                        editor.unfold_at(buffer_row, window, cx);
2306                    })
2307                    .ok();
2308            })
2309            .into_any_element()
2310    })
2311}
2312
2313type ToggleFold = Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>;
2314
2315fn render_slash_command_output_toggle(
2316    row: MultiBufferRow,
2317    is_folded: bool,
2318    fold: ToggleFold,
2319    _window: &mut Window,
2320    _cx: &mut App,
2321) -> AnyElement {
2322    Disclosure::new(
2323        ("slash-command-output-fold-indicator", row.0 as u64),
2324        !is_folded,
2325    )
2326    .toggle_state(is_folded)
2327    .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2328    .into_any_element()
2329}
2330
2331pub fn fold_toggle(
2332    name: &'static str,
2333) -> impl Fn(
2334    MultiBufferRow,
2335    bool,
2336    Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
2337    &mut Window,
2338    &mut App,
2339) -> AnyElement {
2340    move |row, is_folded, fold, _window, _cx| {
2341        Disclosure::new((name, row.0 as u64), !is_folded)
2342            .toggle_state(is_folded)
2343            .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2344            .into_any_element()
2345    }
2346}
2347
2348fn quote_selection_fold_placeholder(title: String, editor: WeakEntity<Editor>) -> FoldPlaceholder {
2349    FoldPlaceholder {
2350        render: Arc::new({
2351            move |fold_id, fold_range, _cx| {
2352                let editor = editor.clone();
2353                ButtonLike::new(fold_id)
2354                    .style(ButtonStyle::Filled)
2355                    .layer(ElevationIndex::ElevatedSurface)
2356                    .child(Icon::new(IconName::TextSnippet))
2357                    .child(Label::new(title.clone()).single_line())
2358                    .on_click(move |_, window, cx| {
2359                        editor
2360                            .update(cx, |editor, cx| {
2361                                let buffer_start = fold_range
2362                                    .start
2363                                    .to_point(&editor.buffer().read(cx).read(cx));
2364                                let buffer_row = MultiBufferRow(buffer_start.row);
2365                                editor.unfold_at(buffer_row, window, cx);
2366                            })
2367                            .ok();
2368                    })
2369                    .into_any_element()
2370            }
2371        }),
2372        merge_adjacent: false,
2373        ..Default::default()
2374    }
2375}
2376
2377fn render_quote_selection_output_toggle(
2378    row: MultiBufferRow,
2379    is_folded: bool,
2380    fold: ToggleFold,
2381    _window: &mut Window,
2382    _cx: &mut App,
2383) -> AnyElement {
2384    Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
2385        .toggle_state(is_folded)
2386        .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2387        .into_any_element()
2388}
2389
2390fn render_pending_slash_command_gutter_decoration(
2391    row: MultiBufferRow,
2392    status: &PendingSlashCommandStatus,
2393    confirm_command: Arc<dyn Fn(&mut Window, &mut App)>,
2394) -> AnyElement {
2395    let mut icon = IconButton::new(
2396        ("slash-command-gutter-decoration", row.0),
2397        ui::IconName::TriangleRight,
2398    )
2399    .on_click(move |_e, window, cx| confirm_command(window, cx))
2400    .icon_size(ui::IconSize::Small)
2401    .size(ui::ButtonSize::None);
2402
2403    match status {
2404        PendingSlashCommandStatus::Idle => {
2405            icon = icon.icon_color(Color::Muted);
2406        }
2407        PendingSlashCommandStatus::Running { .. } => {
2408            icon = icon.toggle_state(true);
2409        }
2410        PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
2411    }
2412
2413    icon.into_any_element()
2414}
2415
2416#[derive(Debug, Clone, Serialize, Deserialize)]
2417struct CopyMetadata {
2418    creases: Vec<SelectedCreaseMetadata>,
2419}
2420
2421#[derive(Debug, Clone, Serialize, Deserialize)]
2422struct SelectedCreaseMetadata {
2423    range_relative_to_selection: Range<usize>,
2424    crease: CreaseMetadata,
2425}
2426
2427impl EventEmitter<EditorEvent> for TextThreadEditor {}
2428impl EventEmitter<SearchEvent> for TextThreadEditor {}
2429
2430impl Render for TextThreadEditor {
2431    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2432        let language_model_selector = self.language_model_selector_menu_handle.clone();
2433
2434        v_flex()
2435            .key_context("ContextEditor")
2436            .capture_action(cx.listener(TextThreadEditor::cancel))
2437            .capture_action(cx.listener(TextThreadEditor::save))
2438            .capture_action(cx.listener(TextThreadEditor::copy))
2439            .capture_action(cx.listener(TextThreadEditor::cut))
2440            .capture_action(cx.listener(TextThreadEditor::paste))
2441            .capture_action(cx.listener(TextThreadEditor::cycle_message_role))
2442            .capture_action(cx.listener(TextThreadEditor::confirm_command))
2443            .on_action(cx.listener(TextThreadEditor::assist))
2444            .on_action(cx.listener(TextThreadEditor::split))
2445            .on_action(move |_: &ToggleModelSelector, window, cx| {
2446                language_model_selector.toggle(window, cx);
2447            })
2448            .size_full()
2449            .child(
2450                div()
2451                    .flex_grow()
2452                    .bg(cx.theme().colors().editor_background)
2453                    .child(self.editor.clone()),
2454            )
2455            .children(self.render_last_error(cx))
2456            .child(
2457                h_flex()
2458                    .relative()
2459                    .py_2()
2460                    .pl_1p5()
2461                    .pr_2()
2462                    .w_full()
2463                    .justify_between()
2464                    .border_t_1()
2465                    .border_color(cx.theme().colors().border_variant)
2466                    .bg(cx.theme().colors().editor_background)
2467                    .child(
2468                        h_flex()
2469                            .gap_0p5()
2470                            .child(self.render_inject_context_menu(cx))
2471                            .children(self.render_burn_mode_toggle(cx)),
2472                    )
2473                    .child(
2474                        h_flex()
2475                            .gap_2p5()
2476                            .children(self.render_remaining_tokens(cx))
2477                            .child(
2478                                h_flex()
2479                                    .gap_1()
2480                                    .child(self.render_language_model_selector(window, cx))
2481                                    .child(self.render_send_button(window, cx)),
2482                            ),
2483                    ),
2484            )
2485    }
2486}
2487
2488impl Focusable for TextThreadEditor {
2489    fn focus_handle(&self, cx: &App) -> FocusHandle {
2490        self.editor.focus_handle(cx)
2491    }
2492}
2493
2494impl Item for TextThreadEditor {
2495    type Event = editor::EditorEvent;
2496
2497    fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
2498        util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into()
2499    }
2500
2501    fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
2502        match event {
2503            EditorEvent::Edited { .. } => {
2504                f(item::ItemEvent::Edit);
2505            }
2506            EditorEvent::TitleChanged => {
2507                f(item::ItemEvent::UpdateTab);
2508            }
2509            _ => {}
2510        }
2511    }
2512
2513    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
2514        Some(self.title(cx).to_string().into())
2515    }
2516
2517    fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
2518        Some(Box::new(handle.clone()))
2519    }
2520
2521    fn set_nav_history(
2522        &mut self,
2523        nav_history: pane::ItemNavHistory,
2524        window: &mut Window,
2525        cx: &mut Context<Self>,
2526    ) {
2527        self.editor.update(cx, |editor, cx| {
2528            Item::set_nav_history(editor, nav_history, window, cx)
2529        })
2530    }
2531
2532    fn navigate(
2533        &mut self,
2534        data: Box<dyn std::any::Any>,
2535        window: &mut Window,
2536        cx: &mut Context<Self>,
2537    ) -> bool {
2538        self.editor
2539            .update(cx, |editor, cx| Item::navigate(editor, data, window, cx))
2540    }
2541
2542    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2543        self.editor
2544            .update(cx, |editor, cx| Item::deactivated(editor, window, cx))
2545    }
2546
2547    fn act_as_type<'a>(
2548        &'a self,
2549        type_id: TypeId,
2550        self_handle: &'a Entity<Self>,
2551        _: &'a App,
2552    ) -> Option<AnyView> {
2553        if type_id == TypeId::of::<Self>() {
2554            Some(self_handle.to_any())
2555        } else if type_id == TypeId::of::<Editor>() {
2556            Some(self.editor.to_any())
2557        } else {
2558            None
2559        }
2560    }
2561
2562    fn include_in_nav_history() -> bool {
2563        false
2564    }
2565}
2566
2567impl SearchableItem for TextThreadEditor {
2568    type Match = <Editor as SearchableItem>::Match;
2569
2570    fn clear_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2571        self.editor.update(cx, |editor, cx| {
2572            editor.clear_matches(window, cx);
2573        });
2574    }
2575
2576    fn update_matches(
2577        &mut self,
2578        matches: &[Self::Match],
2579        window: &mut Window,
2580        cx: &mut Context<Self>,
2581    ) {
2582        self.editor
2583            .update(cx, |editor, cx| editor.update_matches(matches, window, cx));
2584    }
2585
2586    fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
2587        self.editor
2588            .update(cx, |editor, cx| editor.query_suggestion(window, cx))
2589    }
2590
2591    fn activate_match(
2592        &mut self,
2593        index: usize,
2594        matches: &[Self::Match],
2595        window: &mut Window,
2596        cx: &mut Context<Self>,
2597    ) {
2598        self.editor.update(cx, |editor, cx| {
2599            editor.activate_match(index, matches, window, cx);
2600        });
2601    }
2602
2603    fn select_matches(
2604        &mut self,
2605        matches: &[Self::Match],
2606        window: &mut Window,
2607        cx: &mut Context<Self>,
2608    ) {
2609        self.editor
2610            .update(cx, |editor, cx| editor.select_matches(matches, window, cx));
2611    }
2612
2613    fn replace(
2614        &mut self,
2615        identifier: &Self::Match,
2616        query: &project::search::SearchQuery,
2617        window: &mut Window,
2618        cx: &mut Context<Self>,
2619    ) {
2620        self.editor.update(cx, |editor, cx| {
2621            editor.replace(identifier, query, window, cx)
2622        });
2623    }
2624
2625    fn find_matches(
2626        &mut self,
2627        query: Arc<project::search::SearchQuery>,
2628        window: &mut Window,
2629        cx: &mut Context<Self>,
2630    ) -> Task<Vec<Self::Match>> {
2631        self.editor
2632            .update(cx, |editor, cx| editor.find_matches(query, window, cx))
2633    }
2634
2635    fn active_match_index(
2636        &mut self,
2637        direction: Direction,
2638        matches: &[Self::Match],
2639        window: &mut Window,
2640        cx: &mut Context<Self>,
2641    ) -> Option<usize> {
2642        self.editor.update(cx, |editor, cx| {
2643            editor.active_match_index(direction, matches, window, cx)
2644        })
2645    }
2646}
2647
2648impl FollowableItem for TextThreadEditor {
2649    fn remote_id(&self) -> Option<workspace::ViewId> {
2650        self.remote_id
2651    }
2652
2653    fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant> {
2654        let context = self.context.read(cx);
2655        Some(proto::view::Variant::ContextEditor(
2656            proto::view::ContextEditor {
2657                context_id: context.id().to_proto(),
2658                editor: if let Some(proto::view::Variant::Editor(proto)) =
2659                    self.editor.read(cx).to_state_proto(window, cx)
2660                {
2661                    Some(proto)
2662                } else {
2663                    None
2664                },
2665            },
2666        ))
2667    }
2668
2669    fn from_state_proto(
2670        workspace: Entity<Workspace>,
2671        id: workspace::ViewId,
2672        state: &mut Option<proto::view::Variant>,
2673        window: &mut Window,
2674        cx: &mut App,
2675    ) -> Option<Task<Result<Entity<Self>>>> {
2676        let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
2677            return None;
2678        };
2679        let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
2680            unreachable!()
2681        };
2682
2683        let context_id = ContextId::from_proto(state.context_id);
2684        let editor_state = state.editor?;
2685
2686        let project = workspace.read(cx).project().clone();
2687        let agent_panel_delegate = <dyn AgentPanelDelegate>::try_global(cx)?;
2688
2689        let context_editor_task = workspace.update(cx, |workspace, cx| {
2690            agent_panel_delegate.open_remote_context(workspace, context_id, window, cx)
2691        });
2692
2693        Some(window.spawn(cx, async move |cx| {
2694            let context_editor = context_editor_task.await?;
2695            context_editor
2696                .update_in(cx, |context_editor, window, cx| {
2697                    context_editor.remote_id = Some(id);
2698                    context_editor.editor.update(cx, |editor, cx| {
2699                        editor.apply_update_proto(
2700                            &project,
2701                            proto::update_view::Variant::Editor(proto::update_view::Editor {
2702                                selections: editor_state.selections,
2703                                pending_selection: editor_state.pending_selection,
2704                                scroll_top_anchor: editor_state.scroll_top_anchor,
2705                                scroll_x: editor_state.scroll_y,
2706                                scroll_y: editor_state.scroll_y,
2707                                ..Default::default()
2708                            }),
2709                            window,
2710                            cx,
2711                        )
2712                    })
2713                })?
2714                .await?;
2715            Ok(context_editor)
2716        }))
2717    }
2718
2719    fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
2720        Editor::to_follow_event(event)
2721    }
2722
2723    fn add_event_to_update_proto(
2724        &self,
2725        event: &Self::Event,
2726        update: &mut Option<proto::update_view::Variant>,
2727        window: &Window,
2728        cx: &App,
2729    ) -> bool {
2730        self.editor
2731            .read(cx)
2732            .add_event_to_update_proto(event, update, window, cx)
2733    }
2734
2735    fn apply_update_proto(
2736        &mut self,
2737        project: &Entity<Project>,
2738        message: proto::update_view::Variant,
2739        window: &mut Window,
2740        cx: &mut Context<Self>,
2741    ) -> Task<Result<()>> {
2742        self.editor.update(cx, |editor, cx| {
2743            editor.apply_update_proto(project, message, window, cx)
2744        })
2745    }
2746
2747    fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
2748        true
2749    }
2750
2751    fn set_leader_id(
2752        &mut self,
2753        leader_id: Option<CollaboratorId>,
2754        window: &mut Window,
2755        cx: &mut Context<Self>,
2756    ) {
2757        self.editor
2758            .update(cx, |editor, cx| editor.set_leader_id(leader_id, window, cx))
2759    }
2760
2761    fn dedup(&self, existing: &Self, _window: &Window, cx: &App) -> Option<item::Dedup> {
2762        if existing.context.read(cx).id() == self.context.read(cx).id() {
2763            Some(item::Dedup::KeepExisting)
2764        } else {
2765            None
2766        }
2767    }
2768}
2769
2770enum PendingSlashCommand {}
2771
2772fn invoked_slash_command_fold_placeholder(
2773    command_id: InvokedSlashCommandId,
2774    context: WeakEntity<AssistantContext>,
2775) -> FoldPlaceholder {
2776    FoldPlaceholder {
2777        constrain_width: false,
2778        merge_adjacent: false,
2779        render: Arc::new(move |fold_id, _, cx| {
2780            let Some(context) = context.upgrade() else {
2781                return Empty.into_any();
2782            };
2783
2784            let Some(command) = context.read(cx).invoked_slash_command(&command_id) else {
2785                return Empty.into_any();
2786            };
2787
2788            h_flex()
2789                .id(fold_id)
2790                .px_1()
2791                .ml_6()
2792                .gap_2()
2793                .bg(cx.theme().colors().surface_background)
2794                .rounded_sm()
2795                .child(Label::new(format!("/{}", command.name)))
2796                .map(|parent| match &command.status {
2797                    InvokedSlashCommandStatus::Running(_) => {
2798                        parent.child(Icon::new(IconName::ArrowCircle).with_rotate_animation(4))
2799                    }
2800                    InvokedSlashCommandStatus::Error(message) => parent.child(
2801                        Label::new(format!("error: {message}"))
2802                            .single_line()
2803                            .color(Color::Error),
2804                    ),
2805                    InvokedSlashCommandStatus::Finished => parent,
2806                })
2807                .into_any_element()
2808        }),
2809        type_tag: Some(TypeId::of::<PendingSlashCommand>()),
2810    }
2811}
2812
2813enum TokenState {
2814    NoTokensLeft {
2815        max_token_count: u64,
2816        token_count: u64,
2817    },
2818    HasMoreTokens {
2819        max_token_count: u64,
2820        token_count: u64,
2821        over_warn_threshold: bool,
2822    },
2823}
2824
2825fn token_state(context: &Entity<AssistantContext>, cx: &App) -> Option<TokenState> {
2826    const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
2827
2828    let model = LanguageModelRegistry::read_global(cx)
2829        .default_model()?
2830        .model;
2831    let token_count = context.read(cx).token_count()?;
2832    let max_token_count = model.max_token_count_for_mode(context.read(cx).completion_mode().into());
2833    let token_state = if max_token_count.saturating_sub(token_count) == 0 {
2834        TokenState::NoTokensLeft {
2835            max_token_count,
2836            token_count,
2837        }
2838    } else {
2839        let over_warn_threshold =
2840            token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
2841        TokenState::HasMoreTokens {
2842            max_token_count,
2843            token_count,
2844            over_warn_threshold,
2845        }
2846    };
2847    Some(token_state)
2848}
2849
2850fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
2851    let image_size = data
2852        .size(0)
2853        .map(|dimension| Pixels::from(u32::from(dimension)));
2854    let image_ratio = image_size.width / image_size.height;
2855    let bounds_ratio = max_size.width / max_size.height;
2856
2857    if image_size.width > max_size.width || image_size.height > max_size.height {
2858        if bounds_ratio > image_ratio {
2859            size(
2860                image_size.width * (max_size.height / image_size.height),
2861                max_size.height,
2862            )
2863        } else {
2864            size(
2865                max_size.width,
2866                image_size.height * (max_size.width / image_size.width),
2867            )
2868        }
2869    } else {
2870        size(image_size.width, image_size.height)
2871    }
2872}
2873
2874pub fn humanize_token_count(count: u64) -> String {
2875    match count {
2876        0..=999 => count.to_string(),
2877        1000..=9999 => {
2878            let thousands = count / 1000;
2879            let hundreds = (count % 1000 + 50) / 100;
2880            if hundreds == 0 {
2881                format!("{}k", thousands)
2882            } else if hundreds == 10 {
2883                format!("{}k", thousands + 1)
2884            } else {
2885                format!("{}.{}k", thousands, hundreds)
2886            }
2887        }
2888        1_000_000..=9_999_999 => {
2889            let millions = count / 1_000_000;
2890            let hundred_thousands = (count % 1_000_000 + 50_000) / 100_000;
2891            if hundred_thousands == 0 {
2892                format!("{}M", millions)
2893            } else if hundred_thousands == 10 {
2894                format!("{}M", millions + 1)
2895            } else {
2896                format!("{}.{}M", millions, hundred_thousands)
2897            }
2898        }
2899        10_000_000.. => format!("{}M", (count + 500_000) / 1_000_000),
2900        _ => format!("{}k", (count + 500) / 1000),
2901    }
2902}
2903
2904pub fn make_lsp_adapter_delegate(
2905    project: &Entity<Project>,
2906    cx: &mut App,
2907) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
2908    project.update(cx, |project, cx| {
2909        // TODO: Find the right worktree.
2910        let Some(worktree) = project.worktrees(cx).next() else {
2911            return Ok(None::<Arc<dyn LspAdapterDelegate>>);
2912        };
2913        let http_client = project.client().http_client();
2914        project.lsp_store().update(cx, |_, cx| {
2915            Ok(Some(LocalLspAdapterDelegate::new(
2916                project.languages().clone(),
2917                project.environment(),
2918                cx.weak_entity(),
2919                &worktree,
2920                http_client,
2921                project.fs().clone(),
2922                cx,
2923            ) as Arc<dyn LspAdapterDelegate>))
2924        })
2925    })
2926}
2927
2928#[cfg(test)]
2929mod tests {
2930    use super::*;
2931    use editor::SelectionEffects;
2932    use fs::FakeFs;
2933    use gpui::{App, TestAppContext, VisualTestContext};
2934    use indoc::indoc;
2935    use language::{Buffer, LanguageRegistry};
2936    use pretty_assertions::assert_eq;
2937    use prompt_store::PromptBuilder;
2938    use text::OffsetRangeExt;
2939    use unindent::Unindent;
2940    use util::path;
2941
2942    #[gpui::test]
2943    async fn test_copy_paste_whole_message(cx: &mut TestAppContext) {
2944        let (context, context_editor, mut cx) = setup_context_editor_text(vec![
2945            (Role::User, "What is the Zed editor?"),
2946            (
2947                Role::Assistant,
2948                "Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.",
2949            ),
2950            (Role::User, ""),
2951        ],cx).await;
2952
2953        // Select & Copy whole user message
2954        assert_copy_paste_context_editor(
2955            &context_editor,
2956            message_range(&context, 0, &mut cx),
2957            indoc! {"
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                What is the Zed editor?
2961            "},
2962            &mut cx,
2963        );
2964
2965        // Select & Copy whole assistant message
2966        assert_copy_paste_context_editor(
2967            &context_editor,
2968            message_range(&context, 1, &mut cx),
2969            indoc! {"
2970                What is the Zed editor?
2971                Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
2972                What is the Zed editor?
2973                Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
2974            "},
2975            &mut cx,
2976        );
2977    }
2978
2979    #[gpui::test]
2980    async fn test_copy_paste_no_selection(cx: &mut TestAppContext) {
2981        let (context, context_editor, mut cx) = setup_context_editor_text(
2982            vec![
2983                (Role::User, "user1"),
2984                (Role::Assistant, "assistant1"),
2985                (Role::Assistant, "assistant2"),
2986                (Role::User, ""),
2987            ],
2988            cx,
2989        )
2990        .await;
2991
2992        // Copy and paste first assistant message
2993        let message_2_range = message_range(&context, 1, &mut cx);
2994        assert_copy_paste_context_editor(
2995            &context_editor,
2996            message_2_range.start..message_2_range.start,
2997            indoc! {"
2998                user1
2999                assistant1
3000                assistant2
3001                assistant1
3002            "},
3003            &mut cx,
3004        );
3005
3006        // Copy and cut second assistant message
3007        let message_3_range = message_range(&context, 2, &mut cx);
3008        assert_copy_paste_context_editor(
3009            &context_editor,
3010            message_3_range.start..message_3_range.start,
3011            indoc! {"
3012                user1
3013                assistant1
3014                assistant2
3015                assistant1
3016                assistant2
3017            "},
3018            &mut cx,
3019        );
3020    }
3021
3022    #[gpui::test]
3023    fn test_find_code_blocks(cx: &mut App) {
3024        let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
3025
3026        let buffer = cx.new(|cx| {
3027            let text = r#"
3028                line 0
3029                line 1
3030                ```rust
3031                fn main() {}
3032                ```
3033                line 5
3034                line 6
3035                line 7
3036                ```go
3037                func main() {}
3038                ```
3039                line 11
3040                ```
3041                this is plain text code block
3042                ```
3043
3044                ```go
3045                func another() {}
3046                ```
3047                line 19
3048            "#
3049            .unindent();
3050            let mut buffer = Buffer::local(text, cx);
3051            buffer.set_language(Some(markdown.clone()), cx);
3052            buffer
3053        });
3054        let snapshot = buffer.read(cx).snapshot();
3055
3056        let code_blocks = vec![
3057            Point::new(3, 0)..Point::new(4, 0),
3058            Point::new(9, 0)..Point::new(10, 0),
3059            Point::new(13, 0)..Point::new(14, 0),
3060            Point::new(17, 0)..Point::new(18, 0),
3061        ]
3062        .into_iter()
3063        .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
3064        .collect::<Vec<_>>();
3065
3066        let expected_results = vec![
3067            (0, None),
3068            (1, None),
3069            (2, Some(code_blocks[0].clone())),
3070            (3, Some(code_blocks[0].clone())),
3071            (4, Some(code_blocks[0].clone())),
3072            (5, None),
3073            (6, None),
3074            (7, None),
3075            (8, Some(code_blocks[1].clone())),
3076            (9, Some(code_blocks[1].clone())),
3077            (10, Some(code_blocks[1].clone())),
3078            (11, None),
3079            (12, Some(code_blocks[2].clone())),
3080            (13, Some(code_blocks[2].clone())),
3081            (14, Some(code_blocks[2].clone())),
3082            (15, None),
3083            (16, Some(code_blocks[3].clone())),
3084            (17, Some(code_blocks[3].clone())),
3085            (18, Some(code_blocks[3].clone())),
3086            (19, None),
3087        ];
3088
3089        for (row, expected) in expected_results {
3090            let offset = snapshot.point_to_offset(Point::new(row, 0));
3091            let range = find_surrounding_code_block(&snapshot, offset);
3092            assert_eq!(range, expected, "unexpected result on row {:?}", row);
3093        }
3094    }
3095
3096    async fn setup_context_editor_text(
3097        messages: Vec<(Role, &str)>,
3098        cx: &mut TestAppContext,
3099    ) -> (
3100        Entity<AssistantContext>,
3101        Entity<TextThreadEditor>,
3102        VisualTestContext,
3103    ) {
3104        cx.update(init_test);
3105
3106        let fs = FakeFs::new(cx.executor());
3107        let context = create_context_with_messages(messages, cx);
3108
3109        let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
3110        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
3111        let workspace = window.root(cx).unwrap();
3112        let mut cx = VisualTestContext::from_window(*window, cx);
3113
3114        let context_editor = window
3115            .update(&mut cx, |_, window, cx| {
3116                cx.new(|cx| {
3117                    TextThreadEditor::for_context(
3118                        context.clone(),
3119                        fs,
3120                        workspace.downgrade(),
3121                        project,
3122                        None,
3123                        window,
3124                        cx,
3125                    )
3126                })
3127            })
3128            .unwrap();
3129
3130        (context, context_editor, cx)
3131    }
3132
3133    fn message_range(
3134        context: &Entity<AssistantContext>,
3135        message_ix: usize,
3136        cx: &mut TestAppContext,
3137    ) -> Range<usize> {
3138        context.update(cx, |context, cx| {
3139            context
3140                .messages(cx)
3141                .nth(message_ix)
3142                .unwrap()
3143                .anchor_range
3144                .to_offset(&context.buffer().read(cx).snapshot())
3145        })
3146    }
3147
3148    fn assert_copy_paste_context_editor<T: editor::ToOffset>(
3149        context_editor: &Entity<TextThreadEditor>,
3150        range: Range<T>,
3151        expected_text: &str,
3152        cx: &mut VisualTestContext,
3153    ) {
3154        context_editor.update_in(cx, |context_editor, window, cx| {
3155            context_editor.editor.update(cx, |editor, cx| {
3156                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
3157                    s.select_ranges([range])
3158                });
3159            });
3160
3161            context_editor.copy(&Default::default(), window, cx);
3162
3163            context_editor.editor.update(cx, |editor, cx| {
3164                editor.move_to_end(&Default::default(), window, cx);
3165            });
3166
3167            context_editor.paste(&Default::default(), window, cx);
3168
3169            context_editor.editor.update(cx, |editor, cx| {
3170                assert_eq!(editor.text(cx), expected_text);
3171            });
3172        });
3173    }
3174
3175    fn create_context_with_messages(
3176        mut messages: Vec<(Role, &str)>,
3177        cx: &mut TestAppContext,
3178    ) -> Entity<AssistantContext> {
3179        let registry = Arc::new(LanguageRegistry::test(cx.executor()));
3180        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3181        cx.new(|cx| {
3182            let mut context = AssistantContext::local(
3183                registry,
3184                None,
3185                None,
3186                prompt_builder.clone(),
3187                Arc::new(SlashCommandWorkingSet::default()),
3188                cx,
3189            );
3190            let mut message_1 = context.messages(cx).next().unwrap();
3191            let (role, text) = messages.remove(0);
3192
3193            loop {
3194                if role == message_1.role {
3195                    context.buffer().update(cx, |buffer, cx| {
3196                        buffer.edit([(message_1.offset_range, text)], None, cx);
3197                    });
3198                    break;
3199                }
3200                let mut ids = HashSet::default();
3201                ids.insert(message_1.id);
3202                context.cycle_message_roles(ids, cx);
3203                message_1 = context.messages(cx).next().unwrap();
3204            }
3205
3206            let mut last_message_id = message_1.id;
3207            for (role, text) in messages {
3208                context.insert_message_after(last_message_id, role, MessageStatus::Done, cx);
3209                let message = context.messages(cx).last().unwrap();
3210                last_message_id = message.id;
3211                context.buffer().update(cx, |buffer, cx| {
3212                    buffer.edit([(message.offset_range, text)], None, cx);
3213                })
3214            }
3215
3216            context
3217        })
3218    }
3219
3220    fn init_test(cx: &mut App) {
3221        let settings_store = SettingsStore::test(cx);
3222        prompt_store::init(cx);
3223        LanguageModelRegistry::test(cx);
3224        cx.set_global(settings_store);
3225        language::init(cx);
3226        agent_settings::init(cx);
3227        Project::init_settings(cx);
3228        theme::init(theme::LoadThemes::JustBase, cx);
3229        workspace::init_settings(cx);
3230        editor::init_settings(cx);
3231    }
3232}