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