context_editor.rs

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