context_editor.rs

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