text_thread_editor.rs

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