text_thread_editor.rs

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