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                            div().max_w_32().child(
2408                                Label::new(model_name)
2409                                    .size(LabelSize::Small)
2410                                    .color(Color::Muted)
2411                                    .text_ellipsis()
2412                                    .into_any_element(),
2413                            ),
2414                        )
2415                        .child(
2416                            Icon::new(IconName::ChevronDown)
2417                                .color(Color::Muted)
2418                                .size(IconSize::XSmall),
2419                        ),
2420                ),
2421            move |window, cx| {
2422                Tooltip::for_action_in(
2423                    "Change Model",
2424                    &ToggleModelSelector,
2425                    &focus_handle,
2426                    window,
2427                    cx,
2428                )
2429            },
2430        )
2431        .with_handle(self.language_model_selector_menu_handle.clone())
2432    }
2433
2434    fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2435        let last_error = self.last_error.as_ref()?;
2436
2437        Some(
2438            div()
2439                .absolute()
2440                .right_3()
2441                .bottom_12()
2442                .max_w_96()
2443                .py_2()
2444                .px_3()
2445                .elevation_2(cx)
2446                .occlude()
2447                .child(match last_error {
2448                    AssistError::FileRequired => self.render_file_required_error(cx),
2449                    AssistError::PaymentRequired => self.render_payment_required_error(cx),
2450                    AssistError::MaxMonthlySpendReached => {
2451                        self.render_max_monthly_spend_reached_error(cx)
2452                    }
2453                    AssistError::Message(error_message) => {
2454                        self.render_assist_error(error_message, cx)
2455                    }
2456                })
2457                .into_any(),
2458        )
2459    }
2460
2461    fn render_file_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2462        v_flex()
2463            .gap_0p5()
2464            .child(
2465                h_flex()
2466                    .gap_1p5()
2467                    .items_center()
2468                    .child(Icon::new(IconName::Warning).color(Color::Warning))
2469                    .child(
2470                        Label::new("Suggest Edits needs a file to edit").weight(FontWeight::MEDIUM),
2471                    ),
2472            )
2473            .child(
2474                div()
2475                    .id("error-message")
2476                    .max_h_24()
2477                    .overflow_y_scroll()
2478                    .child(Label::new(
2479                        "To include files, type /file or /tab in your prompt.",
2480                    )),
2481            )
2482            .child(
2483                h_flex()
2484                    .justify_end()
2485                    .mt_1()
2486                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2487                        |this, _, _window, cx| {
2488                            this.last_error = None;
2489                            cx.notify();
2490                        },
2491                    ))),
2492            )
2493            .into_any()
2494    }
2495
2496    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2497        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.";
2498
2499        v_flex()
2500            .gap_0p5()
2501            .child(
2502                h_flex()
2503                    .gap_1p5()
2504                    .items_center()
2505                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2506                    .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2507            )
2508            .child(
2509                div()
2510                    .id("error-message")
2511                    .max_h_24()
2512                    .overflow_y_scroll()
2513                    .child(Label::new(ERROR_MESSAGE)),
2514            )
2515            .child(
2516                h_flex()
2517                    .justify_end()
2518                    .mt_1()
2519                    .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
2520                        |this, _, _window, cx| {
2521                            this.last_error = None;
2522                            cx.open_url(&zed_urls::account_url(cx));
2523                            cx.notify();
2524                        },
2525                    )))
2526                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2527                        |this, _, _window, cx| {
2528                            this.last_error = None;
2529                            cx.notify();
2530                        },
2531                    ))),
2532            )
2533            .into_any()
2534    }
2535
2536    fn render_max_monthly_spend_reached_error(&self, cx: &mut Context<Self>) -> AnyElement {
2537        const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
2538
2539        v_flex()
2540            .gap_0p5()
2541            .child(
2542                h_flex()
2543                    .gap_1p5()
2544                    .items_center()
2545                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2546                    .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
2547            )
2548            .child(
2549                div()
2550                    .id("error-message")
2551                    .max_h_24()
2552                    .overflow_y_scroll()
2553                    .child(Label::new(ERROR_MESSAGE)),
2554            )
2555            .child(
2556                h_flex()
2557                    .justify_end()
2558                    .mt_1()
2559                    .child(
2560                        Button::new("subscribe", "Update Monthly Spend Limit").on_click(
2561                            cx.listener(|this, _, _window, cx| {
2562                                this.last_error = None;
2563                                cx.open_url(&zed_urls::account_url(cx));
2564                                cx.notify();
2565                            }),
2566                        ),
2567                    )
2568                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2569                        |this, _, _window, cx| {
2570                            this.last_error = None;
2571                            cx.notify();
2572                        },
2573                    ))),
2574            )
2575            .into_any()
2576    }
2577
2578    fn render_assist_error(
2579        &self,
2580        error_message: &SharedString,
2581        cx: &mut Context<Self>,
2582    ) -> AnyElement {
2583        v_flex()
2584            .gap_0p5()
2585            .child(
2586                h_flex()
2587                    .gap_1p5()
2588                    .items_center()
2589                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2590                    .child(
2591                        Label::new("Error interacting with language model")
2592                            .weight(FontWeight::MEDIUM),
2593                    ),
2594            )
2595            .child(
2596                div()
2597                    .id("error-message")
2598                    .max_h_32()
2599                    .overflow_y_scroll()
2600                    .child(Label::new(error_message.clone())),
2601            )
2602            .child(
2603                h_flex()
2604                    .justify_end()
2605                    .mt_1()
2606                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2607                        |this, _, _window, cx| {
2608                            this.last_error = None;
2609                            cx.notify();
2610                        },
2611                    ))),
2612            )
2613            .into_any()
2614    }
2615}
2616
2617/// Returns the contents of the *outermost* fenced code block that contains the given offset.
2618fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
2619    const CODE_BLOCK_NODE: &'static str = "fenced_code_block";
2620    const CODE_BLOCK_CONTENT: &'static str = "code_fence_content";
2621
2622    let layer = snapshot.syntax_layers().next()?;
2623
2624    let root_node = layer.node();
2625    let mut cursor = root_node.walk();
2626
2627    // Go to the first child for the given offset
2628    while cursor.goto_first_child_for_byte(offset).is_some() {
2629        // If we're at the end of the node, go to the next one.
2630        // Example: if you have a fenced-code-block, and you're on the start of the line
2631        // right after the closing ```, you want to skip the fenced-code-block and
2632        // go to the next sibling.
2633        if cursor.node().end_byte() == offset {
2634            cursor.goto_next_sibling();
2635        }
2636
2637        if cursor.node().start_byte() > offset {
2638            break;
2639        }
2640
2641        // We found the fenced code block.
2642        if cursor.node().kind() == CODE_BLOCK_NODE {
2643            // Now we need to find the child node that contains the code.
2644            cursor.goto_first_child();
2645            loop {
2646                if cursor.node().kind() == CODE_BLOCK_CONTENT {
2647                    return Some(cursor.node().byte_range());
2648                }
2649                if !cursor.goto_next_sibling() {
2650                    break;
2651                }
2652            }
2653        }
2654    }
2655
2656    None
2657}
2658
2659fn render_fold_icon_button(
2660    editor: WeakEntity<Editor>,
2661    icon: IconName,
2662    label: SharedString,
2663) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut Window, &mut App) -> AnyElement> {
2664    Arc::new(move |fold_id, fold_range, _window, _cx| {
2665        let editor = editor.clone();
2666        ButtonLike::new(fold_id)
2667            .style(ButtonStyle::Filled)
2668            .layer(ElevationIndex::ElevatedSurface)
2669            .child(Icon::new(icon))
2670            .child(Label::new(label.clone()).single_line())
2671            .on_click(move |_, window, cx| {
2672                editor
2673                    .update(cx, |editor, cx| {
2674                        let buffer_start = fold_range
2675                            .start
2676                            .to_point(&editor.buffer().read(cx).read(cx));
2677                        let buffer_row = MultiBufferRow(buffer_start.row);
2678                        editor.unfold_at(&UnfoldAt { buffer_row }, window, cx);
2679                    })
2680                    .ok();
2681            })
2682            .into_any_element()
2683    })
2684}
2685
2686type ToggleFold = Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>;
2687
2688fn render_slash_command_output_toggle(
2689    row: MultiBufferRow,
2690    is_folded: bool,
2691    fold: ToggleFold,
2692    _window: &mut Window,
2693    _cx: &mut App,
2694) -> AnyElement {
2695    Disclosure::new(
2696        ("slash-command-output-fold-indicator", row.0 as u64),
2697        !is_folded,
2698    )
2699    .toggle_state(is_folded)
2700    .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2701    .into_any_element()
2702}
2703
2704pub fn fold_toggle(
2705    name: &'static str,
2706) -> impl Fn(
2707    MultiBufferRow,
2708    bool,
2709    Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
2710    &mut Window,
2711    &mut App,
2712) -> AnyElement {
2713    move |row, is_folded, fold, _window, _cx| {
2714        Disclosure::new((name, row.0 as u64), !is_folded)
2715            .toggle_state(is_folded)
2716            .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2717            .into_any_element()
2718    }
2719}
2720
2721fn quote_selection_fold_placeholder(title: String, editor: WeakEntity<Editor>) -> FoldPlaceholder {
2722    FoldPlaceholder {
2723        render: Arc::new({
2724            move |fold_id, fold_range, _window, _cx| {
2725                let editor = editor.clone();
2726                ButtonLike::new(fold_id)
2727                    .style(ButtonStyle::Filled)
2728                    .layer(ElevationIndex::ElevatedSurface)
2729                    .child(Icon::new(IconName::TextSnippet))
2730                    .child(Label::new(title.clone()).single_line())
2731                    .on_click(move |_, window, cx| {
2732                        editor
2733                            .update(cx, |editor, cx| {
2734                                let buffer_start = fold_range
2735                                    .start
2736                                    .to_point(&editor.buffer().read(cx).read(cx));
2737                                let buffer_row = MultiBufferRow(buffer_start.row);
2738                                editor.unfold_at(&UnfoldAt { buffer_row }, window, cx);
2739                            })
2740                            .ok();
2741                    })
2742                    .into_any_element()
2743            }
2744        }),
2745        merge_adjacent: false,
2746        ..Default::default()
2747    }
2748}
2749
2750fn render_quote_selection_output_toggle(
2751    row: MultiBufferRow,
2752    is_folded: bool,
2753    fold: ToggleFold,
2754    _window: &mut Window,
2755    _cx: &mut App,
2756) -> AnyElement {
2757    Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
2758        .toggle_state(is_folded)
2759        .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2760        .into_any_element()
2761}
2762
2763fn render_pending_slash_command_gutter_decoration(
2764    row: MultiBufferRow,
2765    status: &PendingSlashCommandStatus,
2766    confirm_command: Arc<dyn Fn(&mut Window, &mut App)>,
2767) -> AnyElement {
2768    let mut icon = IconButton::new(
2769        ("slash-command-gutter-decoration", row.0),
2770        ui::IconName::TriangleRight,
2771    )
2772    .on_click(move |_e, window, cx| confirm_command(window, cx))
2773    .icon_size(ui::IconSize::Small)
2774    .size(ui::ButtonSize::None);
2775
2776    match status {
2777        PendingSlashCommandStatus::Idle => {
2778            icon = icon.icon_color(Color::Muted);
2779        }
2780        PendingSlashCommandStatus::Running { .. } => {
2781            icon = icon.toggle_state(true);
2782        }
2783        PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
2784    }
2785
2786    icon.into_any_element()
2787}
2788
2789fn render_docs_slash_command_trailer(
2790    row: MultiBufferRow,
2791    command: ParsedSlashCommand,
2792    cx: &mut App,
2793) -> AnyElement {
2794    if command.arguments.is_empty() {
2795        return Empty.into_any();
2796    }
2797    let args = DocsSlashCommandArgs::parse(&command.arguments);
2798
2799    let Some(store) = args
2800        .provider()
2801        .and_then(|provider| IndexedDocsStore::try_global(provider, cx).ok())
2802    else {
2803        return Empty.into_any();
2804    };
2805
2806    let Some(package) = args.package() else {
2807        return Empty.into_any();
2808    };
2809
2810    let mut children = Vec::new();
2811
2812    if store.is_indexing(&package) {
2813        children.push(
2814            div()
2815                .id(("crates-being-indexed", row.0))
2816                .child(Icon::new(IconName::ArrowCircle).with_animation(
2817                    "arrow-circle",
2818                    Animation::new(Duration::from_secs(4)).repeat(),
2819                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
2820                ))
2821                .tooltip({
2822                    let package = package.clone();
2823                    Tooltip::text(format!("Indexing {package}"))
2824                })
2825                .into_any_element(),
2826        );
2827    }
2828
2829    if let Some(latest_error) = store.latest_error_for_package(&package) {
2830        children.push(
2831            div()
2832                .id(("latest-error", row.0))
2833                .child(
2834                    Icon::new(IconName::Warning)
2835                        .size(IconSize::Small)
2836                        .color(Color::Warning),
2837                )
2838                .tooltip(Tooltip::text(format!("Failed to index: {latest_error}")))
2839                .into_any_element(),
2840        )
2841    }
2842
2843    let is_indexing = store.is_indexing(&package);
2844    let latest_error = store.latest_error_for_package(&package);
2845
2846    if !is_indexing && latest_error.is_none() {
2847        return Empty.into_any();
2848    }
2849
2850    h_flex().gap_2().children(children).into_any_element()
2851}
2852
2853#[derive(Debug, Clone, Serialize, Deserialize)]
2854struct CopyMetadata {
2855    creases: Vec<SelectedCreaseMetadata>,
2856}
2857
2858#[derive(Debug, Clone, Serialize, Deserialize)]
2859struct SelectedCreaseMetadata {
2860    range_relative_to_selection: Range<usize>,
2861    crease: CreaseMetadata,
2862}
2863
2864impl EventEmitter<EditorEvent> for ContextEditor {}
2865impl EventEmitter<SearchEvent> for ContextEditor {}
2866
2867impl Render for ContextEditor {
2868    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2869        let provider = LanguageModelRegistry::read_global(cx).active_provider();
2870        let accept_terms = if self.show_accept_terms {
2871            provider.as_ref().and_then(|provider| {
2872                provider.render_accept_terms(LanguageModelProviderTosView::PromptEditorPopup, cx)
2873            })
2874        } else {
2875            None
2876        };
2877
2878        v_flex()
2879            .key_context("ContextEditor")
2880            .capture_action(cx.listener(ContextEditor::cancel))
2881            .capture_action(cx.listener(ContextEditor::save))
2882            .capture_action(cx.listener(ContextEditor::copy))
2883            .capture_action(cx.listener(ContextEditor::cut))
2884            .capture_action(cx.listener(ContextEditor::paste))
2885            .capture_action(cx.listener(ContextEditor::cycle_message_role))
2886            .capture_action(cx.listener(ContextEditor::confirm_command))
2887            .on_action(cx.listener(ContextEditor::edit))
2888            .on_action(cx.listener(ContextEditor::assist))
2889            .on_action(cx.listener(ContextEditor::split))
2890            .size_full()
2891            .children(self.render_notice(cx))
2892            .child(
2893                div()
2894                    .flex_grow()
2895                    .bg(cx.theme().colors().editor_background)
2896                    .child(self.editor.clone()),
2897            )
2898            .when_some(accept_terms, |this, element| {
2899                this.child(
2900                    div()
2901                        .absolute()
2902                        .right_3()
2903                        .bottom_12()
2904                        .max_w_96()
2905                        .py_2()
2906                        .px_3()
2907                        .elevation_2(cx)
2908                        .bg(cx.theme().colors().surface_background)
2909                        .occlude()
2910                        .child(element),
2911                )
2912            })
2913            .children(self.render_last_error(cx))
2914            .child(
2915                h_flex().w_full().relative().child(
2916                    h_flex()
2917                        .p_2()
2918                        .w_full()
2919                        .border_t_1()
2920                        .border_color(cx.theme().colors().border_variant)
2921                        .bg(cx.theme().colors().editor_background)
2922                        .child(
2923                            h_flex()
2924                                .gap_1()
2925                                .child(self.render_inject_context_menu(cx))
2926                                .child(ui::Divider::vertical())
2927                                .child(
2928                                    div()
2929                                        .pl_0p5()
2930                                        .child(self.render_language_model_selector(cx)),
2931                                ),
2932                        )
2933                        .child(
2934                            h_flex()
2935                                .w_full()
2936                                .justify_end()
2937                                .when(
2938                                    AssistantSettings::get_global(cx).are_live_diffs_enabled(cx),
2939                                    |buttons| {
2940                                        buttons
2941                                            .items_center()
2942                                            .gap_1p5()
2943                                            .child(self.render_edit_button(window, cx))
2944                                            .child(
2945                                                Label::new("or")
2946                                                    .size(LabelSize::Small)
2947                                                    .color(Color::Muted),
2948                                            )
2949                                    },
2950                                )
2951                                .child(self.render_send_button(window, cx)),
2952                        ),
2953                ),
2954            )
2955    }
2956}
2957
2958impl Focusable for ContextEditor {
2959    fn focus_handle(&self, cx: &App) -> FocusHandle {
2960        self.editor.focus_handle(cx)
2961    }
2962}
2963
2964impl Item for ContextEditor {
2965    type Event = editor::EditorEvent;
2966
2967    fn tab_content_text(&self, _window: &Window, cx: &App) -> Option<SharedString> {
2968        Some(util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into())
2969    }
2970
2971    fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
2972        match event {
2973            EditorEvent::Edited { .. } => {
2974                f(item::ItemEvent::Edit);
2975            }
2976            EditorEvent::TitleChanged => {
2977                f(item::ItemEvent::UpdateTab);
2978            }
2979            _ => {}
2980        }
2981    }
2982
2983    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
2984        Some(self.title(cx).to_string().into())
2985    }
2986
2987    fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
2988        Some(Box::new(handle.clone()))
2989    }
2990
2991    fn set_nav_history(
2992        &mut self,
2993        nav_history: pane::ItemNavHistory,
2994        window: &mut Window,
2995        cx: &mut Context<Self>,
2996    ) {
2997        self.editor.update(cx, |editor, cx| {
2998            Item::set_nav_history(editor, nav_history, window, cx)
2999        })
3000    }
3001
3002    fn navigate(
3003        &mut self,
3004        data: Box<dyn std::any::Any>,
3005        window: &mut Window,
3006        cx: &mut Context<Self>,
3007    ) -> bool {
3008        self.editor
3009            .update(cx, |editor, cx| Item::navigate(editor, data, window, cx))
3010    }
3011
3012    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3013        self.editor
3014            .update(cx, |editor, cx| Item::deactivated(editor, window, cx))
3015    }
3016
3017    fn act_as_type<'a>(
3018        &'a self,
3019        type_id: TypeId,
3020        self_handle: &'a Entity<Self>,
3021        _: &'a App,
3022    ) -> Option<AnyView> {
3023        if type_id == TypeId::of::<Self>() {
3024            Some(self_handle.to_any())
3025        } else if type_id == TypeId::of::<Editor>() {
3026            Some(self.editor.to_any())
3027        } else {
3028            None
3029        }
3030    }
3031
3032    fn include_in_nav_history() -> bool {
3033        false
3034    }
3035}
3036
3037impl SearchableItem for ContextEditor {
3038    type Match = <Editor as SearchableItem>::Match;
3039
3040    fn clear_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3041        self.editor.update(cx, |editor, cx| {
3042            editor.clear_matches(window, cx);
3043        });
3044    }
3045
3046    fn update_matches(
3047        &mut self,
3048        matches: &[Self::Match],
3049        window: &mut Window,
3050        cx: &mut Context<Self>,
3051    ) {
3052        self.editor
3053            .update(cx, |editor, cx| editor.update_matches(matches, window, cx));
3054    }
3055
3056    fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
3057        self.editor
3058            .update(cx, |editor, cx| editor.query_suggestion(window, cx))
3059    }
3060
3061    fn activate_match(
3062        &mut self,
3063        index: usize,
3064        matches: &[Self::Match],
3065        window: &mut Window,
3066        cx: &mut Context<Self>,
3067    ) {
3068        self.editor.update(cx, |editor, cx| {
3069            editor.activate_match(index, matches, window, cx);
3070        });
3071    }
3072
3073    fn select_matches(
3074        &mut self,
3075        matches: &[Self::Match],
3076        window: &mut Window,
3077        cx: &mut Context<Self>,
3078    ) {
3079        self.editor
3080            .update(cx, |editor, cx| editor.select_matches(matches, window, cx));
3081    }
3082
3083    fn replace(
3084        &mut self,
3085        identifier: &Self::Match,
3086        query: &project::search::SearchQuery,
3087        window: &mut Window,
3088        cx: &mut Context<Self>,
3089    ) {
3090        self.editor.update(cx, |editor, cx| {
3091            editor.replace(identifier, query, window, cx)
3092        });
3093    }
3094
3095    fn find_matches(
3096        &mut self,
3097        query: Arc<project::search::SearchQuery>,
3098        window: &mut Window,
3099        cx: &mut Context<Self>,
3100    ) -> Task<Vec<Self::Match>> {
3101        self.editor
3102            .update(cx, |editor, cx| editor.find_matches(query, window, cx))
3103    }
3104
3105    fn active_match_index(
3106        &mut self,
3107        matches: &[Self::Match],
3108        window: &mut Window,
3109        cx: &mut Context<Self>,
3110    ) -> Option<usize> {
3111        self.editor.update(cx, |editor, cx| {
3112            editor.active_match_index(matches, window, cx)
3113        })
3114    }
3115}
3116
3117impl FollowableItem for ContextEditor {
3118    fn remote_id(&self) -> Option<workspace::ViewId> {
3119        self.remote_id
3120    }
3121
3122    fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant> {
3123        let context = self.context.read(cx);
3124        Some(proto::view::Variant::ContextEditor(
3125            proto::view::ContextEditor {
3126                context_id: context.id().to_proto(),
3127                editor: if let Some(proto::view::Variant::Editor(proto)) =
3128                    self.editor.read(cx).to_state_proto(window, cx)
3129                {
3130                    Some(proto)
3131                } else {
3132                    None
3133                },
3134            },
3135        ))
3136    }
3137
3138    fn from_state_proto(
3139        workspace: Entity<Workspace>,
3140        id: workspace::ViewId,
3141        state: &mut Option<proto::view::Variant>,
3142        window: &mut Window,
3143        cx: &mut App,
3144    ) -> Option<Task<Result<Entity<Self>>>> {
3145        let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
3146            return None;
3147        };
3148        let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
3149            unreachable!()
3150        };
3151
3152        let context_id = ContextId::from_proto(state.context_id);
3153        let editor_state = state.editor?;
3154
3155        let project = workspace.read(cx).project().clone();
3156        let assistant_panel_delegate = <dyn AssistantPanelDelegate>::try_global(cx)?;
3157
3158        let context_editor_task = workspace.update(cx, |workspace, cx| {
3159            assistant_panel_delegate.open_remote_context(workspace, context_id, window, cx)
3160        });
3161
3162        Some(window.spawn(cx, |mut cx| async move {
3163            let context_editor = context_editor_task.await?;
3164            context_editor
3165                .update_in(&mut cx, |context_editor, window, cx| {
3166                    context_editor.remote_id = Some(id);
3167                    context_editor.editor.update(cx, |editor, cx| {
3168                        editor.apply_update_proto(
3169                            &project,
3170                            proto::update_view::Variant::Editor(proto::update_view::Editor {
3171                                selections: editor_state.selections,
3172                                pending_selection: editor_state.pending_selection,
3173                                scroll_top_anchor: editor_state.scroll_top_anchor,
3174                                scroll_x: editor_state.scroll_y,
3175                                scroll_y: editor_state.scroll_y,
3176                                ..Default::default()
3177                            }),
3178                            window,
3179                            cx,
3180                        )
3181                    })
3182                })?
3183                .await?;
3184            Ok(context_editor)
3185        }))
3186    }
3187
3188    fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
3189        Editor::to_follow_event(event)
3190    }
3191
3192    fn add_event_to_update_proto(
3193        &self,
3194        event: &Self::Event,
3195        update: &mut Option<proto::update_view::Variant>,
3196        window: &Window,
3197        cx: &App,
3198    ) -> bool {
3199        self.editor
3200            .read(cx)
3201            .add_event_to_update_proto(event, update, window, cx)
3202    }
3203
3204    fn apply_update_proto(
3205        &mut self,
3206        project: &Entity<Project>,
3207        message: proto::update_view::Variant,
3208        window: &mut Window,
3209        cx: &mut Context<Self>,
3210    ) -> Task<Result<()>> {
3211        self.editor.update(cx, |editor, cx| {
3212            editor.apply_update_proto(project, message, window, cx)
3213        })
3214    }
3215
3216    fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
3217        true
3218    }
3219
3220    fn set_leader_peer_id(
3221        &mut self,
3222        leader_peer_id: Option<proto::PeerId>,
3223        window: &mut Window,
3224        cx: &mut Context<Self>,
3225    ) {
3226        self.editor.update(cx, |editor, cx| {
3227            editor.set_leader_peer_id(leader_peer_id, window, cx)
3228        })
3229    }
3230
3231    fn dedup(&self, existing: &Self, _window: &Window, cx: &App) -> Option<item::Dedup> {
3232        if existing.context.read(cx).id() == self.context.read(cx).id() {
3233            Some(item::Dedup::KeepExisting)
3234        } else {
3235            None
3236        }
3237    }
3238}
3239
3240pub struct ContextEditorToolbarItem {
3241    active_context_editor: Option<WeakEntity<ContextEditor>>,
3242    model_summary_editor: Entity<Editor>,
3243}
3244
3245impl ContextEditorToolbarItem {
3246    pub fn new(model_summary_editor: Entity<Editor>) -> Self {
3247        Self {
3248            active_context_editor: None,
3249            model_summary_editor,
3250        }
3251    }
3252}
3253
3254pub fn render_remaining_tokens(
3255    context_editor: &Entity<ContextEditor>,
3256    cx: &App,
3257) -> Option<impl IntoElement> {
3258    let context = &context_editor.read(cx).context;
3259
3260    let (token_count_color, token_count, max_token_count, tooltip) = match token_state(context, cx)?
3261    {
3262        TokenState::NoTokensLeft {
3263            max_token_count,
3264            token_count,
3265        } => (
3266            Color::Error,
3267            token_count,
3268            max_token_count,
3269            Some("Token Limit Reached"),
3270        ),
3271        TokenState::HasMoreTokens {
3272            max_token_count,
3273            token_count,
3274            over_warn_threshold,
3275        } => {
3276            let (color, tooltip) = if over_warn_threshold {
3277                (Color::Warning, Some("Token Limit is Close to Exhaustion"))
3278            } else {
3279                (Color::Muted, None)
3280            };
3281            (color, token_count, max_token_count, tooltip)
3282        }
3283    };
3284
3285    Some(
3286        h_flex()
3287            .id("token-count")
3288            .gap_0p5()
3289            .child(
3290                Label::new(humanize_token_count(token_count))
3291                    .size(LabelSize::Small)
3292                    .color(token_count_color),
3293            )
3294            .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
3295            .child(
3296                Label::new(humanize_token_count(max_token_count))
3297                    .size(LabelSize::Small)
3298                    .color(Color::Muted),
3299            )
3300            .when_some(tooltip, |element, tooltip| {
3301                element.tooltip(Tooltip::text(tooltip))
3302            }),
3303    )
3304}
3305
3306impl Render for ContextEditorToolbarItem {
3307    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3308        let left_side = h_flex()
3309            .group("chat-title-group")
3310            .gap_1()
3311            .items_center()
3312            .flex_grow()
3313            .child(
3314                div()
3315                    .w_full()
3316                    .when(self.active_context_editor.is_some(), |left_side| {
3317                        left_side.child(self.model_summary_editor.clone())
3318                    }),
3319            )
3320            .child(
3321                div().visible_on_hover("chat-title-group").child(
3322                    IconButton::new("regenerate-context", IconName::RefreshTitle)
3323                        .shape(ui::IconButtonShape::Square)
3324                        .tooltip(Tooltip::text("Regenerate Title"))
3325                        .on_click(cx.listener(move |_, _, _window, cx| {
3326                            cx.emit(ContextEditorToolbarItemEvent::RegenerateSummary)
3327                        })),
3328                ),
3329            );
3330
3331        let right_side = h_flex()
3332            .gap_2()
3333            // TODO display this in a nicer way, once we have a design for it.
3334            // .children({
3335            //     let project = self
3336            //         .workspace
3337            //         .upgrade()
3338            //         .map(|workspace| workspace.read(cx).project().downgrade());
3339            //
3340            //     let scan_items_remaining = cx.update_global(|db: &mut SemanticDb, cx| {
3341            //         project.and_then(|project| db.remaining_summaries(&project, cx))
3342            //     });
3343            //     scan_items_remaining
3344            //         .map(|remaining_items| format!("Files to scan: {}", remaining_items))
3345            // })
3346            .children(
3347                self.active_context_editor
3348                    .as_ref()
3349                    .and_then(|editor| editor.upgrade())
3350                    .and_then(|editor| render_remaining_tokens(&editor, cx)),
3351            );
3352
3353        h_flex()
3354            .px_0p5()
3355            .size_full()
3356            .gap_2()
3357            .justify_between()
3358            .child(left_side)
3359            .child(right_side)
3360    }
3361}
3362
3363impl ToolbarItemView for ContextEditorToolbarItem {
3364    fn set_active_pane_item(
3365        &mut self,
3366        active_pane_item: Option<&dyn ItemHandle>,
3367        _window: &mut Window,
3368        cx: &mut Context<Self>,
3369    ) -> ToolbarItemLocation {
3370        self.active_context_editor = active_pane_item
3371            .and_then(|item| item.act_as::<ContextEditor>(cx))
3372            .map(|editor| editor.downgrade());
3373        cx.notify();
3374        if self.active_context_editor.is_none() {
3375            ToolbarItemLocation::Hidden
3376        } else {
3377            ToolbarItemLocation::PrimaryRight
3378        }
3379    }
3380
3381    fn pane_focus_update(
3382        &mut self,
3383        _pane_focused: bool,
3384        _window: &mut Window,
3385        cx: &mut Context<Self>,
3386    ) {
3387        cx.notify();
3388    }
3389}
3390
3391impl EventEmitter<ToolbarItemEvent> for ContextEditorToolbarItem {}
3392
3393pub enum ContextEditorToolbarItemEvent {
3394    RegenerateSummary,
3395}
3396impl EventEmitter<ContextEditorToolbarItemEvent> for ContextEditorToolbarItem {}
3397
3398enum PendingSlashCommand {}
3399
3400fn invoked_slash_command_fold_placeholder(
3401    command_id: InvokedSlashCommandId,
3402    context: WeakEntity<AssistantContext>,
3403) -> FoldPlaceholder {
3404    FoldPlaceholder {
3405        constrain_width: false,
3406        merge_adjacent: false,
3407        render: Arc::new(move |fold_id, _, _window, cx| {
3408            let Some(context) = context.upgrade() else {
3409                return Empty.into_any();
3410            };
3411
3412            let Some(command) = context.read(cx).invoked_slash_command(&command_id) else {
3413                return Empty.into_any();
3414            };
3415
3416            h_flex()
3417                .id(fold_id)
3418                .px_1()
3419                .ml_6()
3420                .gap_2()
3421                .bg(cx.theme().colors().surface_background)
3422                .rounded_md()
3423                .child(Label::new(format!("/{}", command.name.clone())))
3424                .map(|parent| match &command.status {
3425                    InvokedSlashCommandStatus::Running(_) => {
3426                        parent.child(Icon::new(IconName::ArrowCircle).with_animation(
3427                            "arrow-circle",
3428                            Animation::new(Duration::from_secs(4)).repeat(),
3429                            |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
3430                        ))
3431                    }
3432                    InvokedSlashCommandStatus::Error(message) => parent.child(
3433                        Label::new(format!("error: {message}"))
3434                            .single_line()
3435                            .color(Color::Error),
3436                    ),
3437                    InvokedSlashCommandStatus::Finished => parent,
3438                })
3439                .into_any_element()
3440        }),
3441        type_tag: Some(TypeId::of::<PendingSlashCommand>()),
3442    }
3443}
3444
3445enum TokenState {
3446    NoTokensLeft {
3447        max_token_count: usize,
3448        token_count: usize,
3449    },
3450    HasMoreTokens {
3451        max_token_count: usize,
3452        token_count: usize,
3453        over_warn_threshold: bool,
3454    },
3455}
3456
3457fn token_state(context: &Entity<AssistantContext>, cx: &App) -> Option<TokenState> {
3458    const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
3459
3460    let model = LanguageModelRegistry::read_global(cx).active_model()?;
3461    let token_count = context.read(cx).token_count()?;
3462    let max_token_count = model.max_token_count();
3463
3464    let remaining_tokens = max_token_count as isize - token_count as isize;
3465    let token_state = if remaining_tokens <= 0 {
3466        TokenState::NoTokensLeft {
3467            max_token_count,
3468            token_count,
3469        }
3470    } else {
3471        let over_warn_threshold =
3472            token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
3473        TokenState::HasMoreTokens {
3474            max_token_count,
3475            token_count,
3476            over_warn_threshold,
3477        }
3478    };
3479    Some(token_state)
3480}
3481
3482fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
3483    let image_size = data
3484        .size(0)
3485        .map(|dimension| Pixels::from(u32::from(dimension)));
3486    let image_ratio = image_size.width / image_size.height;
3487    let bounds_ratio = max_size.width / max_size.height;
3488
3489    if image_size.width > max_size.width || image_size.height > max_size.height {
3490        if bounds_ratio > image_ratio {
3491            size(
3492                image_size.width * (max_size.height / image_size.height),
3493                max_size.height,
3494            )
3495        } else {
3496            size(
3497                max_size.width,
3498                image_size.height * (max_size.width / image_size.width),
3499            )
3500        }
3501    } else {
3502        size(image_size.width, image_size.height)
3503    }
3504}
3505
3506pub enum ConfigurationError {
3507    NoProvider,
3508    ProviderNotAuthenticated,
3509    ProviderPendingTermsAcceptance(Arc<dyn LanguageModelProvider>),
3510}
3511
3512fn configuration_error(cx: &App) -> Option<ConfigurationError> {
3513    let provider = LanguageModelRegistry::read_global(cx).active_provider();
3514    let is_authenticated = provider
3515        .as_ref()
3516        .map_or(false, |provider| provider.is_authenticated(cx));
3517
3518    if provider.is_some() && is_authenticated {
3519        return None;
3520    }
3521
3522    if provider.is_none() {
3523        return Some(ConfigurationError::NoProvider);
3524    }
3525
3526    if !is_authenticated {
3527        return Some(ConfigurationError::ProviderNotAuthenticated);
3528    }
3529
3530    None
3531}
3532
3533pub fn humanize_token_count(count: usize) -> String {
3534    match count {
3535        0..=999 => count.to_string(),
3536        1000..=9999 => {
3537            let thousands = count / 1000;
3538            let hundreds = (count % 1000 + 50) / 100;
3539            if hundreds == 0 {
3540                format!("{}k", thousands)
3541            } else if hundreds == 10 {
3542                format!("{}k", thousands + 1)
3543            } else {
3544                format!("{}.{}k", thousands, hundreds)
3545            }
3546        }
3547        _ => format!("{}k", (count + 500) / 1000),
3548    }
3549}
3550
3551pub fn make_lsp_adapter_delegate(
3552    project: &Entity<Project>,
3553    cx: &mut App,
3554) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
3555    project.update(cx, |project, cx| {
3556        // TODO: Find the right worktree.
3557        let Some(worktree) = project.worktrees(cx).next() else {
3558            return Ok(None::<Arc<dyn LspAdapterDelegate>>);
3559        };
3560        let http_client = project.client().http_client().clone();
3561        project.lsp_store().update(cx, |_, cx| {
3562            Ok(Some(LocalLspAdapterDelegate::new(
3563                project.languages().clone(),
3564                project.environment(),
3565                cx.weak_entity(),
3566                &worktree,
3567                http_client,
3568                project.fs().clone(),
3569                cx,
3570            ) as Arc<dyn LspAdapterDelegate>))
3571        })
3572    })
3573}
3574
3575#[cfg(test)]
3576mod tests {
3577    use super::*;
3578    use gpui::App;
3579    use language::Buffer;
3580    use unindent::Unindent;
3581
3582    #[gpui::test]
3583    fn test_find_code_blocks(cx: &mut App) {
3584        let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
3585
3586        let buffer = cx.new(|cx| {
3587            let text = r#"
3588                line 0
3589                line 1
3590                ```rust
3591                fn main() {}
3592                ```
3593                line 5
3594                line 6
3595                line 7
3596                ```go
3597                func main() {}
3598                ```
3599                line 11
3600                ```
3601                this is plain text code block
3602                ```
3603
3604                ```go
3605                func another() {}
3606                ```
3607                line 19
3608            "#
3609            .unindent();
3610            let mut buffer = Buffer::local(text, cx);
3611            buffer.set_language(Some(markdown.clone()), cx);
3612            buffer
3613        });
3614        let snapshot = buffer.read(cx).snapshot();
3615
3616        let code_blocks = vec![
3617            Point::new(3, 0)..Point::new(4, 0),
3618            Point::new(9, 0)..Point::new(10, 0),
3619            Point::new(13, 0)..Point::new(14, 0),
3620            Point::new(17, 0)..Point::new(18, 0),
3621        ]
3622        .into_iter()
3623        .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
3624        .collect::<Vec<_>>();
3625
3626        let expected_results = vec![
3627            (0, None),
3628            (1, None),
3629            (2, Some(code_blocks[0].clone())),
3630            (3, Some(code_blocks[0].clone())),
3631            (4, Some(code_blocks[0].clone())),
3632            (5, None),
3633            (6, None),
3634            (7, None),
3635            (8, Some(code_blocks[1].clone())),
3636            (9, Some(code_blocks[1].clone())),
3637            (10, Some(code_blocks[1].clone())),
3638            (11, None),
3639            (12, Some(code_blocks[2].clone())),
3640            (13, Some(code_blocks[2].clone())),
3641            (14, Some(code_blocks[2].clone())),
3642            (15, None),
3643            (16, Some(code_blocks[3].clone())),
3644            (17, Some(code_blocks[3].clone())),
3645            (18, Some(code_blocks[3].clone())),
3646            (19, None),
3647        ];
3648
3649        for (row, expected) in expected_results {
3650            let offset = snapshot.point_to_offset(Point::new(row, 0));
3651            let range = find_surrounding_code_block(&snapshot, offset);
3652            assert_eq!(range, expected, "unexpected result on row {:?}", row);
3653        }
3654    }
3655}