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