context_editor.rs

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