text_thread_editor.rs

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