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