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