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