context_editor.rs

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