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