context_editor.rs

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