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