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, Transformation, WeakEntity, actions,
  29    div, img, percentage, point, 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, Disclosure, ElevationIndex, KeyBinding, PopoverMenuHandle, TintColor, Tooltip,
  57    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_animation(
1065                                                "arrow-circle",
1066                                                Animation::new(Duration::from_secs(2)).repeat(),
1067                                                |icon, delta| {
1068                                                    icon.transform(Transformation::rotate(
1069                                                        percentage(delta),
1070                                                    ))
1071                                                },
1072                                            )
1073                                            .into_any_element(),
1074                                    );
1075                                    note = Some(Self::esc_kbd(cx).into_any_element());
1076                                }
1077                                (animated_label, spinner, note)
1078                            }
1079                            Role::System => (
1080                                Label::new("System")
1081                                    .color(Color::Warning)
1082                                    .into_any_element(),
1083                                None,
1084                                None,
1085                            ),
1086                        };
1087
1088                        let sender = h_flex()
1089                            .items_center()
1090                            .gap_2p5()
1091                            .child(
1092                                ButtonLike::new("role")
1093                                    .style(ButtonStyle::Filled)
1094                                    .child(
1095                                        h_flex()
1096                                            .items_center()
1097                                            .gap_1p5()
1098                                            .child(label)
1099                                            .children(spinner),
1100                                    )
1101                                    .tooltip(|window, cx| {
1102                                        Tooltip::with_meta(
1103                                            "Toggle message role",
1104                                            None,
1105                                            "Available roles: You (User), Agent, System",
1106                                            window,
1107                                            cx,
1108                                        )
1109                                    })
1110                                    .on_click({
1111                                        let context = context.clone();
1112                                        move |_, _window, cx| {
1113                                            context.update(cx, |context, cx| {
1114                                                context.cycle_message_roles(
1115                                                    HashSet::from_iter(Some(message_id)),
1116                                                    cx,
1117                                                )
1118                                            })
1119                                        }
1120                                    }),
1121                            )
1122                            .children(note);
1123
1124                        h_flex()
1125                            .id(("message_header", message_id.as_u64()))
1126                            .pl(cx.margins.gutter.full_width())
1127                            .h_11()
1128                            .w_full()
1129                            .relative()
1130                            .gap_1p5()
1131                            .child(sender)
1132                            .children(match &message.cache {
1133                                Some(cache) if cache.is_final_anchor => match cache.status {
1134                                    CacheStatus::Cached => Some(
1135                                        div()
1136                                            .id("cached")
1137                                            .child(
1138                                                Icon::new(IconName::DatabaseZap)
1139                                                    .size(IconSize::XSmall)
1140                                                    .color(Color::Hint),
1141                                            )
1142                                            .tooltip(|window, cx| {
1143                                                Tooltip::with_meta(
1144                                                    "Context Cached",
1145                                                    None,
1146                                                    "Large messages cached to optimize performance",
1147                                                    window,
1148                                                    cx,
1149                                                )
1150                                            })
1151                                            .into_any_element(),
1152                                    ),
1153                                    CacheStatus::Pending => Some(
1154                                        div()
1155                                            .child(
1156                                                Icon::new(IconName::Ellipsis)
1157                                                    .size(IconSize::XSmall)
1158                                                    .color(Color::Hint),
1159                                            )
1160                                            .into_any_element(),
1161                                    ),
1162                                },
1163                                _ => None,
1164                            })
1165                            .children(match &message.status {
1166                                MessageStatus::Error(error) => Some(
1167                                    Button::new("show-error", "Error")
1168                                        .color(Color::Error)
1169                                        .selected_label_color(Color::Error)
1170                                        .selected_icon_color(Color::Error)
1171                                        .icon(IconName::XCircle)
1172                                        .icon_color(Color::Error)
1173                                        .icon_size(IconSize::XSmall)
1174                                        .icon_position(IconPosition::Start)
1175                                        .tooltip(Tooltip::text("View Details"))
1176                                        .on_click({
1177                                            let context = context.clone();
1178                                            let error = error.clone();
1179                                            move |_, _window, cx| {
1180                                                context.update(cx, |_, cx| {
1181                                                    cx.emit(ContextEvent::ShowAssistError(
1182                                                        error.clone(),
1183                                                    ));
1184                                                });
1185                                            }
1186                                        })
1187                                        .into_any_element(),
1188                                ),
1189                                MessageStatus::Canceled => Some(
1190                                    h_flex()
1191                                        .gap_1()
1192                                        .items_center()
1193                                        .child(
1194                                            Icon::new(IconName::XCircle)
1195                                                .color(Color::Disabled)
1196                                                .size(IconSize::XSmall),
1197                                        )
1198                                        .child(
1199                                            Label::new("Canceled")
1200                                                .size(LabelSize::Small)
1201                                                .color(Color::Disabled),
1202                                        )
1203                                        .into_any_element(),
1204                                ),
1205                                _ => None,
1206                            })
1207                            .into_any_element()
1208                    }
1209                })
1210            };
1211            let create_block_properties = |message: &Message| BlockProperties {
1212                height: Some(2),
1213                style: BlockStyle::Sticky,
1214                placement: BlockPlacement::Above(
1215                    buffer
1216                        .anchor_in_excerpt(excerpt_id, message.anchor_range.start)
1217                        .unwrap(),
1218                ),
1219                priority: usize::MAX,
1220                render: render_block(MessageMetadata::from(message)),
1221            };
1222            let mut new_blocks = vec![];
1223            let mut block_index_to_message = vec![];
1224            for message in self.context.read(cx).messages(cx) {
1225                if blocks_to_remove.remove(&message.id).is_some() {
1226                    // This is an old message that we might modify.
1227                    let Some((meta, block_id)) = old_blocks.get_mut(&message.id) else {
1228                        debug_assert!(
1229                            false,
1230                            "old_blocks should contain a message_id we've just removed."
1231                        );
1232                        continue;
1233                    };
1234                    // Should we modify it?
1235                    let message_meta = MessageMetadata::from(&message);
1236                    if meta != &message_meta {
1237                        blocks_to_replace.insert(*block_id, render_block(message_meta.clone()));
1238                        *meta = message_meta;
1239                    }
1240                } else {
1241                    // This is a new message.
1242                    new_blocks.push(create_block_properties(&message));
1243                    block_index_to_message.push((message.id, MessageMetadata::from(&message)));
1244                }
1245            }
1246            editor.replace_blocks(blocks_to_replace, None, cx);
1247            editor.remove_blocks(blocks_to_remove.into_values().collect(), None, cx);
1248
1249            let ids = editor.insert_blocks(new_blocks, None, cx);
1250            old_blocks.extend(ids.into_iter().zip(block_index_to_message).map(
1251                |(block_id, (message_id, message_meta))| (message_id, (message_meta, block_id)),
1252            ));
1253            self.blocks = old_blocks;
1254        });
1255    }
1256
1257    /// Returns either the selected text, or the content of the Markdown code
1258    /// block surrounding the cursor.
1259    fn get_selection_or_code_block(
1260        context_editor_view: &Entity<TextThreadEditor>,
1261        cx: &mut Context<Workspace>,
1262    ) -> Option<(String, bool)> {
1263        const CODE_FENCE_DELIMITER: &str = "```";
1264
1265        let context_editor = context_editor_view.read(cx).editor.clone();
1266        context_editor.update(cx, |context_editor, cx| {
1267            if context_editor.selections.newest::<Point>(cx).is_empty() {
1268                let snapshot = context_editor.buffer().read(cx).snapshot(cx);
1269                let (_, _, snapshot) = snapshot.as_singleton()?;
1270
1271                let head = context_editor.selections.newest::<Point>(cx).head();
1272                let offset = snapshot.point_to_offset(head);
1273
1274                let surrounding_code_block_range = find_surrounding_code_block(snapshot, offset)?;
1275                let mut text = snapshot
1276                    .text_for_range(surrounding_code_block_range)
1277                    .collect::<String>();
1278
1279                // If there is no newline trailing the closing three-backticks, then
1280                // tree-sitter-md extends the range of the content node to include
1281                // the backticks.
1282                if text.ends_with(CODE_FENCE_DELIMITER) {
1283                    text.drain((text.len() - CODE_FENCE_DELIMITER.len())..);
1284                }
1285
1286                (!text.is_empty()).then_some((text, true))
1287            } else {
1288                let selection = context_editor.selections.newest_adjusted(cx);
1289                let buffer = context_editor.buffer().read(cx).snapshot(cx);
1290                let selected_text = buffer.text_for_range(selection.range()).collect::<String>();
1291
1292                (!selected_text.is_empty()).then_some((selected_text, false))
1293            }
1294        })
1295    }
1296
1297    pub fn insert_selection(
1298        workspace: &mut Workspace,
1299        _: &InsertIntoEditor,
1300        window: &mut Window,
1301        cx: &mut Context<Workspace>,
1302    ) {
1303        let Some(agent_panel_delegate) = <dyn AgentPanelDelegate>::try_global(cx) else {
1304            return;
1305        };
1306        let Some(context_editor_view) =
1307            agent_panel_delegate.active_context_editor(workspace, window, cx)
1308        else {
1309            return;
1310        };
1311        let Some(active_editor_view) = workspace
1312            .active_item(cx)
1313            .and_then(|item| item.act_as::<Editor>(cx))
1314        else {
1315            return;
1316        };
1317
1318        if let Some((text, _)) = Self::get_selection_or_code_block(&context_editor_view, cx) {
1319            active_editor_view.update(cx, |editor, cx| {
1320                editor.insert(&text, window, cx);
1321                editor.focus_handle(cx).focus(window);
1322            })
1323        }
1324    }
1325
1326    pub fn copy_code(
1327        workspace: &mut Workspace,
1328        _: &CopyCode,
1329        window: &mut Window,
1330        cx: &mut Context<Workspace>,
1331    ) {
1332        let result = maybe!({
1333            let agent_panel_delegate = <dyn AgentPanelDelegate>::try_global(cx)?;
1334            let context_editor_view =
1335                agent_panel_delegate.active_context_editor(workspace, window, cx)?;
1336            Self::get_selection_or_code_block(&context_editor_view, cx)
1337        });
1338        let Some((text, is_code_block)) = result else {
1339            return;
1340        };
1341
1342        cx.write_to_clipboard(ClipboardItem::new_string(text));
1343
1344        struct CopyToClipboardToast;
1345        workspace.show_toast(
1346            Toast::new(
1347                NotificationId::unique::<CopyToClipboardToast>(),
1348                format!(
1349                    "{} copied to clipboard.",
1350                    if is_code_block {
1351                        "Code block"
1352                    } else {
1353                        "Selection"
1354                    }
1355                ),
1356            )
1357            .autohide(),
1358            cx,
1359        );
1360    }
1361
1362    pub fn handle_insert_dragged_files(
1363        workspace: &mut Workspace,
1364        action: &InsertDraggedFiles,
1365        window: &mut Window,
1366        cx: &mut Context<Workspace>,
1367    ) {
1368        let Some(agent_panel_delegate) = <dyn AgentPanelDelegate>::try_global(cx) else {
1369            return;
1370        };
1371        let Some(context_editor_view) =
1372            agent_panel_delegate.active_context_editor(workspace, window, cx)
1373        else {
1374            return;
1375        };
1376
1377        let project = context_editor_view.read(cx).project.clone();
1378
1379        let paths = match action {
1380            InsertDraggedFiles::ProjectPaths(paths) => Task::ready((paths.clone(), vec![])),
1381            InsertDraggedFiles::ExternalFiles(paths) => {
1382                let tasks = paths
1383                    .clone()
1384                    .into_iter()
1385                    .map(|path| Workspace::project_path_for_path(project.clone(), &path, false, cx))
1386                    .collect::<Vec<_>>();
1387
1388                cx.background_spawn(async move {
1389                    let mut paths = vec![];
1390                    let mut worktrees = vec![];
1391
1392                    let opened_paths = futures::future::join_all(tasks).await;
1393
1394                    for entry in opened_paths {
1395                        if let Some((worktree, project_path)) = entry.log_err() {
1396                            worktrees.push(worktree);
1397                            paths.push(project_path);
1398                        }
1399                    }
1400
1401                    (paths, worktrees)
1402                })
1403            }
1404        };
1405
1406        context_editor_view.update(cx, |_, cx| {
1407            cx.spawn_in(window, async move |this, cx| {
1408                let (paths, dragged_file_worktrees) = paths.await;
1409                this.update_in(cx, |this, window, cx| {
1410                    this.insert_dragged_files(paths, dragged_file_worktrees, window, cx);
1411                })
1412                .ok();
1413            })
1414            .detach();
1415        })
1416    }
1417
1418    pub fn insert_dragged_files(
1419        &mut self,
1420        opened_paths: Vec<ProjectPath>,
1421        added_worktrees: Vec<Entity<Worktree>>,
1422        window: &mut Window,
1423        cx: &mut Context<Self>,
1424    ) {
1425        let mut file_slash_command_args = vec![];
1426        for project_path in opened_paths.into_iter() {
1427            let Some(worktree) = self
1428                .project
1429                .read(cx)
1430                .worktree_for_id(project_path.worktree_id, cx)
1431            else {
1432                continue;
1433            };
1434            let worktree_root_name = worktree.read(cx).root_name().to_string();
1435            let mut full_path = PathBuf::from(worktree_root_name.clone());
1436            full_path.push(&project_path.path);
1437            file_slash_command_args.push(full_path.to_string_lossy().to_string());
1438        }
1439
1440        let cmd_name = FileSlashCommand.name();
1441
1442        let file_argument = file_slash_command_args.join(" ");
1443
1444        self.editor.update(cx, |editor, cx| {
1445            editor.insert("\n", window, cx);
1446            editor.insert(&format!("/{} {}", cmd_name, file_argument), window, cx);
1447        });
1448        self.confirm_command(&ConfirmCommand, window, cx);
1449        self.dragged_file_worktrees.extend(added_worktrees);
1450    }
1451
1452    pub fn quote_selection(
1453        workspace: &mut Workspace,
1454        _: &QuoteSelection,
1455        window: &mut Window,
1456        cx: &mut Context<Workspace>,
1457    ) {
1458        let Some(agent_panel_delegate) = <dyn AgentPanelDelegate>::try_global(cx) else {
1459            return;
1460        };
1461
1462        let Some((selections, buffer)) = maybe!({
1463            let editor = workspace
1464                .active_item(cx)
1465                .and_then(|item| item.act_as::<Editor>(cx))?;
1466
1467            let buffer = editor.read(cx).buffer().clone();
1468            let snapshot = buffer.read(cx).snapshot(cx);
1469            let selections = editor.update(cx, |editor, cx| {
1470                editor
1471                    .selections
1472                    .all_adjusted(cx)
1473                    .into_iter()
1474                    .filter_map(|s| {
1475                        (!s.is_empty())
1476                            .then(|| snapshot.anchor_after(s.start)..snapshot.anchor_before(s.end))
1477                    })
1478                    .collect::<Vec<_>>()
1479            });
1480            Some((selections, buffer))
1481        }) else {
1482            return;
1483        };
1484
1485        if selections.is_empty() {
1486            return;
1487        }
1488
1489        agent_panel_delegate.quote_selection(workspace, selections, buffer, window, cx);
1490    }
1491
1492    pub fn quote_ranges(
1493        &mut self,
1494        ranges: Vec<Range<Point>>,
1495        snapshot: MultiBufferSnapshot,
1496        window: &mut Window,
1497        cx: &mut Context<Self>,
1498    ) {
1499        let creases = selections_creases(ranges, snapshot, cx);
1500
1501        self.editor.update(cx, |editor, cx| {
1502            editor.insert("\n", window, cx);
1503            for (text, crease_title) in creases {
1504                let point = editor.selections.newest::<Point>(cx).head();
1505                let start_row = MultiBufferRow(point.row);
1506
1507                editor.insert(&text, window, cx);
1508
1509                let snapshot = editor.buffer().read(cx).snapshot(cx);
1510                let anchor_before = snapshot.anchor_after(point);
1511                let anchor_after = editor
1512                    .selections
1513                    .newest_anchor()
1514                    .head()
1515                    .bias_left(&snapshot);
1516
1517                editor.insert("\n", window, cx);
1518
1519                let fold_placeholder =
1520                    quote_selection_fold_placeholder(crease_title, cx.entity().downgrade());
1521                let crease = Crease::inline(
1522                    anchor_before..anchor_after,
1523                    fold_placeholder,
1524                    render_quote_selection_output_toggle,
1525                    |_, _, _, _| Empty.into_any(),
1526                );
1527                editor.insert_creases(vec![crease], cx);
1528                editor.fold_at(start_row, window, cx);
1529            }
1530        })
1531    }
1532
1533    fn copy(&mut self, _: &editor::actions::Copy, _window: &mut Window, cx: &mut Context<Self>) {
1534        if self.editor.read(cx).selections.count() == 1 {
1535            let (copied_text, metadata, _) = self.get_clipboard_contents(cx);
1536            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1537                copied_text,
1538                metadata,
1539            ));
1540            cx.stop_propagation();
1541            return;
1542        }
1543
1544        cx.propagate();
1545    }
1546
1547    fn cut(&mut self, _: &editor::actions::Cut, window: &mut Window, cx: &mut Context<Self>) {
1548        if self.editor.read(cx).selections.count() == 1 {
1549            let (copied_text, metadata, selections) = self.get_clipboard_contents(cx);
1550
1551            self.editor.update(cx, |editor, cx| {
1552                editor.transact(window, cx, |this, window, cx| {
1553                    this.change_selections(Default::default(), window, cx, |s| {
1554                        s.select(selections);
1555                    });
1556                    this.insert("", window, cx);
1557                    cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1558                        copied_text,
1559                        metadata,
1560                    ));
1561                });
1562            });
1563
1564            cx.stop_propagation();
1565            return;
1566        }
1567
1568        cx.propagate();
1569    }
1570
1571    fn get_clipboard_contents(
1572        &mut self,
1573        cx: &mut Context<Self>,
1574    ) -> (String, CopyMetadata, Vec<text::Selection<usize>>) {
1575        let (mut selection, creases) = self.editor.update(cx, |editor, cx| {
1576            let mut selection = editor.selections.newest_adjusted(cx);
1577            let snapshot = editor.buffer().read(cx).snapshot(cx);
1578
1579            selection.goal = SelectionGoal::None;
1580
1581            let selection_start = snapshot.point_to_offset(selection.start);
1582
1583            (
1584                selection.map(|point| snapshot.point_to_offset(point)),
1585                editor.display_map.update(cx, |display_map, cx| {
1586                    display_map
1587                        .snapshot(cx)
1588                        .crease_snapshot
1589                        .creases_in_range(
1590                            MultiBufferRow(selection.start.row)
1591                                ..MultiBufferRow(selection.end.row + 1),
1592                            &snapshot,
1593                        )
1594                        .filter_map(|crease| {
1595                            if let Crease::Inline {
1596                                range, metadata, ..
1597                            } = &crease
1598                            {
1599                                let metadata = metadata.as_ref()?;
1600                                let start = range
1601                                    .start
1602                                    .to_offset(&snapshot)
1603                                    .saturating_sub(selection_start);
1604                                let end = range
1605                                    .end
1606                                    .to_offset(&snapshot)
1607                                    .saturating_sub(selection_start);
1608
1609                                let range_relative_to_selection = start..end;
1610                                if !range_relative_to_selection.is_empty() {
1611                                    return Some(SelectedCreaseMetadata {
1612                                        range_relative_to_selection,
1613                                        crease: metadata.clone(),
1614                                    });
1615                                }
1616                            }
1617                            None
1618                        })
1619                        .collect::<Vec<_>>()
1620                }),
1621            )
1622        });
1623
1624        let context = self.context.read(cx);
1625
1626        let mut text = String::new();
1627
1628        // If selection is empty, we want to copy the entire line
1629        if selection.range().is_empty() {
1630            let snapshot = context.buffer().read(cx).snapshot();
1631            let point = snapshot.offset_to_point(selection.range().start);
1632            selection.start = snapshot.point_to_offset(Point::new(point.row, 0));
1633            selection.end = snapshot
1634                .point_to_offset(cmp::min(Point::new(point.row + 1, 0), snapshot.max_point()));
1635            for chunk in context.buffer().read(cx).text_for_range(selection.range()) {
1636                text.push_str(chunk);
1637            }
1638        } else {
1639            for message in context.messages(cx) {
1640                if message.offset_range.start >= selection.range().end {
1641                    break;
1642                } else if message.offset_range.end >= selection.range().start {
1643                    let range = cmp::max(message.offset_range.start, selection.range().start)
1644                        ..cmp::min(message.offset_range.end, selection.range().end);
1645                    if !range.is_empty() {
1646                        for chunk in context.buffer().read(cx).text_for_range(range) {
1647                            text.push_str(chunk);
1648                        }
1649                        if message.offset_range.end < selection.range().end {
1650                            text.push('\n');
1651                        }
1652                    }
1653                }
1654            }
1655        }
1656        (text, CopyMetadata { creases }, vec![selection])
1657    }
1658
1659    fn paste(
1660        &mut self,
1661        action: &editor::actions::Paste,
1662        window: &mut Window,
1663        cx: &mut Context<Self>,
1664    ) {
1665        cx.stop_propagation();
1666
1667        let images = if let Some(item) = cx.read_from_clipboard() {
1668            item.into_entries()
1669                .filter_map(|entry| {
1670                    if let ClipboardEntry::Image(image) = entry {
1671                        Some(image)
1672                    } else {
1673                        None
1674                    }
1675                })
1676                .collect()
1677        } else {
1678            Vec::new()
1679        };
1680
1681        let metadata = if let Some(item) = cx.read_from_clipboard() {
1682            item.entries().first().and_then(|entry| {
1683                if let ClipboardEntry::String(text) = entry {
1684                    text.metadata_json::<CopyMetadata>()
1685                } else {
1686                    None
1687                }
1688            })
1689        } else {
1690            None
1691        };
1692
1693        if images.is_empty() {
1694            self.editor.update(cx, |editor, cx| {
1695                let paste_position = editor.selections.newest::<usize>(cx).head();
1696                editor.paste(action, window, cx);
1697
1698                if let Some(metadata) = metadata {
1699                    let buffer = editor.buffer().read(cx).snapshot(cx);
1700
1701                    let mut buffer_rows_to_fold = BTreeSet::new();
1702                    let weak_editor = cx.entity().downgrade();
1703                    editor.insert_creases(
1704                        metadata.creases.into_iter().map(|metadata| {
1705                            let start = buffer.anchor_after(
1706                                paste_position + metadata.range_relative_to_selection.start,
1707                            );
1708                            let end = buffer.anchor_before(
1709                                paste_position + metadata.range_relative_to_selection.end,
1710                            );
1711
1712                            let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1713                            buffer_rows_to_fold.insert(buffer_row);
1714                            Crease::inline(
1715                                start..end,
1716                                FoldPlaceholder {
1717                                    render: render_fold_icon_button(
1718                                        weak_editor.clone(),
1719                                        metadata.crease.icon_path.clone(),
1720                                        metadata.crease.label.clone(),
1721                                    ),
1722                                    ..Default::default()
1723                                },
1724                                render_slash_command_output_toggle,
1725                                |_, _, _, _| Empty.into_any(),
1726                            )
1727                            .with_metadata(metadata.crease)
1728                        }),
1729                        cx,
1730                    );
1731                    for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1732                        editor.fold_at(buffer_row, window, cx);
1733                    }
1734                }
1735            });
1736        } else {
1737            let mut image_positions = Vec::new();
1738            self.editor.update(cx, |editor, cx| {
1739                editor.transact(window, cx, |editor, _window, cx| {
1740                    let edits = editor
1741                        .selections
1742                        .all::<usize>(cx)
1743                        .into_iter()
1744                        .map(|selection| (selection.start..selection.end, "\n"));
1745                    editor.edit(edits, cx);
1746
1747                    let snapshot = editor.buffer().read(cx).snapshot(cx);
1748                    for selection in editor.selections.all::<usize>(cx) {
1749                        image_positions.push(snapshot.anchor_before(selection.end));
1750                    }
1751                });
1752            });
1753
1754            self.context.update(cx, |context, cx| {
1755                for image in images {
1756                    let Some(render_image) = image.to_image_data(cx.svg_renderer()).log_err()
1757                    else {
1758                        continue;
1759                    };
1760                    let image_id = image.id();
1761                    let image_task = LanguageModelImage::from_image(Arc::new(image), cx).shared();
1762
1763                    for image_position in image_positions.iter() {
1764                        context.insert_content(
1765                            Content::Image {
1766                                anchor: image_position.text_anchor,
1767                                image_id,
1768                                image: image_task.clone(),
1769                                render_image: render_image.clone(),
1770                            },
1771                            cx,
1772                        );
1773                    }
1774                }
1775            });
1776        }
1777    }
1778
1779    fn update_image_blocks(&mut self, cx: &mut Context<Self>) {
1780        self.editor.update(cx, |editor, cx| {
1781            let buffer = editor.buffer().read(cx).snapshot(cx);
1782            let excerpt_id = *buffer.as_singleton().unwrap().0;
1783            let old_blocks = std::mem::take(&mut self.image_blocks);
1784            let new_blocks = self
1785                .context
1786                .read(cx)
1787                .contents(cx)
1788                .map(
1789                    |Content::Image {
1790                         anchor,
1791                         render_image,
1792                         ..
1793                     }| (anchor, render_image),
1794                )
1795                .filter_map(|(anchor, render_image)| {
1796                    const MAX_HEIGHT_IN_LINES: u32 = 8;
1797                    let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
1798                    let image = render_image;
1799                    anchor.is_valid(&buffer).then(|| BlockProperties {
1800                        placement: BlockPlacement::Above(anchor),
1801                        height: Some(MAX_HEIGHT_IN_LINES),
1802                        style: BlockStyle::Sticky,
1803                        render: Arc::new(move |cx| {
1804                            let image_size = size_for_image(
1805                                &image,
1806                                size(
1807                                    cx.max_width - cx.margins.gutter.full_width(),
1808                                    MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
1809                                ),
1810                            );
1811                            h_flex()
1812                                .pl(cx.margins.gutter.full_width())
1813                                .child(
1814                                    img(image.clone())
1815                                        .object_fit(gpui::ObjectFit::ScaleDown)
1816                                        .w(image_size.width)
1817                                        .h(image_size.height),
1818                                )
1819                                .into_any_element()
1820                        }),
1821                        priority: 0,
1822                    })
1823                })
1824                .collect::<Vec<_>>();
1825
1826            editor.remove_blocks(old_blocks, None, cx);
1827            let ids = editor.insert_blocks(new_blocks, None, cx);
1828            self.image_blocks = HashSet::from_iter(ids);
1829        });
1830    }
1831
1832    fn split(&mut self, _: &Split, _window: &mut Window, cx: &mut Context<Self>) {
1833        self.context.update(cx, |context, cx| {
1834            let selections = self.editor.read(cx).selections.disjoint_anchors();
1835            for selection in selections.as_ref() {
1836                let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
1837                let range = selection
1838                    .map(|endpoint| endpoint.to_offset(&buffer))
1839                    .range();
1840                context.split_message(range, cx);
1841            }
1842        });
1843    }
1844
1845    fn save(&mut self, _: &Save, _window: &mut Window, cx: &mut Context<Self>) {
1846        self.context.update(cx, |context, cx| {
1847            context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
1848        });
1849    }
1850
1851    pub fn title(&self, cx: &App) -> SharedString {
1852        self.context.read(cx).summary().or_default()
1853    }
1854
1855    pub fn regenerate_summary(&mut self, cx: &mut Context<Self>) {
1856        self.context
1857            .update(cx, |context, cx| context.summarize(true, cx));
1858    }
1859
1860    fn render_remaining_tokens(&self, cx: &App) -> Option<impl IntoElement + use<>> {
1861        let (token_count_color, token_count, max_token_count, tooltip) =
1862            match token_state(&self.context, cx)? {
1863                TokenState::NoTokensLeft {
1864                    max_token_count,
1865                    token_count,
1866                } => (
1867                    Color::Error,
1868                    token_count,
1869                    max_token_count,
1870                    Some("Token Limit Reached"),
1871                ),
1872                TokenState::HasMoreTokens {
1873                    max_token_count,
1874                    token_count,
1875                    over_warn_threshold,
1876                } => {
1877                    let (color, tooltip) = if over_warn_threshold {
1878                        (Color::Warning, Some("Token Limit is Close to Exhaustion"))
1879                    } else {
1880                        (Color::Muted, None)
1881                    };
1882                    (color, token_count, max_token_count, tooltip)
1883                }
1884            };
1885
1886        Some(
1887            h_flex()
1888                .id("token-count")
1889                .gap_0p5()
1890                .child(
1891                    Label::new(humanize_token_count(token_count))
1892                        .size(LabelSize::Small)
1893                        .color(token_count_color),
1894                )
1895                .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
1896                .child(
1897                    Label::new(humanize_token_count(max_token_count))
1898                        .size(LabelSize::Small)
1899                        .color(Color::Muted),
1900                )
1901                .when_some(tooltip, |element, tooltip| {
1902                    element.tooltip(Tooltip::text(tooltip))
1903                }),
1904        )
1905    }
1906
1907    fn render_send_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1908        let focus_handle = self.focus_handle(cx);
1909
1910        let (style, tooltip) = match token_state(&self.context, cx) {
1911            Some(TokenState::NoTokensLeft { .. }) => (
1912                ButtonStyle::Tinted(TintColor::Error),
1913                Some(Tooltip::text("Token limit reached")(window, cx)),
1914            ),
1915            Some(TokenState::HasMoreTokens {
1916                over_warn_threshold,
1917                ..
1918            }) => {
1919                let (style, tooltip) = if over_warn_threshold {
1920                    (
1921                        ButtonStyle::Tinted(TintColor::Warning),
1922                        Some(Tooltip::text("Token limit is close to exhaustion")(
1923                            window, cx,
1924                        )),
1925                    )
1926                } else {
1927                    (ButtonStyle::Filled, None)
1928                };
1929                (style, tooltip)
1930            }
1931            None => (ButtonStyle::Filled, None),
1932        };
1933
1934        Button::new("send_button", "Send")
1935            .label_size(LabelSize::Small)
1936            .disabled(self.sending_disabled(cx))
1937            .style(style)
1938            .when_some(tooltip, |button, tooltip| {
1939                button.tooltip(move |_, _| tooltip.clone())
1940            })
1941            .layer(ElevationIndex::ModalSurface)
1942            .key_binding(
1943                KeyBinding::for_action_in(&Assist, &focus_handle, window, cx)
1944                    .map(|kb| kb.size(rems_from_px(12.))),
1945            )
1946            .on_click(move |_event, window, cx| {
1947                focus_handle.dispatch_action(&Assist, window, cx);
1948            })
1949    }
1950
1951    /// Whether or not we should allow messages to be sent.
1952    /// Will return false if the selected provided has a configuration error or
1953    /// if the user has not accepted the terms of service for this provider.
1954    fn sending_disabled(&self, cx: &mut Context<'_, TextThreadEditor>) -> bool {
1955        let model_registry = LanguageModelRegistry::read_global(cx);
1956        let Some(configuration_error) =
1957            model_registry.configuration_error(model_registry.default_model(), cx)
1958        else {
1959            return false;
1960        };
1961
1962        match configuration_error {
1963            ConfigurationError::NoProvider
1964            | ConfigurationError::ModelNotFound
1965            | ConfigurationError::ProviderNotAuthenticated(_) => true,
1966        }
1967    }
1968
1969    fn render_inject_context_menu(&self, cx: &mut Context<Self>) -> impl IntoElement {
1970        slash_command_picker::SlashCommandSelector::new(
1971            self.slash_commands.clone(),
1972            cx.entity().downgrade(),
1973            IconButton::new("trigger", IconName::Plus)
1974                .icon_size(IconSize::Small)
1975                .icon_color(Color::Muted),
1976            move |window, cx| {
1977                Tooltip::with_meta(
1978                    "Add Context",
1979                    None,
1980                    "Type / to insert via keyboard",
1981                    window,
1982                    cx,
1983                )
1984            },
1985        )
1986    }
1987
1988    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
1989        let context = self.context().read(cx);
1990        let active_model = LanguageModelRegistry::read_global(cx)
1991            .default_model()
1992            .map(|default| default.model)?;
1993        if !active_model.supports_burn_mode() {
1994            return None;
1995        }
1996
1997        let active_completion_mode = context.completion_mode();
1998        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
1999        let icon = if burn_mode_enabled {
2000            IconName::ZedBurnModeOn
2001        } else {
2002            IconName::ZedBurnMode
2003        };
2004
2005        Some(
2006            IconButton::new("burn-mode", icon)
2007                .icon_size(IconSize::Small)
2008                .icon_color(Color::Muted)
2009                .toggle_state(burn_mode_enabled)
2010                .selected_icon_color(Color::Error)
2011                .on_click(cx.listener(move |this, _event, _window, cx| {
2012                    this.context().update(cx, |context, _cx| {
2013                        context.set_completion_mode(match active_completion_mode {
2014                            CompletionMode::Burn => CompletionMode::Normal,
2015                            CompletionMode::Normal => CompletionMode::Burn,
2016                        });
2017                    });
2018                }))
2019                .tooltip(move |_window, cx| {
2020                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
2021                        .into()
2022                })
2023                .into_any_element(),
2024        )
2025    }
2026
2027    fn render_language_model_selector(
2028        &self,
2029        window: &mut Window,
2030        cx: &mut Context<Self>,
2031    ) -> impl IntoElement {
2032        let active_model = LanguageModelRegistry::read_global(cx)
2033            .default_model()
2034            .map(|default| default.model);
2035        let model_name = match active_model {
2036            Some(model) => model.name().0,
2037            None => SharedString::from("Select Model"),
2038        };
2039
2040        let active_provider = LanguageModelRegistry::read_global(cx)
2041            .default_model()
2042            .map(|default| default.provider);
2043
2044        let provider_icon = match active_provider {
2045            Some(provider) => provider.icon(),
2046            None => IconName::Ai,
2047        };
2048
2049        let focus_handle = self.editor().focus_handle(cx);
2050
2051        PickerPopoverMenu::new(
2052            self.language_model_selector.clone(),
2053            ButtonLike::new("active-model")
2054                .style(ButtonStyle::Subtle)
2055                .child(
2056                    h_flex()
2057                        .gap_0p5()
2058                        .child(
2059                            Icon::new(provider_icon)
2060                                .color(Color::Muted)
2061                                .size(IconSize::XSmall),
2062                        )
2063                        .child(
2064                            Label::new(model_name)
2065                                .color(Color::Muted)
2066                                .size(LabelSize::Small)
2067                                .ml_0p5(),
2068                        )
2069                        .child(
2070                            Icon::new(IconName::ChevronDown)
2071                                .color(Color::Muted)
2072                                .size(IconSize::XSmall),
2073                        ),
2074                ),
2075            move |window, cx| {
2076                Tooltip::for_action_in(
2077                    "Change Model",
2078                    &ToggleModelSelector,
2079                    &focus_handle,
2080                    window,
2081                    cx,
2082                )
2083            },
2084            gpui::Corner::BottomLeft,
2085            cx,
2086        )
2087        .with_handle(self.language_model_selector_menu_handle.clone())
2088        .render(window, cx)
2089    }
2090
2091    fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2092        let last_error = self.last_error.as_ref()?;
2093
2094        Some(
2095            div()
2096                .absolute()
2097                .right_3()
2098                .bottom_12()
2099                .max_w_96()
2100                .py_2()
2101                .px_3()
2102                .elevation_2(cx)
2103                .occlude()
2104                .child(match last_error {
2105                    AssistError::PaymentRequired => self.render_payment_required_error(cx),
2106                    AssistError::Message(error_message) => {
2107                        self.render_assist_error(error_message, cx)
2108                    }
2109                })
2110                .into_any(),
2111        )
2112    }
2113
2114    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2115        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.";
2116
2117        v_flex()
2118            .gap_0p5()
2119            .child(
2120                h_flex()
2121                    .gap_1p5()
2122                    .items_center()
2123                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2124                    .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2125            )
2126            .child(
2127                div()
2128                    .id("error-message")
2129                    .max_h_24()
2130                    .overflow_y_scroll()
2131                    .child(Label::new(ERROR_MESSAGE)),
2132            )
2133            .child(
2134                h_flex()
2135                    .justify_end()
2136                    .mt_1()
2137                    .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
2138                        |this, _, _window, cx| {
2139                            this.last_error = None;
2140                            cx.open_url(&zed_urls::account_url(cx));
2141                            cx.notify();
2142                        },
2143                    )))
2144                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2145                        |this, _, _window, cx| {
2146                            this.last_error = None;
2147                            cx.notify();
2148                        },
2149                    ))),
2150            )
2151            .into_any()
2152    }
2153
2154    fn render_assist_error(
2155        &self,
2156        error_message: &SharedString,
2157        cx: &mut Context<Self>,
2158    ) -> AnyElement {
2159        v_flex()
2160            .gap_0p5()
2161            .child(
2162                h_flex()
2163                    .gap_1p5()
2164                    .items_center()
2165                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2166                    .child(
2167                        Label::new("Error interacting with language model")
2168                            .weight(FontWeight::MEDIUM),
2169                    ),
2170            )
2171            .child(
2172                div()
2173                    .id("error-message")
2174                    .max_h_32()
2175                    .overflow_y_scroll()
2176                    .child(Label::new(error_message.clone())),
2177            )
2178            .child(
2179                h_flex()
2180                    .justify_end()
2181                    .mt_1()
2182                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2183                        |this, _, _window, cx| {
2184                            this.last_error = None;
2185                            cx.notify();
2186                        },
2187                    ))),
2188            )
2189            .into_any()
2190    }
2191}
2192
2193/// Returns the contents of the *outermost* fenced code block that contains the given offset.
2194fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
2195    const CODE_BLOCK_NODE: &str = "fenced_code_block";
2196    const CODE_BLOCK_CONTENT: &str = "code_fence_content";
2197
2198    let layer = snapshot.syntax_layers().next()?;
2199
2200    let root_node = layer.node();
2201    let mut cursor = root_node.walk();
2202
2203    // Go to the first child for the given offset
2204    while cursor.goto_first_child_for_byte(offset).is_some() {
2205        // If we're at the end of the node, go to the next one.
2206        // Example: if you have a fenced-code-block, and you're on the start of the line
2207        // right after the closing ```, you want to skip the fenced-code-block and
2208        // go to the next sibling.
2209        if cursor.node().end_byte() == offset {
2210            cursor.goto_next_sibling();
2211        }
2212
2213        if cursor.node().start_byte() > offset {
2214            break;
2215        }
2216
2217        // We found the fenced code block.
2218        if cursor.node().kind() == CODE_BLOCK_NODE {
2219            // Now we need to find the child node that contains the code.
2220            cursor.goto_first_child();
2221            loop {
2222                if cursor.node().kind() == CODE_BLOCK_CONTENT {
2223                    return Some(cursor.node().byte_range());
2224                }
2225                if !cursor.goto_next_sibling() {
2226                    break;
2227                }
2228            }
2229        }
2230    }
2231
2232    None
2233}
2234
2235fn render_thought_process_fold_icon_button(
2236    editor: WeakEntity<Editor>,
2237    status: ThoughtProcessStatus,
2238) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2239    Arc::new(move |fold_id, fold_range, _cx| {
2240        let editor = editor.clone();
2241
2242        let button = ButtonLike::new(fold_id).layer(ElevationIndex::ElevatedSurface);
2243        let button = match status {
2244            ThoughtProcessStatus::Pending => button
2245                .child(
2246                    Icon::new(IconName::ToolThink)
2247                        .size(IconSize::Small)
2248                        .color(Color::Muted),
2249                )
2250                .child(
2251                    Label::new("Thinking…").color(Color::Muted).with_animation(
2252                        "pulsating-label",
2253                        Animation::new(Duration::from_secs(2))
2254                            .repeat()
2255                            .with_easing(pulsating_between(0.4, 0.8)),
2256                        |label, delta| label.alpha(delta),
2257                    ),
2258                ),
2259            ThoughtProcessStatus::Completed => button
2260                .style(ButtonStyle::Filled)
2261                .child(Icon::new(IconName::ToolThink).size(IconSize::Small))
2262                .child(Label::new("Thought Process").single_line()),
2263        };
2264
2265        button
2266            .on_click(move |_, window, cx| {
2267                editor
2268                    .update(cx, |editor, cx| {
2269                        let buffer_start = fold_range
2270                            .start
2271                            .to_point(&editor.buffer().read(cx).read(cx));
2272                        let buffer_row = MultiBufferRow(buffer_start.row);
2273                        editor.unfold_at(buffer_row, window, cx);
2274                    })
2275                    .ok();
2276            })
2277            .into_any_element()
2278    })
2279}
2280
2281fn render_fold_icon_button(
2282    editor: WeakEntity<Editor>,
2283    icon_path: SharedString,
2284    label: SharedString,
2285) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2286    Arc::new(move |fold_id, fold_range, _cx| {
2287        let editor = editor.clone();
2288        ButtonLike::new(fold_id)
2289            .style(ButtonStyle::Filled)
2290            .layer(ElevationIndex::ElevatedSurface)
2291            .child(Icon::from_path(icon_path.clone()))
2292            .child(Label::new(label.clone()).single_line())
2293            .on_click(move |_, window, cx| {
2294                editor
2295                    .update(cx, |editor, cx| {
2296                        let buffer_start = fold_range
2297                            .start
2298                            .to_point(&editor.buffer().read(cx).read(cx));
2299                        let buffer_row = MultiBufferRow(buffer_start.row);
2300                        editor.unfold_at(buffer_row, window, cx);
2301                    })
2302                    .ok();
2303            })
2304            .into_any_element()
2305    })
2306}
2307
2308type ToggleFold = Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>;
2309
2310fn render_slash_command_output_toggle(
2311    row: MultiBufferRow,
2312    is_folded: bool,
2313    fold: ToggleFold,
2314    _window: &mut Window,
2315    _cx: &mut App,
2316) -> AnyElement {
2317    Disclosure::new(
2318        ("slash-command-output-fold-indicator", row.0 as u64),
2319        !is_folded,
2320    )
2321    .toggle_state(is_folded)
2322    .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2323    .into_any_element()
2324}
2325
2326pub fn fold_toggle(
2327    name: &'static str,
2328) -> impl Fn(
2329    MultiBufferRow,
2330    bool,
2331    Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
2332    &mut Window,
2333    &mut App,
2334) -> AnyElement {
2335    move |row, is_folded, fold, _window, _cx| {
2336        Disclosure::new((name, row.0 as u64), !is_folded)
2337            .toggle_state(is_folded)
2338            .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2339            .into_any_element()
2340    }
2341}
2342
2343fn quote_selection_fold_placeholder(title: String, editor: WeakEntity<Editor>) -> FoldPlaceholder {
2344    FoldPlaceholder {
2345        render: Arc::new({
2346            move |fold_id, fold_range, _cx| {
2347                let editor = editor.clone();
2348                ButtonLike::new(fold_id)
2349                    .style(ButtonStyle::Filled)
2350                    .layer(ElevationIndex::ElevatedSurface)
2351                    .child(Icon::new(IconName::TextSnippet))
2352                    .child(Label::new(title.clone()).single_line())
2353                    .on_click(move |_, window, cx| {
2354                        editor
2355                            .update(cx, |editor, cx| {
2356                                let buffer_start = fold_range
2357                                    .start
2358                                    .to_point(&editor.buffer().read(cx).read(cx));
2359                                let buffer_row = MultiBufferRow(buffer_start.row);
2360                                editor.unfold_at(buffer_row, window, cx);
2361                            })
2362                            .ok();
2363                    })
2364                    .into_any_element()
2365            }
2366        }),
2367        merge_adjacent: false,
2368        ..Default::default()
2369    }
2370}
2371
2372fn render_quote_selection_output_toggle(
2373    row: MultiBufferRow,
2374    is_folded: bool,
2375    fold: ToggleFold,
2376    _window: &mut Window,
2377    _cx: &mut App,
2378) -> AnyElement {
2379    Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
2380        .toggle_state(is_folded)
2381        .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2382        .into_any_element()
2383}
2384
2385fn render_pending_slash_command_gutter_decoration(
2386    row: MultiBufferRow,
2387    status: &PendingSlashCommandStatus,
2388    confirm_command: Arc<dyn Fn(&mut Window, &mut App)>,
2389) -> AnyElement {
2390    let mut icon = IconButton::new(
2391        ("slash-command-gutter-decoration", row.0),
2392        ui::IconName::TriangleRight,
2393    )
2394    .on_click(move |_e, window, cx| confirm_command(window, cx))
2395    .icon_size(ui::IconSize::Small)
2396    .size(ui::ButtonSize::None);
2397
2398    match status {
2399        PendingSlashCommandStatus::Idle => {
2400            icon = icon.icon_color(Color::Muted);
2401        }
2402        PendingSlashCommandStatus::Running { .. } => {
2403            icon = icon.toggle_state(true);
2404        }
2405        PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
2406    }
2407
2408    icon.into_any_element()
2409}
2410
2411#[derive(Debug, Clone, Serialize, Deserialize)]
2412struct CopyMetadata {
2413    creases: Vec<SelectedCreaseMetadata>,
2414}
2415
2416#[derive(Debug, Clone, Serialize, Deserialize)]
2417struct SelectedCreaseMetadata {
2418    range_relative_to_selection: Range<usize>,
2419    crease: CreaseMetadata,
2420}
2421
2422impl EventEmitter<EditorEvent> for TextThreadEditor {}
2423impl EventEmitter<SearchEvent> for TextThreadEditor {}
2424
2425impl Render for TextThreadEditor {
2426    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2427        let language_model_selector = self.language_model_selector_menu_handle.clone();
2428
2429        v_flex()
2430            .key_context("ContextEditor")
2431            .capture_action(cx.listener(TextThreadEditor::cancel))
2432            .capture_action(cx.listener(TextThreadEditor::save))
2433            .capture_action(cx.listener(TextThreadEditor::copy))
2434            .capture_action(cx.listener(TextThreadEditor::cut))
2435            .capture_action(cx.listener(TextThreadEditor::paste))
2436            .capture_action(cx.listener(TextThreadEditor::cycle_message_role))
2437            .capture_action(cx.listener(TextThreadEditor::confirm_command))
2438            .on_action(cx.listener(TextThreadEditor::assist))
2439            .on_action(cx.listener(TextThreadEditor::split))
2440            .on_action(move |_: &ToggleModelSelector, window, cx| {
2441                language_model_selector.toggle(window, cx);
2442            })
2443            .size_full()
2444            .child(
2445                div()
2446                    .flex_grow()
2447                    .bg(cx.theme().colors().editor_background)
2448                    .child(self.editor.clone()),
2449            )
2450            .children(self.render_last_error(cx))
2451            .child(
2452                h_flex()
2453                    .relative()
2454                    .py_2()
2455                    .pl_1p5()
2456                    .pr_2()
2457                    .w_full()
2458                    .justify_between()
2459                    .border_t_1()
2460                    .border_color(cx.theme().colors().border_variant)
2461                    .bg(cx.theme().colors().editor_background)
2462                    .child(
2463                        h_flex()
2464                            .gap_0p5()
2465                            .child(self.render_inject_context_menu(cx))
2466                            .children(self.render_burn_mode_toggle(cx)),
2467                    )
2468                    .child(
2469                        h_flex()
2470                            .gap_2p5()
2471                            .children(self.render_remaining_tokens(cx))
2472                            .child(
2473                                h_flex()
2474                                    .gap_1()
2475                                    .child(self.render_language_model_selector(window, cx))
2476                                    .child(self.render_send_button(window, cx)),
2477                            ),
2478                    ),
2479            )
2480    }
2481}
2482
2483impl Focusable for TextThreadEditor {
2484    fn focus_handle(&self, cx: &App) -> FocusHandle {
2485        self.editor.focus_handle(cx)
2486    }
2487}
2488
2489impl Item for TextThreadEditor {
2490    type Event = editor::EditorEvent;
2491
2492    fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
2493        util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into()
2494    }
2495
2496    fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
2497        match event {
2498            EditorEvent::Edited { .. } => {
2499                f(item::ItemEvent::Edit);
2500            }
2501            EditorEvent::TitleChanged => {
2502                f(item::ItemEvent::UpdateTab);
2503            }
2504            _ => {}
2505        }
2506    }
2507
2508    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
2509        Some(self.title(cx).to_string().into())
2510    }
2511
2512    fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
2513        Some(Box::new(handle.clone()))
2514    }
2515
2516    fn set_nav_history(
2517        &mut self,
2518        nav_history: pane::ItemNavHistory,
2519        window: &mut Window,
2520        cx: &mut Context<Self>,
2521    ) {
2522        self.editor.update(cx, |editor, cx| {
2523            Item::set_nav_history(editor, nav_history, window, cx)
2524        })
2525    }
2526
2527    fn navigate(
2528        &mut self,
2529        data: Box<dyn std::any::Any>,
2530        window: &mut Window,
2531        cx: &mut Context<Self>,
2532    ) -> bool {
2533        self.editor
2534            .update(cx, |editor, cx| Item::navigate(editor, data, window, cx))
2535    }
2536
2537    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2538        self.editor
2539            .update(cx, |editor, cx| Item::deactivated(editor, window, cx))
2540    }
2541
2542    fn act_as_type<'a>(
2543        &'a self,
2544        type_id: TypeId,
2545        self_handle: &'a Entity<Self>,
2546        _: &'a App,
2547    ) -> Option<AnyView> {
2548        if type_id == TypeId::of::<Self>() {
2549            Some(self_handle.to_any())
2550        } else if type_id == TypeId::of::<Editor>() {
2551            Some(self.editor.to_any())
2552        } else {
2553            None
2554        }
2555    }
2556
2557    fn include_in_nav_history() -> bool {
2558        false
2559    }
2560}
2561
2562impl SearchableItem for TextThreadEditor {
2563    type Match = <Editor as SearchableItem>::Match;
2564
2565    fn clear_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2566        self.editor.update(cx, |editor, cx| {
2567            editor.clear_matches(window, cx);
2568        });
2569    }
2570
2571    fn update_matches(
2572        &mut self,
2573        matches: &[Self::Match],
2574        window: &mut Window,
2575        cx: &mut Context<Self>,
2576    ) {
2577        self.editor
2578            .update(cx, |editor, cx| editor.update_matches(matches, window, cx));
2579    }
2580
2581    fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
2582        self.editor
2583            .update(cx, |editor, cx| editor.query_suggestion(window, cx))
2584    }
2585
2586    fn activate_match(
2587        &mut self,
2588        index: usize,
2589        matches: &[Self::Match],
2590        window: &mut Window,
2591        cx: &mut Context<Self>,
2592    ) {
2593        self.editor.update(cx, |editor, cx| {
2594            editor.activate_match(index, matches, window, cx);
2595        });
2596    }
2597
2598    fn select_matches(
2599        &mut self,
2600        matches: &[Self::Match],
2601        window: &mut Window,
2602        cx: &mut Context<Self>,
2603    ) {
2604        self.editor
2605            .update(cx, |editor, cx| editor.select_matches(matches, window, cx));
2606    }
2607
2608    fn replace(
2609        &mut self,
2610        identifier: &Self::Match,
2611        query: &project::search::SearchQuery,
2612        window: &mut Window,
2613        cx: &mut Context<Self>,
2614    ) {
2615        self.editor.update(cx, |editor, cx| {
2616            editor.replace(identifier, query, window, cx)
2617        });
2618    }
2619
2620    fn find_matches(
2621        &mut self,
2622        query: Arc<project::search::SearchQuery>,
2623        window: &mut Window,
2624        cx: &mut Context<Self>,
2625    ) -> Task<Vec<Self::Match>> {
2626        self.editor
2627            .update(cx, |editor, cx| editor.find_matches(query, window, cx))
2628    }
2629
2630    fn active_match_index(
2631        &mut self,
2632        direction: Direction,
2633        matches: &[Self::Match],
2634        window: &mut Window,
2635        cx: &mut Context<Self>,
2636    ) -> Option<usize> {
2637        self.editor.update(cx, |editor, cx| {
2638            editor.active_match_index(direction, matches, window, cx)
2639        })
2640    }
2641}
2642
2643impl FollowableItem for TextThreadEditor {
2644    fn remote_id(&self) -> Option<workspace::ViewId> {
2645        self.remote_id
2646    }
2647
2648    fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant> {
2649        let context = self.context.read(cx);
2650        Some(proto::view::Variant::ContextEditor(
2651            proto::view::ContextEditor {
2652                context_id: context.id().to_proto(),
2653                editor: if let Some(proto::view::Variant::Editor(proto)) =
2654                    self.editor.read(cx).to_state_proto(window, cx)
2655                {
2656                    Some(proto)
2657                } else {
2658                    None
2659                },
2660            },
2661        ))
2662    }
2663
2664    fn from_state_proto(
2665        workspace: Entity<Workspace>,
2666        id: workspace::ViewId,
2667        state: &mut Option<proto::view::Variant>,
2668        window: &mut Window,
2669        cx: &mut App,
2670    ) -> Option<Task<Result<Entity<Self>>>> {
2671        let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
2672            return None;
2673        };
2674        let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
2675            unreachable!()
2676        };
2677
2678        let context_id = ContextId::from_proto(state.context_id);
2679        let editor_state = state.editor?;
2680
2681        let project = workspace.read(cx).project().clone();
2682        let agent_panel_delegate = <dyn AgentPanelDelegate>::try_global(cx)?;
2683
2684        let context_editor_task = workspace.update(cx, |workspace, cx| {
2685            agent_panel_delegate.open_remote_context(workspace, context_id, window, cx)
2686        });
2687
2688        Some(window.spawn(cx, async move |cx| {
2689            let context_editor = context_editor_task.await?;
2690            context_editor
2691                .update_in(cx, |context_editor, window, cx| {
2692                    context_editor.remote_id = Some(id);
2693                    context_editor.editor.update(cx, |editor, cx| {
2694                        editor.apply_update_proto(
2695                            &project,
2696                            proto::update_view::Variant::Editor(proto::update_view::Editor {
2697                                selections: editor_state.selections,
2698                                pending_selection: editor_state.pending_selection,
2699                                scroll_top_anchor: editor_state.scroll_top_anchor,
2700                                scroll_x: editor_state.scroll_y,
2701                                scroll_y: editor_state.scroll_y,
2702                                ..Default::default()
2703                            }),
2704                            window,
2705                            cx,
2706                        )
2707                    })
2708                })?
2709                .await?;
2710            Ok(context_editor)
2711        }))
2712    }
2713
2714    fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
2715        Editor::to_follow_event(event)
2716    }
2717
2718    fn add_event_to_update_proto(
2719        &self,
2720        event: &Self::Event,
2721        update: &mut Option<proto::update_view::Variant>,
2722        window: &Window,
2723        cx: &App,
2724    ) -> bool {
2725        self.editor
2726            .read(cx)
2727            .add_event_to_update_proto(event, update, window, cx)
2728    }
2729
2730    fn apply_update_proto(
2731        &mut self,
2732        project: &Entity<Project>,
2733        message: proto::update_view::Variant,
2734        window: &mut Window,
2735        cx: &mut Context<Self>,
2736    ) -> Task<Result<()>> {
2737        self.editor.update(cx, |editor, cx| {
2738            editor.apply_update_proto(project, message, window, cx)
2739        })
2740    }
2741
2742    fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
2743        true
2744    }
2745
2746    fn set_leader_id(
2747        &mut self,
2748        leader_id: Option<CollaboratorId>,
2749        window: &mut Window,
2750        cx: &mut Context<Self>,
2751    ) {
2752        self.editor
2753            .update(cx, |editor, cx| editor.set_leader_id(leader_id, window, cx))
2754    }
2755
2756    fn dedup(&self, existing: &Self, _window: &Window, cx: &App) -> Option<item::Dedup> {
2757        if existing.context.read(cx).id() == self.context.read(cx).id() {
2758            Some(item::Dedup::KeepExisting)
2759        } else {
2760            None
2761        }
2762    }
2763}
2764
2765enum PendingSlashCommand {}
2766
2767fn invoked_slash_command_fold_placeholder(
2768    command_id: InvokedSlashCommandId,
2769    context: WeakEntity<AssistantContext>,
2770) -> FoldPlaceholder {
2771    FoldPlaceholder {
2772        constrain_width: false,
2773        merge_adjacent: false,
2774        render: Arc::new(move |fold_id, _, cx| {
2775            let Some(context) = context.upgrade() else {
2776                return Empty.into_any();
2777            };
2778
2779            let Some(command) = context.read(cx).invoked_slash_command(&command_id) else {
2780                return Empty.into_any();
2781            };
2782
2783            h_flex()
2784                .id(fold_id)
2785                .px_1()
2786                .ml_6()
2787                .gap_2()
2788                .bg(cx.theme().colors().surface_background)
2789                .rounded_sm()
2790                .child(Label::new(format!("/{}", command.name)))
2791                .map(|parent| match &command.status {
2792                    InvokedSlashCommandStatus::Running(_) => {
2793                        parent.child(Icon::new(IconName::ArrowCircle).with_animation(
2794                            "arrow-circle",
2795                            Animation::new(Duration::from_secs(4)).repeat(),
2796                            |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2797                        ))
2798                    }
2799                    InvokedSlashCommandStatus::Error(message) => parent.child(
2800                        Label::new(format!("error: {message}"))
2801                            .single_line()
2802                            .color(Color::Error),
2803                    ),
2804                    InvokedSlashCommandStatus::Finished => parent,
2805                })
2806                .into_any_element()
2807        }),
2808        type_tag: Some(TypeId::of::<PendingSlashCommand>()),
2809    }
2810}
2811
2812enum TokenState {
2813    NoTokensLeft {
2814        max_token_count: u64,
2815        token_count: u64,
2816    },
2817    HasMoreTokens {
2818        max_token_count: u64,
2819        token_count: u64,
2820        over_warn_threshold: bool,
2821    },
2822}
2823
2824fn token_state(context: &Entity<AssistantContext>, cx: &App) -> Option<TokenState> {
2825    const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
2826
2827    let model = LanguageModelRegistry::read_global(cx)
2828        .default_model()?
2829        .model;
2830    let token_count = context.read(cx).token_count()?;
2831    let max_token_count = model.max_token_count_for_mode(context.read(cx).completion_mode().into());
2832    let token_state = if max_token_count.saturating_sub(token_count) == 0 {
2833        TokenState::NoTokensLeft {
2834            max_token_count,
2835            token_count,
2836        }
2837    } else {
2838        let over_warn_threshold =
2839            token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
2840        TokenState::HasMoreTokens {
2841            max_token_count,
2842            token_count,
2843            over_warn_threshold,
2844        }
2845    };
2846    Some(token_state)
2847}
2848
2849fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
2850    let image_size = data
2851        .size(0)
2852        .map(|dimension| Pixels::from(u32::from(dimension)));
2853    let image_ratio = image_size.width / image_size.height;
2854    let bounds_ratio = max_size.width / max_size.height;
2855
2856    if image_size.width > max_size.width || image_size.height > max_size.height {
2857        if bounds_ratio > image_ratio {
2858            size(
2859                image_size.width * (max_size.height / image_size.height),
2860                max_size.height,
2861            )
2862        } else {
2863            size(
2864                max_size.width,
2865                image_size.height * (max_size.width / image_size.width),
2866            )
2867        }
2868    } else {
2869        size(image_size.width, image_size.height)
2870    }
2871}
2872
2873pub fn humanize_token_count(count: u64) -> String {
2874    match count {
2875        0..=999 => count.to_string(),
2876        1000..=9999 => {
2877            let thousands = count / 1000;
2878            let hundreds = (count % 1000 + 50) / 100;
2879            if hundreds == 0 {
2880                format!("{}k", thousands)
2881            } else if hundreds == 10 {
2882                format!("{}k", thousands + 1)
2883            } else {
2884                format!("{}.{}k", thousands, hundreds)
2885            }
2886        }
2887        1_000_000..=9_999_999 => {
2888            let millions = count / 1_000_000;
2889            let hundred_thousands = (count % 1_000_000 + 50_000) / 100_000;
2890            if hundred_thousands == 0 {
2891                format!("{}M", millions)
2892            } else if hundred_thousands == 10 {
2893                format!("{}M", millions + 1)
2894            } else {
2895                format!("{}.{}M", millions, hundred_thousands)
2896            }
2897        }
2898        10_000_000.. => format!("{}M", (count + 500_000) / 1_000_000),
2899        _ => format!("{}k", (count + 500) / 1000),
2900    }
2901}
2902
2903pub fn make_lsp_adapter_delegate(
2904    project: &Entity<Project>,
2905    cx: &mut App,
2906) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
2907    project.update(cx, |project, cx| {
2908        // TODO: Find the right worktree.
2909        let Some(worktree) = project.worktrees(cx).next() else {
2910            return Ok(None::<Arc<dyn LspAdapterDelegate>>);
2911        };
2912        let http_client = project.client().http_client();
2913        project.lsp_store().update(cx, |_, cx| {
2914            Ok(Some(LocalLspAdapterDelegate::new(
2915                project.languages().clone(),
2916                project.environment(),
2917                cx.weak_entity(),
2918                &worktree,
2919                http_client,
2920                project.fs().clone(),
2921                cx,
2922            ) as Arc<dyn LspAdapterDelegate>))
2923        })
2924    })
2925}
2926
2927#[cfg(test)]
2928mod tests {
2929    use super::*;
2930    use editor::SelectionEffects;
2931    use fs::FakeFs;
2932    use gpui::{App, TestAppContext, VisualTestContext};
2933    use indoc::indoc;
2934    use language::{Buffer, LanguageRegistry};
2935    use pretty_assertions::assert_eq;
2936    use prompt_store::PromptBuilder;
2937    use text::OffsetRangeExt;
2938    use unindent::Unindent;
2939    use util::path;
2940
2941    #[gpui::test]
2942    async fn test_copy_paste_whole_message(cx: &mut TestAppContext) {
2943        let (context, context_editor, mut cx) = setup_context_editor_text(vec![
2944            (Role::User, "What is the Zed editor?"),
2945            (
2946                Role::Assistant,
2947                "Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.",
2948            ),
2949            (Role::User, ""),
2950        ],cx).await;
2951
2952        // Select & Copy whole user message
2953        assert_copy_paste_context_editor(
2954            &context_editor,
2955            message_range(&context, 0, &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            "},
2961            &mut cx,
2962        );
2963
2964        // Select & Copy whole assistant message
2965        assert_copy_paste_context_editor(
2966            &context_editor,
2967            message_range(&context, 1, &mut cx),
2968            indoc! {"
2969                What is the Zed editor?
2970                Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
2971                What is the Zed editor?
2972                Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
2973            "},
2974            &mut cx,
2975        );
2976    }
2977
2978    #[gpui::test]
2979    async fn test_copy_paste_no_selection(cx: &mut TestAppContext) {
2980        let (context, context_editor, mut cx) = setup_context_editor_text(
2981            vec![
2982                (Role::User, "user1"),
2983                (Role::Assistant, "assistant1"),
2984                (Role::Assistant, "assistant2"),
2985                (Role::User, ""),
2986            ],
2987            cx,
2988        )
2989        .await;
2990
2991        // Copy and paste first assistant message
2992        let message_2_range = message_range(&context, 1, &mut cx);
2993        assert_copy_paste_context_editor(
2994            &context_editor,
2995            message_2_range.start..message_2_range.start,
2996            indoc! {"
2997                user1
2998                assistant1
2999                assistant2
3000                assistant1
3001            "},
3002            &mut cx,
3003        );
3004
3005        // Copy and cut second assistant message
3006        let message_3_range = message_range(&context, 2, &mut cx);
3007        assert_copy_paste_context_editor(
3008            &context_editor,
3009            message_3_range.start..message_3_range.start,
3010            indoc! {"
3011                user1
3012                assistant1
3013                assistant2
3014                assistant1
3015                assistant2
3016            "},
3017            &mut cx,
3018        );
3019    }
3020
3021    #[gpui::test]
3022    fn test_find_code_blocks(cx: &mut App) {
3023        let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
3024
3025        let buffer = cx.new(|cx| {
3026            let text = r#"
3027                line 0
3028                line 1
3029                ```rust
3030                fn main() {}
3031                ```
3032                line 5
3033                line 6
3034                line 7
3035                ```go
3036                func main() {}
3037                ```
3038                line 11
3039                ```
3040                this is plain text code block
3041                ```
3042
3043                ```go
3044                func another() {}
3045                ```
3046                line 19
3047            "#
3048            .unindent();
3049            let mut buffer = Buffer::local(text, cx);
3050            buffer.set_language(Some(markdown.clone()), cx);
3051            buffer
3052        });
3053        let snapshot = buffer.read(cx).snapshot();
3054
3055        let code_blocks = vec![
3056            Point::new(3, 0)..Point::new(4, 0),
3057            Point::new(9, 0)..Point::new(10, 0),
3058            Point::new(13, 0)..Point::new(14, 0),
3059            Point::new(17, 0)..Point::new(18, 0),
3060        ]
3061        .into_iter()
3062        .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
3063        .collect::<Vec<_>>();
3064
3065        let expected_results = vec![
3066            (0, None),
3067            (1, None),
3068            (2, Some(code_blocks[0].clone())),
3069            (3, Some(code_blocks[0].clone())),
3070            (4, Some(code_blocks[0].clone())),
3071            (5, None),
3072            (6, None),
3073            (7, None),
3074            (8, Some(code_blocks[1].clone())),
3075            (9, Some(code_blocks[1].clone())),
3076            (10, Some(code_blocks[1].clone())),
3077            (11, None),
3078            (12, Some(code_blocks[2].clone())),
3079            (13, Some(code_blocks[2].clone())),
3080            (14, Some(code_blocks[2].clone())),
3081            (15, None),
3082            (16, Some(code_blocks[3].clone())),
3083            (17, Some(code_blocks[3].clone())),
3084            (18, Some(code_blocks[3].clone())),
3085            (19, None),
3086        ];
3087
3088        for (row, expected) in expected_results {
3089            let offset = snapshot.point_to_offset(Point::new(row, 0));
3090            let range = find_surrounding_code_block(&snapshot, offset);
3091            assert_eq!(range, expected, "unexpected result on row {:?}", row);
3092        }
3093    }
3094
3095    async fn setup_context_editor_text(
3096        messages: Vec<(Role, &str)>,
3097        cx: &mut TestAppContext,
3098    ) -> (
3099        Entity<AssistantContext>,
3100        Entity<TextThreadEditor>,
3101        VisualTestContext,
3102    ) {
3103        cx.update(init_test);
3104
3105        let fs = FakeFs::new(cx.executor());
3106        let context = create_context_with_messages(messages, cx);
3107
3108        let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
3109        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
3110        let workspace = window.root(cx).unwrap();
3111        let mut cx = VisualTestContext::from_window(*window, cx);
3112
3113        let context_editor = window
3114            .update(&mut cx, |_, window, cx| {
3115                cx.new(|cx| {
3116                    TextThreadEditor::for_context(
3117                        context.clone(),
3118                        fs,
3119                        workspace.downgrade(),
3120                        project,
3121                        None,
3122                        window,
3123                        cx,
3124                    )
3125                })
3126            })
3127            .unwrap();
3128
3129        (context, context_editor, cx)
3130    }
3131
3132    fn message_range(
3133        context: &Entity<AssistantContext>,
3134        message_ix: usize,
3135        cx: &mut TestAppContext,
3136    ) -> Range<usize> {
3137        context.update(cx, |context, cx| {
3138            context
3139                .messages(cx)
3140                .nth(message_ix)
3141                .unwrap()
3142                .anchor_range
3143                .to_offset(&context.buffer().read(cx).snapshot())
3144        })
3145    }
3146
3147    fn assert_copy_paste_context_editor<T: editor::ToOffset>(
3148        context_editor: &Entity<TextThreadEditor>,
3149        range: Range<T>,
3150        expected_text: &str,
3151        cx: &mut VisualTestContext,
3152    ) {
3153        context_editor.update_in(cx, |context_editor, window, cx| {
3154            context_editor.editor.update(cx, |editor, cx| {
3155                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
3156                    s.select_ranges([range])
3157                });
3158            });
3159
3160            context_editor.copy(&Default::default(), window, cx);
3161
3162            context_editor.editor.update(cx, |editor, cx| {
3163                editor.move_to_end(&Default::default(), window, cx);
3164            });
3165
3166            context_editor.paste(&Default::default(), window, cx);
3167
3168            context_editor.editor.update(cx, |editor, cx| {
3169                assert_eq!(editor.text(cx), expected_text);
3170            });
3171        });
3172    }
3173
3174    fn create_context_with_messages(
3175        mut messages: Vec<(Role, &str)>,
3176        cx: &mut TestAppContext,
3177    ) -> Entity<AssistantContext> {
3178        let registry = Arc::new(LanguageRegistry::test(cx.executor()));
3179        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3180        cx.new(|cx| {
3181            let mut context = AssistantContext::local(
3182                registry,
3183                None,
3184                None,
3185                prompt_builder.clone(),
3186                Arc::new(SlashCommandWorkingSet::default()),
3187                cx,
3188            );
3189            let mut message_1 = context.messages(cx).next().unwrap();
3190            let (role, text) = messages.remove(0);
3191
3192            loop {
3193                if role == message_1.role {
3194                    context.buffer().update(cx, |buffer, cx| {
3195                        buffer.edit([(message_1.offset_range, text)], None, cx);
3196                    });
3197                    break;
3198                }
3199                let mut ids = HashSet::default();
3200                ids.insert(message_1.id);
3201                context.cycle_message_roles(ids, cx);
3202                message_1 = context.messages(cx).next().unwrap();
3203            }
3204
3205            let mut last_message_id = message_1.id;
3206            for (role, text) in messages {
3207                context.insert_message_after(last_message_id, role, MessageStatus::Done, cx);
3208                let message = context.messages(cx).last().unwrap();
3209                last_message_id = message.id;
3210                context.buffer().update(cx, |buffer, cx| {
3211                    buffer.edit([(message.offset_range, text)], None, cx);
3212                })
3213            }
3214
3215            context
3216        })
3217    }
3218
3219    fn init_test(cx: &mut App) {
3220        let settings_store = SettingsStore::test(cx);
3221        prompt_store::init(cx);
3222        LanguageModelRegistry::test(cx);
3223        cx.set_global(settings_store);
3224        language::init(cx);
3225        agent_settings::init(cx);
3226        Project::init_settings(cx);
3227        theme::init(theme::LoadThemes::JustBase, cx);
3228        workspace::init_settings(cx);
3229        editor::init_settings(cx);
3230    }
3231}