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 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        let metadata = if let Some(item) = cx.read_from_clipboard() {
1697            item.entries().first().and_then(|entry| {
1698                if let ClipboardEntry::String(text) = entry {
1699                    text.metadata_json::<CopyMetadata>()
1700                } else {
1701                    None
1702                }
1703            })
1704        } else {
1705            None
1706        };
1707
1708        if images.is_empty() {
1709            self.editor.update(cx, |editor, cx| {
1710                let paste_position = editor
1711                    .selections
1712                    .newest::<usize>(&editor.display_snapshot(cx))
1713                    .head();
1714                editor.paste(action, window, cx);
1715
1716                if let Some(metadata) = metadata {
1717                    let buffer = editor.buffer().read(cx).snapshot(cx);
1718
1719                    let mut buffer_rows_to_fold = BTreeSet::new();
1720                    let weak_editor = cx.entity().downgrade();
1721                    editor.insert_creases(
1722                        metadata.creases.into_iter().map(|metadata| {
1723                            let start = buffer.anchor_after(
1724                                paste_position + metadata.range_relative_to_selection.start,
1725                            );
1726                            let end = buffer.anchor_before(
1727                                paste_position + metadata.range_relative_to_selection.end,
1728                            );
1729
1730                            let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1731                            buffer_rows_to_fold.insert(buffer_row);
1732                            Crease::inline(
1733                                start..end,
1734                                FoldPlaceholder {
1735                                    render: render_fold_icon_button(
1736                                        weak_editor.clone(),
1737                                        metadata.crease.icon_path.clone(),
1738                                        metadata.crease.label.clone(),
1739                                    ),
1740                                    ..Default::default()
1741                                },
1742                                render_slash_command_output_toggle,
1743                                |_, _, _, _| Empty.into_any(),
1744                            )
1745                            .with_metadata(metadata.crease)
1746                        }),
1747                        cx,
1748                    );
1749                    for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1750                        editor.fold_at(buffer_row, window, cx);
1751                    }
1752                }
1753            });
1754        } else {
1755            let mut image_positions = Vec::new();
1756            self.editor.update(cx, |editor, cx| {
1757                editor.transact(window, cx, |editor, _window, cx| {
1758                    let edits = editor
1759                        .selections
1760                        .all::<usize>(&editor.display_snapshot(cx))
1761                        .into_iter()
1762                        .map(|selection| (selection.start..selection.end, "\n"));
1763                    editor.edit(edits, cx);
1764
1765                    let snapshot = editor.buffer().read(cx).snapshot(cx);
1766                    for selection in editor.selections.all::<usize>(&editor.display_snapshot(cx)) {
1767                        image_positions.push(snapshot.anchor_before(selection.end));
1768                    }
1769                });
1770            });
1771
1772            self.text_thread.update(cx, |text_thread, cx| {
1773                for image in images {
1774                    let Some(render_image) = image.to_image_data(cx.svg_renderer()).log_err()
1775                    else {
1776                        continue;
1777                    };
1778                    let image_id = image.id();
1779                    let image_task = LanguageModelImage::from_image(Arc::new(image), cx).shared();
1780
1781                    for image_position in image_positions.iter() {
1782                        text_thread.insert_content(
1783                            Content::Image {
1784                                anchor: image_position.text_anchor,
1785                                image_id,
1786                                image: image_task.clone(),
1787                                render_image: render_image.clone(),
1788                            },
1789                            cx,
1790                        );
1791                    }
1792                }
1793            });
1794        }
1795    }
1796
1797    fn update_image_blocks(&mut self, cx: &mut Context<Self>) {
1798        self.editor.update(cx, |editor, cx| {
1799            let buffer = editor.buffer().read(cx).snapshot(cx);
1800            let excerpt_id = *buffer.as_singleton().unwrap().0;
1801            let old_blocks = std::mem::take(&mut self.image_blocks);
1802            let new_blocks = self
1803                .text_thread
1804                .read(cx)
1805                .contents(cx)
1806                .map(
1807                    |Content::Image {
1808                         anchor,
1809                         render_image,
1810                         ..
1811                     }| (anchor, render_image),
1812                )
1813                .filter_map(|(anchor, render_image)| {
1814                    const MAX_HEIGHT_IN_LINES: u32 = 8;
1815                    let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
1816                    let image = render_image;
1817                    anchor.is_valid(&buffer).then(|| BlockProperties {
1818                        placement: BlockPlacement::Above(anchor),
1819                        height: Some(MAX_HEIGHT_IN_LINES),
1820                        style: BlockStyle::Sticky,
1821                        render: Arc::new(move |cx| {
1822                            let image_size = size_for_image(
1823                                &image,
1824                                size(
1825                                    cx.max_width - cx.margins.gutter.full_width(),
1826                                    MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
1827                                ),
1828                            );
1829                            h_flex()
1830                                .pl(cx.margins.gutter.full_width())
1831                                .child(
1832                                    img(image.clone())
1833                                        .object_fit(gpui::ObjectFit::ScaleDown)
1834                                        .w(image_size.width)
1835                                        .h(image_size.height),
1836                                )
1837                                .into_any_element()
1838                        }),
1839                        priority: 0,
1840                    })
1841                })
1842                .collect::<Vec<_>>();
1843
1844            editor.remove_blocks(old_blocks, None, cx);
1845            let ids = editor.insert_blocks(new_blocks, None, cx);
1846            self.image_blocks = HashSet::from_iter(ids);
1847        });
1848    }
1849
1850    fn split(&mut self, _: &Split, _window: &mut Window, cx: &mut Context<Self>) {
1851        self.text_thread.update(cx, |text_thread, cx| {
1852            let selections = self.editor.read(cx).selections.disjoint_anchors_arc();
1853            for selection in selections.as_ref() {
1854                let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
1855                let range = selection
1856                    .map(|endpoint| endpoint.to_offset(&buffer))
1857                    .range();
1858                text_thread.split_message(range, cx);
1859            }
1860        });
1861    }
1862
1863    fn save(&mut self, _: &Save, _window: &mut Window, cx: &mut Context<Self>) {
1864        self.text_thread.update(cx, |text_thread, cx| {
1865            text_thread.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
1866        });
1867    }
1868
1869    pub fn title(&self, cx: &App) -> SharedString {
1870        self.text_thread.read(cx).summary().or_default()
1871    }
1872
1873    pub fn regenerate_summary(&mut self, cx: &mut Context<Self>) {
1874        self.text_thread
1875            .update(cx, |text_thread, cx| text_thread.summarize(true, cx));
1876    }
1877
1878    fn render_remaining_tokens(&self, cx: &App) -> Option<impl IntoElement + use<>> {
1879        let (token_count_color, token_count, max_token_count, tooltip) =
1880            match token_state(&self.text_thread, cx)? {
1881                TokenState::NoTokensLeft {
1882                    max_token_count,
1883                    token_count,
1884                } => (
1885                    Color::Error,
1886                    token_count,
1887                    max_token_count,
1888                    Some("Token Limit Reached"),
1889                ),
1890                TokenState::HasMoreTokens {
1891                    max_token_count,
1892                    token_count,
1893                    over_warn_threshold,
1894                } => {
1895                    let (color, tooltip) = if over_warn_threshold {
1896                        (Color::Warning, Some("Token Limit is Close to Exhaustion"))
1897                    } else {
1898                        (Color::Muted, None)
1899                    };
1900                    (color, token_count, max_token_count, tooltip)
1901                }
1902            };
1903
1904        Some(
1905            h_flex()
1906                .id("token-count")
1907                .gap_0p5()
1908                .child(
1909                    Label::new(humanize_token_count(token_count))
1910                        .size(LabelSize::Small)
1911                        .color(token_count_color),
1912                )
1913                .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
1914                .child(
1915                    Label::new(humanize_token_count(max_token_count))
1916                        .size(LabelSize::Small)
1917                        .color(Color::Muted),
1918                )
1919                .when_some(tooltip, |element, tooltip| {
1920                    element.tooltip(Tooltip::text(tooltip))
1921                }),
1922        )
1923    }
1924
1925    fn render_send_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1926        let focus_handle = self.focus_handle(cx);
1927
1928        let (style, tooltip) = match token_state(&self.text_thread, cx) {
1929            Some(TokenState::NoTokensLeft { .. }) => (
1930                ButtonStyle::Tinted(TintColor::Error),
1931                Some(Tooltip::text("Token limit reached")(window, cx)),
1932            ),
1933            Some(TokenState::HasMoreTokens {
1934                over_warn_threshold,
1935                ..
1936            }) => {
1937                let (style, tooltip) = if over_warn_threshold {
1938                    (
1939                        ButtonStyle::Tinted(TintColor::Warning),
1940                        Some(Tooltip::text("Token limit is close to exhaustion")(
1941                            window, cx,
1942                        )),
1943                    )
1944                } else {
1945                    (ButtonStyle::Filled, None)
1946                };
1947                (style, tooltip)
1948            }
1949            None => (ButtonStyle::Filled, None),
1950        };
1951
1952        Button::new("send_button", "Send")
1953            .label_size(LabelSize::Small)
1954            .disabled(self.sending_disabled(cx))
1955            .style(style)
1956            .when_some(tooltip, |button, tooltip| {
1957                button.tooltip(move |_, _| tooltip.clone())
1958            })
1959            .layer(ElevationIndex::ModalSurface)
1960            .key_binding(
1961                KeyBinding::for_action_in(&Assist, &focus_handle, cx)
1962                    .map(|kb| kb.size(rems_from_px(12.))),
1963            )
1964            .on_click(move |_event, window, cx| {
1965                focus_handle.dispatch_action(&Assist, window, cx);
1966            })
1967    }
1968
1969    /// Whether or not we should allow messages to be sent.
1970    /// Will return false if the selected provided has a configuration error or
1971    /// if the user has not accepted the terms of service for this provider.
1972    fn sending_disabled(&self, cx: &mut Context<'_, TextThreadEditor>) -> bool {
1973        let model_registry = LanguageModelRegistry::read_global(cx);
1974        let Some(configuration_error) =
1975            model_registry.configuration_error(model_registry.default_model(), cx)
1976        else {
1977            return false;
1978        };
1979
1980        match configuration_error {
1981            ConfigurationError::NoProvider
1982            | ConfigurationError::ModelNotFound
1983            | ConfigurationError::ProviderNotAuthenticated(_) => true,
1984        }
1985    }
1986
1987    fn render_inject_context_menu(&self, cx: &mut Context<Self>) -> impl IntoElement {
1988        slash_command_picker::SlashCommandSelector::new(
1989            self.slash_commands.clone(),
1990            cx.entity().downgrade(),
1991            IconButton::new("trigger", IconName::Plus)
1992                .icon_size(IconSize::Small)
1993                .icon_color(Color::Muted)
1994                .selected_icon_color(Color::Accent)
1995                .selected_style(ButtonStyle::Filled),
1996            move |_window, cx| {
1997                Tooltip::with_meta("Add Context", None, "Type / to insert via keyboard", cx)
1998            },
1999        )
2000    }
2001
2002    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2003        let text_thread = self.text_thread().read(cx);
2004        let active_model = LanguageModelRegistry::read_global(cx)
2005            .default_model()
2006            .map(|default| default.model)?;
2007        if !active_model.supports_burn_mode() {
2008            return None;
2009        }
2010
2011        let active_completion_mode = text_thread.completion_mode();
2012        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
2013        let icon = if burn_mode_enabled {
2014            IconName::ZedBurnModeOn
2015        } else {
2016            IconName::ZedBurnMode
2017        };
2018
2019        Some(
2020            IconButton::new("burn-mode", icon)
2021                .icon_size(IconSize::Small)
2022                .icon_color(Color::Muted)
2023                .toggle_state(burn_mode_enabled)
2024                .selected_icon_color(Color::Error)
2025                .on_click(cx.listener(move |this, _event, _window, cx| {
2026                    this.text_thread().update(cx, |text_thread, _cx| {
2027                        text_thread.set_completion_mode(match active_completion_mode {
2028                            CompletionMode::Burn => CompletionMode::Normal,
2029                            CompletionMode::Normal => CompletionMode::Burn,
2030                        });
2031                    });
2032                }))
2033                .tooltip(move |_window, cx| {
2034                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
2035                        .into()
2036                })
2037                .into_any_element(),
2038        )
2039    }
2040
2041    fn render_language_model_selector(
2042        &self,
2043        window: &mut Window,
2044        cx: &mut Context<Self>,
2045    ) -> impl IntoElement {
2046        let active_model = LanguageModelRegistry::read_global(cx)
2047            .default_model()
2048            .map(|default| default.model);
2049        let model_name = match active_model {
2050            Some(model) => model.name().0,
2051            None => SharedString::from("Select Model"),
2052        };
2053
2054        let active_provider = LanguageModelRegistry::read_global(cx)
2055            .default_model()
2056            .map(|default| default.provider);
2057
2058        let provider_icon = match active_provider {
2059            Some(provider) => provider.icon(),
2060            None => IconName::Ai,
2061        };
2062
2063        let focus_handle = self.editor().focus_handle(cx);
2064        let (color, icon) = if self.language_model_selector_menu_handle.is_deployed() {
2065            (Color::Accent, IconName::ChevronUp)
2066        } else {
2067            (Color::Muted, IconName::ChevronDown)
2068        };
2069
2070        PickerPopoverMenu::new(
2071            self.language_model_selector.clone(),
2072            ButtonLike::new("active-model")
2073                .selected_style(ButtonStyle::Tinted(TintColor::Accent))
2074                .child(
2075                    h_flex()
2076                        .gap_0p5()
2077                        .child(Icon::new(provider_icon).color(color).size(IconSize::XSmall))
2078                        .child(
2079                            Label::new(model_name)
2080                                .color(color)
2081                                .size(LabelSize::Small)
2082                                .ml_0p5(),
2083                        )
2084                        .child(Icon::new(icon).color(color).size(IconSize::XSmall)),
2085                ),
2086            move |_window, cx| {
2087                Tooltip::for_action_in("Change Model", &ToggleModelSelector, &focus_handle, cx)
2088            },
2089            gpui::Corner::BottomRight,
2090            cx,
2091        )
2092        .with_handle(self.language_model_selector_menu_handle.clone())
2093        .render(window, cx)
2094    }
2095
2096    fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2097        let last_error = self.last_error.as_ref()?;
2098
2099        Some(
2100            div()
2101                .absolute()
2102                .right_3()
2103                .bottom_12()
2104                .max_w_96()
2105                .py_2()
2106                .px_3()
2107                .elevation_2(cx)
2108                .occlude()
2109                .child(match last_error {
2110                    AssistError::PaymentRequired => self.render_payment_required_error(cx),
2111                    AssistError::Message(error_message) => {
2112                        self.render_assist_error(error_message, cx)
2113                    }
2114                })
2115                .into_any(),
2116        )
2117    }
2118
2119    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2120        const ERROR_MESSAGE: &str = "Free tier exceeded. Subscribe and add payment to continue using Zed LLMs. You'll be billed at cost for tokens used.";
2121
2122        v_flex()
2123            .gap_0p5()
2124            .child(
2125                h_flex()
2126                    .gap_1p5()
2127                    .items_center()
2128                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2129                    .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2130            )
2131            .child(
2132                div()
2133                    .id("error-message")
2134                    .max_h_24()
2135                    .overflow_y_scroll()
2136                    .child(Label::new(ERROR_MESSAGE)),
2137            )
2138            .child(
2139                h_flex()
2140                    .justify_end()
2141                    .mt_1()
2142                    .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
2143                        |this, _, _window, cx| {
2144                            this.last_error = None;
2145                            cx.open_url(&zed_urls::account_url(cx));
2146                            cx.notify();
2147                        },
2148                    )))
2149                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2150                        |this, _, _window, cx| {
2151                            this.last_error = None;
2152                            cx.notify();
2153                        },
2154                    ))),
2155            )
2156            .into_any()
2157    }
2158
2159    fn render_assist_error(
2160        &self,
2161        error_message: &SharedString,
2162        cx: &mut Context<Self>,
2163    ) -> AnyElement {
2164        v_flex()
2165            .gap_0p5()
2166            .child(
2167                h_flex()
2168                    .gap_1p5()
2169                    .items_center()
2170                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2171                    .child(
2172                        Label::new("Error interacting with language model")
2173                            .weight(FontWeight::MEDIUM),
2174                    ),
2175            )
2176            .child(
2177                div()
2178                    .id("error-message")
2179                    .max_h_32()
2180                    .overflow_y_scroll()
2181                    .child(Label::new(error_message.clone())),
2182            )
2183            .child(
2184                h_flex()
2185                    .justify_end()
2186                    .mt_1()
2187                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2188                        |this, _, _window, cx| {
2189                            this.last_error = None;
2190                            cx.notify();
2191                        },
2192                    ))),
2193            )
2194            .into_any()
2195    }
2196}
2197
2198/// Returns the contents of the *outermost* fenced code block that contains the given offset.
2199fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
2200    const CODE_BLOCK_NODE: &str = "fenced_code_block";
2201    const CODE_BLOCK_CONTENT: &str = "code_fence_content";
2202
2203    let layer = snapshot.syntax_layers().next()?;
2204
2205    let root_node = layer.node();
2206    let mut cursor = root_node.walk();
2207
2208    // Go to the first child for the given offset
2209    while cursor.goto_first_child_for_byte(offset).is_some() {
2210        // If we're at the end of the node, go to the next one.
2211        // Example: if you have a fenced-code-block, and you're on the start of the line
2212        // right after the closing ```, you want to skip the fenced-code-block and
2213        // go to the next sibling.
2214        if cursor.node().end_byte() == offset {
2215            cursor.goto_next_sibling();
2216        }
2217
2218        if cursor.node().start_byte() > offset {
2219            break;
2220        }
2221
2222        // We found the fenced code block.
2223        if cursor.node().kind() == CODE_BLOCK_NODE {
2224            // Now we need to find the child node that contains the code.
2225            cursor.goto_first_child();
2226            loop {
2227                if cursor.node().kind() == CODE_BLOCK_CONTENT {
2228                    return Some(cursor.node().byte_range());
2229                }
2230                if !cursor.goto_next_sibling() {
2231                    break;
2232                }
2233            }
2234        }
2235    }
2236
2237    None
2238}
2239
2240fn render_thought_process_fold_icon_button(
2241    editor: WeakEntity<Editor>,
2242    status: ThoughtProcessStatus,
2243) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2244    Arc::new(move |fold_id, fold_range, _cx| {
2245        let editor = editor.clone();
2246
2247        let button = ButtonLike::new(fold_id).layer(ElevationIndex::ElevatedSurface);
2248        let button = match status {
2249            ThoughtProcessStatus::Pending => button
2250                .child(
2251                    Icon::new(IconName::ToolThink)
2252                        .size(IconSize::Small)
2253                        .color(Color::Muted),
2254                )
2255                .child(
2256                    Label::new("Thinking…").color(Color::Muted).with_animation(
2257                        "pulsating-label",
2258                        Animation::new(Duration::from_secs(2))
2259                            .repeat()
2260                            .with_easing(pulsating_between(0.4, 0.8)),
2261                        |label, delta| label.alpha(delta),
2262                    ),
2263                ),
2264            ThoughtProcessStatus::Completed => button
2265                .style(ButtonStyle::Filled)
2266                .child(Icon::new(IconName::ToolThink).size(IconSize::Small))
2267                .child(Label::new("Thought Process").single_line()),
2268        };
2269
2270        button
2271            .on_click(move |_, window, cx| {
2272                editor
2273                    .update(cx, |editor, cx| {
2274                        let buffer_start = fold_range
2275                            .start
2276                            .to_point(&editor.buffer().read(cx).read(cx));
2277                        let buffer_row = MultiBufferRow(buffer_start.row);
2278                        editor.unfold_at(buffer_row, window, cx);
2279                    })
2280                    .ok();
2281            })
2282            .into_any_element()
2283    })
2284}
2285
2286fn render_fold_icon_button(
2287    editor: WeakEntity<Editor>,
2288    icon_path: SharedString,
2289    label: SharedString,
2290) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2291    Arc::new(move |fold_id, fold_range, _cx| {
2292        let editor = editor.clone();
2293        ButtonLike::new(fold_id)
2294            .style(ButtonStyle::Filled)
2295            .layer(ElevationIndex::ElevatedSurface)
2296            .child(Icon::from_path(icon_path.clone()))
2297            .child(Label::new(label.clone()).single_line())
2298            .on_click(move |_, window, cx| {
2299                editor
2300                    .update(cx, |editor, cx| {
2301                        let buffer_start = fold_range
2302                            .start
2303                            .to_point(&editor.buffer().read(cx).read(cx));
2304                        let buffer_row = MultiBufferRow(buffer_start.row);
2305                        editor.unfold_at(buffer_row, window, cx);
2306                    })
2307                    .ok();
2308            })
2309            .into_any_element()
2310    })
2311}
2312
2313type ToggleFold = Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>;
2314
2315fn render_slash_command_output_toggle(
2316    row: MultiBufferRow,
2317    is_folded: bool,
2318    fold: ToggleFold,
2319    _window: &mut Window,
2320    _cx: &mut App,
2321) -> AnyElement {
2322    Disclosure::new(
2323        ("slash-command-output-fold-indicator", row.0 as u64),
2324        !is_folded,
2325    )
2326    .toggle_state(is_folded)
2327    .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2328    .into_any_element()
2329}
2330
2331pub fn fold_toggle(
2332    name: &'static str,
2333) -> impl Fn(
2334    MultiBufferRow,
2335    bool,
2336    Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
2337    &mut Window,
2338    &mut App,
2339) -> AnyElement {
2340    move |row, is_folded, fold, _window, _cx| {
2341        Disclosure::new((name, row.0 as u64), !is_folded)
2342            .toggle_state(is_folded)
2343            .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2344            .into_any_element()
2345    }
2346}
2347
2348fn quote_selection_fold_placeholder(title: String, editor: WeakEntity<Editor>) -> FoldPlaceholder {
2349    FoldPlaceholder {
2350        render: Arc::new({
2351            move |fold_id, fold_range, _cx| {
2352                let editor = editor.clone();
2353                ButtonLike::new(fold_id)
2354                    .style(ButtonStyle::Filled)
2355                    .layer(ElevationIndex::ElevatedSurface)
2356                    .child(Icon::new(IconName::TextSnippet))
2357                    .child(Label::new(title.clone()).single_line())
2358                    .on_click(move |_, window, cx| {
2359                        editor
2360                            .update(cx, |editor, cx| {
2361                                let buffer_start = fold_range
2362                                    .start
2363                                    .to_point(&editor.buffer().read(cx).read(cx));
2364                                let buffer_row = MultiBufferRow(buffer_start.row);
2365                                editor.unfold_at(buffer_row, window, cx);
2366                            })
2367                            .ok();
2368                    })
2369                    .into_any_element()
2370            }
2371        }),
2372        merge_adjacent: false,
2373        ..Default::default()
2374    }
2375}
2376
2377fn render_quote_selection_output_toggle(
2378    row: MultiBufferRow,
2379    is_folded: bool,
2380    fold: ToggleFold,
2381    _window: &mut Window,
2382    _cx: &mut App,
2383) -> AnyElement {
2384    Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
2385        .toggle_state(is_folded)
2386        .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2387        .into_any_element()
2388}
2389
2390fn render_pending_slash_command_gutter_decoration(
2391    row: MultiBufferRow,
2392    status: &PendingSlashCommandStatus,
2393    confirm_command: Arc<dyn Fn(&mut Window, &mut App)>,
2394) -> AnyElement {
2395    let mut icon = IconButton::new(
2396        ("slash-command-gutter-decoration", row.0),
2397        ui::IconName::TriangleRight,
2398    )
2399    .on_click(move |_e, window, cx| confirm_command(window, cx))
2400    .icon_size(ui::IconSize::Small)
2401    .size(ui::ButtonSize::None);
2402
2403    match status {
2404        PendingSlashCommandStatus::Idle => {
2405            icon = icon.icon_color(Color::Muted);
2406        }
2407        PendingSlashCommandStatus::Running { .. } => {
2408            icon = icon.toggle_state(true);
2409        }
2410        PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
2411    }
2412
2413    icon.into_any_element()
2414}
2415
2416#[derive(Debug, Clone, Serialize, Deserialize)]
2417struct CopyMetadata {
2418    creases: Vec<SelectedCreaseMetadata>,
2419}
2420
2421#[derive(Debug, Clone, Serialize, Deserialize)]
2422struct SelectedCreaseMetadata {
2423    range_relative_to_selection: Range<usize>,
2424    crease: CreaseMetadata,
2425}
2426
2427impl EventEmitter<EditorEvent> for TextThreadEditor {}
2428impl EventEmitter<SearchEvent> for TextThreadEditor {}
2429
2430impl Render for TextThreadEditor {
2431    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2432        let language_model_selector = self.language_model_selector_menu_handle.clone();
2433
2434        v_flex()
2435            .key_context("ContextEditor")
2436            .capture_action(cx.listener(TextThreadEditor::cancel))
2437            .capture_action(cx.listener(TextThreadEditor::save))
2438            .capture_action(cx.listener(TextThreadEditor::copy))
2439            .capture_action(cx.listener(TextThreadEditor::cut))
2440            .capture_action(cx.listener(TextThreadEditor::paste))
2441            .capture_action(cx.listener(TextThreadEditor::cycle_message_role))
2442            .capture_action(cx.listener(TextThreadEditor::confirm_command))
2443            .on_action(cx.listener(TextThreadEditor::assist))
2444            .on_action(cx.listener(TextThreadEditor::split))
2445            .on_action(move |_: &ToggleModelSelector, window, cx| {
2446                language_model_selector.toggle(window, cx);
2447            })
2448            .size_full()
2449            .child(
2450                div()
2451                    .flex_grow()
2452                    .bg(cx.theme().colors().editor_background)
2453                    .child(self.editor.clone()),
2454            )
2455            .children(self.render_last_error(cx))
2456            .child(
2457                h_flex()
2458                    .relative()
2459                    .py_2()
2460                    .pl_1p5()
2461                    .pr_2()
2462                    .w_full()
2463                    .justify_between()
2464                    .border_t_1()
2465                    .border_color(cx.theme().colors().border_variant)
2466                    .bg(cx.theme().colors().editor_background)
2467                    .child(
2468                        h_flex()
2469                            .gap_0p5()
2470                            .child(self.render_inject_context_menu(cx))
2471                            .children(self.render_burn_mode_toggle(cx)),
2472                    )
2473                    .child(
2474                        h_flex()
2475                            .gap_2p5()
2476                            .children(self.render_remaining_tokens(cx))
2477                            .child(
2478                                h_flex()
2479                                    .gap_1()
2480                                    .child(self.render_language_model_selector(window, cx))
2481                                    .child(self.render_send_button(window, cx)),
2482                            ),
2483                    ),
2484            )
2485    }
2486}
2487
2488impl Focusable for TextThreadEditor {
2489    fn focus_handle(&self, cx: &App) -> FocusHandle {
2490        self.editor.focus_handle(cx)
2491    }
2492}
2493
2494impl Item for TextThreadEditor {
2495    type Event = editor::EditorEvent;
2496
2497    fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
2498        util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into()
2499    }
2500
2501    fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
2502        match event {
2503            EditorEvent::Edited { .. } => {
2504                f(item::ItemEvent::Edit);
2505            }
2506            EditorEvent::TitleChanged => {
2507                f(item::ItemEvent::UpdateTab);
2508            }
2509            _ => {}
2510        }
2511    }
2512
2513    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
2514        Some(self.title(cx).to_string().into())
2515    }
2516
2517    fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
2518        Some(Box::new(handle.clone()))
2519    }
2520
2521    fn set_nav_history(
2522        &mut self,
2523        nav_history: pane::ItemNavHistory,
2524        window: &mut Window,
2525        cx: &mut Context<Self>,
2526    ) {
2527        self.editor.update(cx, |editor, cx| {
2528            Item::set_nav_history(editor, nav_history, window, cx)
2529        })
2530    }
2531
2532    fn navigate(
2533        &mut self,
2534        data: Box<dyn std::any::Any>,
2535        window: &mut Window,
2536        cx: &mut Context<Self>,
2537    ) -> bool {
2538        self.editor
2539            .update(cx, |editor, cx| Item::navigate(editor, data, window, cx))
2540    }
2541
2542    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2543        self.editor
2544            .update(cx, |editor, cx| Item::deactivated(editor, window, cx))
2545    }
2546
2547    fn act_as_type<'a>(
2548        &'a self,
2549        type_id: TypeId,
2550        self_handle: &'a Entity<Self>,
2551        _: &'a App,
2552    ) -> Option<AnyView> {
2553        if type_id == TypeId::of::<Self>() {
2554            Some(self_handle.to_any())
2555        } else if type_id == TypeId::of::<Editor>() {
2556            Some(self.editor.to_any())
2557        } else {
2558            None
2559        }
2560    }
2561
2562    fn include_in_nav_history() -> bool {
2563        false
2564    }
2565}
2566
2567impl SearchableItem for TextThreadEditor {
2568    type Match = <Editor as SearchableItem>::Match;
2569
2570    fn clear_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2571        self.editor.update(cx, |editor, cx| {
2572            editor.clear_matches(window, cx);
2573        });
2574    }
2575
2576    fn update_matches(
2577        &mut self,
2578        matches: &[Self::Match],
2579        window: &mut Window,
2580        cx: &mut Context<Self>,
2581    ) {
2582        self.editor
2583            .update(cx, |editor, cx| editor.update_matches(matches, window, cx));
2584    }
2585
2586    fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
2587        self.editor
2588            .update(cx, |editor, cx| editor.query_suggestion(window, cx))
2589    }
2590
2591    fn activate_match(
2592        &mut self,
2593        index: usize,
2594        matches: &[Self::Match],
2595        collapse: bool,
2596        window: &mut Window,
2597        cx: &mut Context<Self>,
2598    ) {
2599        self.editor.update(cx, |editor, cx| {
2600            editor.activate_match(index, matches, collapse, window, cx);
2601        });
2602    }
2603
2604    fn select_matches(
2605        &mut self,
2606        matches: &[Self::Match],
2607        window: &mut Window,
2608        cx: &mut Context<Self>,
2609    ) {
2610        self.editor
2611            .update(cx, |editor, cx| editor.select_matches(matches, window, cx));
2612    }
2613
2614    fn replace(
2615        &mut self,
2616        identifier: &Self::Match,
2617        query: &project::search::SearchQuery,
2618        window: &mut Window,
2619        cx: &mut Context<Self>,
2620    ) {
2621        self.editor.update(cx, |editor, cx| {
2622            editor.replace(identifier, query, window, cx)
2623        });
2624    }
2625
2626    fn find_matches(
2627        &mut self,
2628        query: Arc<project::search::SearchQuery>,
2629        window: &mut Window,
2630        cx: &mut Context<Self>,
2631    ) -> Task<Vec<Self::Match>> {
2632        self.editor
2633            .update(cx, |editor, cx| editor.find_matches(query, window, cx))
2634    }
2635
2636    fn active_match_index(
2637        &mut self,
2638        direction: Direction,
2639        matches: &[Self::Match],
2640        window: &mut Window,
2641        cx: &mut Context<Self>,
2642    ) -> Option<usize> {
2643        self.editor.update(cx, |editor, cx| {
2644            editor.active_match_index(direction, matches, window, cx)
2645        })
2646    }
2647}
2648
2649impl FollowableItem for TextThreadEditor {
2650    fn remote_id(&self) -> Option<workspace::ViewId> {
2651        self.remote_id
2652    }
2653
2654    fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant> {
2655        let text_thread = self.text_thread.read(cx);
2656        Some(proto::view::Variant::ContextEditor(
2657            proto::view::ContextEditor {
2658                context_id: text_thread.id().to_proto(),
2659                editor: if let Some(proto::view::Variant::Editor(proto)) =
2660                    self.editor.read(cx).to_state_proto(window, cx)
2661                {
2662                    Some(proto)
2663                } else {
2664                    None
2665                },
2666            },
2667        ))
2668    }
2669
2670    fn from_state_proto(
2671        workspace: Entity<Workspace>,
2672        id: workspace::ViewId,
2673        state: &mut Option<proto::view::Variant>,
2674        window: &mut Window,
2675        cx: &mut App,
2676    ) -> Option<Task<Result<Entity<Self>>>> {
2677        let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
2678            return None;
2679        };
2680        let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
2681            unreachable!()
2682        };
2683
2684        let text_thread_id = TextThreadId::from_proto(state.context_id);
2685        let editor_state = state.editor?;
2686
2687        let project = workspace.read(cx).project().clone();
2688        let agent_panel_delegate = <dyn AgentPanelDelegate>::try_global(cx)?;
2689
2690        let text_thread_editor_task = workspace.update(cx, |workspace, cx| {
2691            agent_panel_delegate.open_remote_text_thread(workspace, text_thread_id, window, cx)
2692        });
2693
2694        Some(window.spawn(cx, async move |cx| {
2695            let text_thread_editor = text_thread_editor_task.await?;
2696            text_thread_editor
2697                .update_in(cx, |text_thread_editor, window, cx| {
2698                    text_thread_editor.remote_id = Some(id);
2699                    text_thread_editor.editor.update(cx, |editor, cx| {
2700                        editor.apply_update_proto(
2701                            &project,
2702                            proto::update_view::Variant::Editor(proto::update_view::Editor {
2703                                selections: editor_state.selections,
2704                                pending_selection: editor_state.pending_selection,
2705                                scroll_top_anchor: editor_state.scroll_top_anchor,
2706                                scroll_x: editor_state.scroll_y,
2707                                scroll_y: editor_state.scroll_y,
2708                                ..Default::default()
2709                            }),
2710                            window,
2711                            cx,
2712                        )
2713                    })
2714                })?
2715                .await?;
2716            Ok(text_thread_editor)
2717        }))
2718    }
2719
2720    fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
2721        Editor::to_follow_event(event)
2722    }
2723
2724    fn add_event_to_update_proto(
2725        &self,
2726        event: &Self::Event,
2727        update: &mut Option<proto::update_view::Variant>,
2728        window: &Window,
2729        cx: &App,
2730    ) -> bool {
2731        self.editor
2732            .read(cx)
2733            .add_event_to_update_proto(event, update, window, cx)
2734    }
2735
2736    fn apply_update_proto(
2737        &mut self,
2738        project: &Entity<Project>,
2739        message: proto::update_view::Variant,
2740        window: &mut Window,
2741        cx: &mut Context<Self>,
2742    ) -> Task<Result<()>> {
2743        self.editor.update(cx, |editor, cx| {
2744            editor.apply_update_proto(project, message, window, cx)
2745        })
2746    }
2747
2748    fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
2749        true
2750    }
2751
2752    fn set_leader_id(
2753        &mut self,
2754        leader_id: Option<CollaboratorId>,
2755        window: &mut Window,
2756        cx: &mut Context<Self>,
2757    ) {
2758        self.editor
2759            .update(cx, |editor, cx| editor.set_leader_id(leader_id, window, cx))
2760    }
2761
2762    fn dedup(&self, existing: &Self, _window: &Window, cx: &App) -> Option<item::Dedup> {
2763        if existing.text_thread.read(cx).id() == self.text_thread.read(cx).id() {
2764            Some(item::Dedup::KeepExisting)
2765        } else {
2766            None
2767        }
2768    }
2769}
2770
2771enum PendingSlashCommand {}
2772
2773fn invoked_slash_command_fold_placeholder(
2774    command_id: InvokedSlashCommandId,
2775    text_thread: WeakEntity<TextThread>,
2776) -> FoldPlaceholder {
2777    FoldPlaceholder {
2778        constrain_width: false,
2779        merge_adjacent: false,
2780        render: Arc::new(move |fold_id, _, cx| {
2781            let Some(text_thread) = text_thread.upgrade() else {
2782                return Empty.into_any();
2783            };
2784
2785            let Some(command) = text_thread.read(cx).invoked_slash_command(&command_id) else {
2786                return Empty.into_any();
2787            };
2788
2789            h_flex()
2790                .id(fold_id)
2791                .px_1()
2792                .ml_6()
2793                .gap_2()
2794                .bg(cx.theme().colors().surface_background)
2795                .rounded_sm()
2796                .child(Label::new(format!("/{}", command.name)))
2797                .map(|parent| match &command.status {
2798                    InvokedSlashCommandStatus::Running(_) => {
2799                        parent.child(Icon::new(IconName::ArrowCircle).with_rotate_animation(4))
2800                    }
2801                    InvokedSlashCommandStatus::Error(message) => parent.child(
2802                        Label::new(format!("error: {message}"))
2803                            .single_line()
2804                            .color(Color::Error),
2805                    ),
2806                    InvokedSlashCommandStatus::Finished => parent,
2807                })
2808                .into_any_element()
2809        }),
2810        type_tag: Some(TypeId::of::<PendingSlashCommand>()),
2811    }
2812}
2813
2814enum TokenState {
2815    NoTokensLeft {
2816        max_token_count: u64,
2817        token_count: u64,
2818    },
2819    HasMoreTokens {
2820        max_token_count: u64,
2821        token_count: u64,
2822        over_warn_threshold: bool,
2823    },
2824}
2825
2826fn token_state(text_thread: &Entity<TextThread>, cx: &App) -> Option<TokenState> {
2827    const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
2828
2829    let model = LanguageModelRegistry::read_global(cx)
2830        .default_model()?
2831        .model;
2832    let token_count = text_thread.read(cx).token_count()?;
2833    let max_token_count =
2834        model.max_token_count_for_mode(text_thread.read(cx).completion_mode().into());
2835    let token_state = if max_token_count.saturating_sub(token_count) == 0 {
2836        TokenState::NoTokensLeft {
2837            max_token_count,
2838            token_count,
2839        }
2840    } else {
2841        let over_warn_threshold =
2842            token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
2843        TokenState::HasMoreTokens {
2844            max_token_count,
2845            token_count,
2846            over_warn_threshold,
2847        }
2848    };
2849    Some(token_state)
2850}
2851
2852fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
2853    let image_size = data
2854        .size(0)
2855        .map(|dimension| Pixels::from(u32::from(dimension)));
2856    let image_ratio = image_size.width / image_size.height;
2857    let bounds_ratio = max_size.width / max_size.height;
2858
2859    if image_size.width > max_size.width || image_size.height > max_size.height {
2860        if bounds_ratio > image_ratio {
2861            size(
2862                image_size.width * (max_size.height / image_size.height),
2863                max_size.height,
2864            )
2865        } else {
2866            size(
2867                max_size.width,
2868                image_size.height * (max_size.width / image_size.width),
2869            )
2870        }
2871    } else {
2872        size(image_size.width, image_size.height)
2873    }
2874}
2875
2876pub fn humanize_token_count(count: u64) -> String {
2877    match count {
2878        0..=999 => count.to_string(),
2879        1000..=9999 => {
2880            let thousands = count / 1000;
2881            let hundreds = (count % 1000 + 50) / 100;
2882            if hundreds == 0 {
2883                format!("{}k", thousands)
2884            } else if hundreds == 10 {
2885                format!("{}k", thousands + 1)
2886            } else {
2887                format!("{}.{}k", thousands, hundreds)
2888            }
2889        }
2890        1_000_000..=9_999_999 => {
2891            let millions = count / 1_000_000;
2892            let hundred_thousands = (count % 1_000_000 + 50_000) / 100_000;
2893            if hundred_thousands == 0 {
2894                format!("{}M", millions)
2895            } else if hundred_thousands == 10 {
2896                format!("{}M", millions + 1)
2897            } else {
2898                format!("{}.{}M", millions, hundred_thousands)
2899            }
2900        }
2901        10_000_000.. => format!("{}M", (count + 500_000) / 1_000_000),
2902        _ => format!("{}k", (count + 500) / 1000),
2903    }
2904}
2905
2906pub fn make_lsp_adapter_delegate(
2907    project: &Entity<Project>,
2908    cx: &mut App,
2909) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
2910    project.update(cx, |project, cx| {
2911        // TODO: Find the right worktree.
2912        let Some(worktree) = project.worktrees(cx).next() else {
2913            return Ok(None::<Arc<dyn LspAdapterDelegate>>);
2914        };
2915        let http_client = project.client().http_client();
2916        project.lsp_store().update(cx, |_, cx| {
2917            Ok(Some(LocalLspAdapterDelegate::new(
2918                project.languages().clone(),
2919                project.environment(),
2920                cx.weak_entity(),
2921                &worktree,
2922                http_client,
2923                project.fs().clone(),
2924                cx,
2925            ) as Arc<dyn LspAdapterDelegate>))
2926        })
2927    })
2928}
2929
2930#[cfg(test)]
2931mod tests {
2932    use super::*;
2933    use editor::SelectionEffects;
2934    use fs::FakeFs;
2935    use gpui::{App, TestAppContext, VisualTestContext};
2936    use indoc::indoc;
2937    use language::{Buffer, LanguageRegistry};
2938    use pretty_assertions::assert_eq;
2939    use prompt_store::PromptBuilder;
2940    use text::OffsetRangeExt;
2941    use unindent::Unindent;
2942    use util::path;
2943
2944    #[gpui::test]
2945    async fn test_copy_paste_whole_message(cx: &mut TestAppContext) {
2946        let (context, text_thread_editor, mut cx) = setup_text_thread_editor_text(vec![
2947            (Role::User, "What is the Zed editor?"),
2948            (
2949                Role::Assistant,
2950                "Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.",
2951            ),
2952            (Role::User, ""),
2953        ],cx).await;
2954
2955        // Select & Copy whole user message
2956        assert_copy_paste_text_thread_editor(
2957            &text_thread_editor,
2958            message_range(&context, 0, &mut cx),
2959            indoc! {"
2960                What is the Zed editor?
2961                Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
2962                What is the Zed editor?
2963            "},
2964            &mut cx,
2965        );
2966
2967        // Select & Copy whole assistant message
2968        assert_copy_paste_text_thread_editor(
2969            &text_thread_editor,
2970            message_range(&context, 1, &mut cx),
2971            indoc! {"
2972                What is the Zed editor?
2973                Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
2974                What is the Zed editor?
2975                Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
2976            "},
2977            &mut cx,
2978        );
2979    }
2980
2981    #[gpui::test]
2982    async fn test_copy_paste_no_selection(cx: &mut TestAppContext) {
2983        let (context, text_thread_editor, mut cx) = setup_text_thread_editor_text(
2984            vec![
2985                (Role::User, "user1"),
2986                (Role::Assistant, "assistant1"),
2987                (Role::Assistant, "assistant2"),
2988                (Role::User, ""),
2989            ],
2990            cx,
2991        )
2992        .await;
2993
2994        // Copy and paste first assistant message
2995        let message_2_range = message_range(&context, 1, &mut cx);
2996        assert_copy_paste_text_thread_editor(
2997            &text_thread_editor,
2998            message_2_range.start..message_2_range.start,
2999            indoc! {"
3000                user1
3001                assistant1
3002                assistant2
3003                assistant1
3004            "},
3005            &mut cx,
3006        );
3007
3008        // Copy and cut second assistant message
3009        let message_3_range = message_range(&context, 2, &mut cx);
3010        assert_copy_paste_text_thread_editor(
3011            &text_thread_editor,
3012            message_3_range.start..message_3_range.start,
3013            indoc! {"
3014                user1
3015                assistant1
3016                assistant2
3017                assistant1
3018                assistant2
3019            "},
3020            &mut cx,
3021        );
3022    }
3023
3024    #[gpui::test]
3025    fn test_find_code_blocks(cx: &mut App) {
3026        let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
3027
3028        let buffer = cx.new(|cx| {
3029            let text = r#"
3030                line 0
3031                line 1
3032                ```rust
3033                fn main() {}
3034                ```
3035                line 5
3036                line 6
3037                line 7
3038                ```go
3039                func main() {}
3040                ```
3041                line 11
3042                ```
3043                this is plain text code block
3044                ```
3045
3046                ```go
3047                func another() {}
3048                ```
3049                line 19
3050            "#
3051            .unindent();
3052            let mut buffer = Buffer::local(text, cx);
3053            buffer.set_language(Some(markdown.clone()), cx);
3054            buffer
3055        });
3056        let snapshot = buffer.read(cx).snapshot();
3057
3058        let code_blocks = vec![
3059            Point::new(3, 0)..Point::new(4, 0),
3060            Point::new(9, 0)..Point::new(10, 0),
3061            Point::new(13, 0)..Point::new(14, 0),
3062            Point::new(17, 0)..Point::new(18, 0),
3063        ]
3064        .into_iter()
3065        .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
3066        .collect::<Vec<_>>();
3067
3068        let expected_results = vec![
3069            (0, None),
3070            (1, None),
3071            (2, Some(code_blocks[0].clone())),
3072            (3, Some(code_blocks[0].clone())),
3073            (4, Some(code_blocks[0].clone())),
3074            (5, None),
3075            (6, None),
3076            (7, None),
3077            (8, Some(code_blocks[1].clone())),
3078            (9, Some(code_blocks[1].clone())),
3079            (10, Some(code_blocks[1].clone())),
3080            (11, None),
3081            (12, Some(code_blocks[2].clone())),
3082            (13, Some(code_blocks[2].clone())),
3083            (14, Some(code_blocks[2].clone())),
3084            (15, None),
3085            (16, Some(code_blocks[3].clone())),
3086            (17, Some(code_blocks[3].clone())),
3087            (18, Some(code_blocks[3].clone())),
3088            (19, None),
3089        ];
3090
3091        for (row, expected) in expected_results {
3092            let offset = snapshot.point_to_offset(Point::new(row, 0));
3093            let range = find_surrounding_code_block(&snapshot, offset);
3094            assert_eq!(range, expected, "unexpected result on row {:?}", row);
3095        }
3096    }
3097
3098    async fn setup_text_thread_editor_text(
3099        messages: Vec<(Role, &str)>,
3100        cx: &mut TestAppContext,
3101    ) -> (
3102        Entity<TextThread>,
3103        Entity<TextThreadEditor>,
3104        VisualTestContext,
3105    ) {
3106        cx.update(init_test);
3107
3108        let fs = FakeFs::new(cx.executor());
3109        let text_thread = create_text_thread_with_messages(messages, cx);
3110
3111        let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
3112        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
3113        let workspace = window.root(cx).unwrap();
3114        let mut cx = VisualTestContext::from_window(*window, cx);
3115
3116        let text_thread_editor = window
3117            .update(&mut cx, |_, window, cx| {
3118                cx.new(|cx| {
3119                    TextThreadEditor::for_text_thread(
3120                        text_thread.clone(),
3121                        fs,
3122                        workspace.downgrade(),
3123                        project,
3124                        None,
3125                        window,
3126                        cx,
3127                    )
3128                })
3129            })
3130            .unwrap();
3131
3132        (text_thread, text_thread_editor, cx)
3133    }
3134
3135    fn message_range(
3136        text_thread: &Entity<TextThread>,
3137        message_ix: usize,
3138        cx: &mut TestAppContext,
3139    ) -> Range<usize> {
3140        text_thread.update(cx, |text_thread, cx| {
3141            text_thread
3142                .messages(cx)
3143                .nth(message_ix)
3144                .unwrap()
3145                .anchor_range
3146                .to_offset(&text_thread.buffer().read(cx).snapshot())
3147        })
3148    }
3149
3150    fn assert_copy_paste_text_thread_editor<T: editor::ToOffset>(
3151        text_thread_editor: &Entity<TextThreadEditor>,
3152        range: Range<T>,
3153        expected_text: &str,
3154        cx: &mut VisualTestContext,
3155    ) {
3156        text_thread_editor.update_in(cx, |text_thread_editor, window, cx| {
3157            text_thread_editor.editor.update(cx, |editor, cx| {
3158                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
3159                    s.select_ranges([range])
3160                });
3161            });
3162
3163            text_thread_editor.copy(&Default::default(), window, cx);
3164
3165            text_thread_editor.editor.update(cx, |editor, cx| {
3166                editor.move_to_end(&Default::default(), window, cx);
3167            });
3168
3169            text_thread_editor.paste(&Default::default(), window, cx);
3170
3171            text_thread_editor.editor.update(cx, |editor, cx| {
3172                assert_eq!(editor.text(cx), expected_text);
3173            });
3174        });
3175    }
3176
3177    fn create_text_thread_with_messages(
3178        mut messages: Vec<(Role, &str)>,
3179        cx: &mut TestAppContext,
3180    ) -> Entity<TextThread> {
3181        let registry = Arc::new(LanguageRegistry::test(cx.executor()));
3182        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3183        cx.new(|cx| {
3184            let mut text_thread = TextThread::local(
3185                registry,
3186                None,
3187                None,
3188                prompt_builder.clone(),
3189                Arc::new(SlashCommandWorkingSet::default()),
3190                cx,
3191            );
3192            let mut message_1 = text_thread.messages(cx).next().unwrap();
3193            let (role, text) = messages.remove(0);
3194
3195            loop {
3196                if role == message_1.role {
3197                    text_thread.buffer().update(cx, |buffer, cx| {
3198                        buffer.edit([(message_1.offset_range, text)], None, cx);
3199                    });
3200                    break;
3201                }
3202                let mut ids = HashSet::default();
3203                ids.insert(message_1.id);
3204                text_thread.cycle_message_roles(ids, cx);
3205                message_1 = text_thread.messages(cx).next().unwrap();
3206            }
3207
3208            let mut last_message_id = message_1.id;
3209            for (role, text) in messages {
3210                text_thread.insert_message_after(last_message_id, role, MessageStatus::Done, cx);
3211                let message = text_thread.messages(cx).last().unwrap();
3212                last_message_id = message.id;
3213                text_thread.buffer().update(cx, |buffer, cx| {
3214                    buffer.edit([(message.offset_range, text)], None, cx);
3215                })
3216            }
3217
3218            text_thread
3219        })
3220    }
3221
3222    fn init_test(cx: &mut App) {
3223        let settings_store = SettingsStore::test(cx);
3224        prompt_store::init(cx);
3225        LanguageModelRegistry::test(cx);
3226        cx.set_global(settings_store);
3227
3228        theme::init(theme::LoadThemes::JustBase, cx);
3229    }
3230}