context_editor.rs

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