context_editor.rs

   1use anyhow::Result;
   2use assistant_settings::AssistantSettings;
   3use assistant_slash_command::{SlashCommand, SlashCommandOutputSection, SlashCommandWorkingSet};
   4use assistant_slash_commands::{
   5    DefaultSlashCommand, DocsSlashCommand, DocsSlashCommandArgs, FileSlashCommand,
   6    selections_creases,
   7};
   8use client::{proto, zed_urls};
   9use collections::{BTreeSet, HashMap, HashSet, hash_map};
  10use editor::{
  11    Anchor, Editor, EditorEvent, MenuInlineCompletionsPolicy, MultiBuffer, MultiBufferSnapshot,
  12    ProposedChangeLocation, ProposedChangesEditor, RowExt, ToOffset as _, ToPoint,
  13    actions::{MoveToEndOfLine, Newline, ShowCompletions},
  14    display_map::{
  15        BlockContext, BlockId, BlockPlacement, BlockProperties, BlockStyle, Crease, CreaseMetadata,
  16        CustomBlockId, FoldId, RenderBlock, ToDisplayPoint,
  17    },
  18    scroll::Autoscroll,
  19};
  20use editor::{FoldPlaceholder, display_map::CreaseId};
  21use fs::Fs;
  22use futures::FutureExt;
  23use gpui::{
  24    Animation, AnimationExt, AnyElement, AnyView, App, AsyncWindowContext, ClipboardEntry,
  25    ClipboardItem, CursorStyle, Empty, Entity, EventEmitter, FocusHandle, Focusable, FontWeight,
  26    Global, InteractiveElement, IntoElement, ParentElement, Pixels, Render, RenderImage,
  27    SharedString, Size, StatefulInteractiveElement, Styled, Subscription, Task, Transformation,
  28    WeakEntity, actions, div, img, impl_internal_actions, percentage, point, prelude::*,
  29    pulsating_between, size,
  30};
  31use indexed_docs::IndexedDocsStore;
  32use language::{
  33    BufferSnapshot, LspAdapterDelegate, ToOffset,
  34    language_settings::{SoftWrap, all_language_settings},
  35};
  36use language_model::{
  37    LanguageModelImage, LanguageModelProvider, LanguageModelProviderTosView, LanguageModelRegistry,
  38    Role,
  39};
  40use language_model_selector::{
  41    LanguageModelSelector, LanguageModelSelectorPopoverMenu, ToggleModelSelector,
  42};
  43use multi_buffer::MultiBufferRow;
  44use picker::Picker;
  45use project::{Project, Worktree};
  46use project::{ProjectPath, lsp_store::LocalLspAdapterDelegate};
  47use rope::Point;
  48use serde::{Deserialize, Serialize};
  49use settings::{Settings, SettingsStore, update_settings_file};
  50use std::{
  51    any::TypeId,
  52    cmp,
  53    ops::Range,
  54    path::{Path, PathBuf},
  55    sync::Arc,
  56    time::Duration,
  57};
  58use text::SelectionGoal;
  59use ui::{
  60    ButtonLike, Disclosure, ElevationIndex, KeyBinding, PopoverMenuHandle, TintColor, Tooltip,
  61    prelude::*,
  62};
  63use util::{ResultExt, maybe};
  64use workspace::{
  65    CollaboratorId,
  66    searchable::{Direction, SearchableItemHandle},
  67};
  68use workspace::{
  69    Save, Toast, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, Workspace,
  70    item::{self, FollowableItem, Item, ItemHandle},
  71    notifications::NotificationId,
  72    pane::{self, SaveIntent},
  73    searchable::{SearchEvent, SearchableItem},
  74};
  75
  76use crate::{
  77    AssistantContext, AssistantPatch, AssistantPatchStatus, CacheStatus, Content, ContextEvent,
  78    ContextId, InvokedSlashCommandId, InvokedSlashCommandStatus, Message, MessageId,
  79    MessageMetadata, MessageStatus, ParsedSlashCommand, PendingSlashCommandStatus, RequestType,
  80};
  81use crate::{
  82    ThoughtProcessOutputSection, slash_command::SlashCommandCompletionProvider,
  83    slash_command_picker,
  84};
  85
  86actions!(
  87    assistant,
  88    [
  89        Assist,
  90        ConfirmCommand,
  91        CopyCode,
  92        CycleMessageRole,
  93        Edit,
  94        InsertIntoEditor,
  95        QuoteSelection,
  96        Split,
  97    ]
  98);
  99
 100#[derive(PartialEq, Clone)]
 101pub enum InsertDraggedFiles {
 102    ProjectPaths(Vec<ProjectPath>),
 103    ExternalFiles(Vec<PathBuf>),
 104}
 105
 106impl_internal_actions!(assistant, [InsertDraggedFiles]);
 107
 108#[derive(Copy, Clone, Debug, PartialEq)]
 109struct ScrollPosition {
 110    offset_before_cursor: gpui::Point<f32>,
 111    cursor: Anchor,
 112}
 113
 114struct PatchViewState {
 115    crease_id: CreaseId,
 116    editor: Option<PatchEditorState>,
 117    update_task: Option<Task<()>>,
 118}
 119
 120struct PatchEditorState {
 121    editor: WeakEntity<ProposedChangesEditor>,
 122    opened_patch: AssistantPatch,
 123}
 124
 125type MessageHeader = MessageMetadata;
 126
 127#[derive(Clone)]
 128enum AssistError {
 129    FileRequired,
 130    PaymentRequired,
 131    MaxMonthlySpendReached,
 132    Message(SharedString),
 133}
 134
 135pub enum ThoughtProcessStatus {
 136    Pending,
 137    Completed,
 138}
 139
 140pub trait AgentPanelDelegate {
 141    fn active_context_editor(
 142        &self,
 143        workspace: &mut Workspace,
 144        window: &mut Window,
 145        cx: &mut Context<Workspace>,
 146    ) -> Option<Entity<ContextEditor>>;
 147
 148    fn open_saved_context(
 149        &self,
 150        workspace: &mut Workspace,
 151        path: Arc<Path>,
 152        window: &mut Window,
 153        cx: &mut Context<Workspace>,
 154    ) -> Task<Result<()>>;
 155
 156    fn open_remote_context(
 157        &self,
 158        workspace: &mut Workspace,
 159        context_id: ContextId,
 160        window: &mut Window,
 161        cx: &mut Context<Workspace>,
 162    ) -> Task<Result<Entity<ContextEditor>>>;
 163
 164    fn quote_selection(
 165        &self,
 166        workspace: &mut Workspace,
 167        selection_ranges: Vec<Range<Anchor>>,
 168        buffer: Entity<MultiBuffer>,
 169        window: &mut Window,
 170        cx: &mut Context<Workspace>,
 171    );
 172}
 173
 174impl dyn AgentPanelDelegate {
 175    /// Returns the global [`AssistantPanelDelegate`], if it exists.
 176    pub fn try_global(cx: &App) -> Option<Arc<Self>> {
 177        cx.try_global::<GlobalAssistantPanelDelegate>()
 178            .map(|global| global.0.clone())
 179    }
 180
 181    /// Sets the global [`AssistantPanelDelegate`].
 182    pub fn set_global(delegate: Arc<Self>, cx: &mut App) {
 183        cx.set_global(GlobalAssistantPanelDelegate(delegate));
 184    }
 185}
 186
 187struct GlobalAssistantPanelDelegate(Arc<dyn AgentPanelDelegate>);
 188
 189impl Global for GlobalAssistantPanelDelegate {}
 190
 191pub struct ContextEditor {
 192    context: Entity<AssistantContext>,
 193    fs: Arc<dyn Fs>,
 194    slash_commands: Arc<SlashCommandWorkingSet>,
 195    workspace: WeakEntity<Workspace>,
 196    project: Entity<Project>,
 197    lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
 198    editor: Entity<Editor>,
 199    pending_thought_process: Option<(CreaseId, language::Anchor)>,
 200    blocks: HashMap<MessageId, (MessageHeader, CustomBlockId)>,
 201    image_blocks: HashSet<CustomBlockId>,
 202    scroll_position: Option<ScrollPosition>,
 203    remote_id: Option<workspace::ViewId>,
 204    pending_slash_command_creases: HashMap<Range<language::Anchor>, CreaseId>,
 205    invoked_slash_command_creases: HashMap<InvokedSlashCommandId, CreaseId>,
 206    _subscriptions: Vec<Subscription>,
 207    patches: HashMap<Range<language::Anchor>, PatchViewState>,
 208    active_patch: Option<Range<language::Anchor>>,
 209    last_error: Option<AssistError>,
 210    show_accept_terms: bool,
 211    pub(crate) slash_menu_handle:
 212        PopoverMenuHandle<Picker<slash_command_picker::SlashCommandDelegate>>,
 213    // dragged_file_worktrees is used to keep references to worktrees that were added
 214    // when the user drag/dropped an external file onto the context editor. Since
 215    // the worktree is not part of the project panel, it would be dropped as soon as
 216    // the file is opened. In order to keep the worktree alive for the duration of the
 217    // context editor, we keep a reference here.
 218    dragged_file_worktrees: Vec<Entity<Worktree>>,
 219    language_model_selector: Entity<LanguageModelSelector>,
 220    language_model_selector_menu_handle: PopoverMenuHandle<LanguageModelSelector>,
 221}
 222
 223pub const DEFAULT_TAB_TITLE: &str = "New Chat";
 224const MAX_TAB_TITLE_LEN: usize = 16;
 225
 226impl ContextEditor {
 227    pub fn for_context(
 228        context: Entity<AssistantContext>,
 229        fs: Arc<dyn Fs>,
 230        workspace: WeakEntity<Workspace>,
 231        project: Entity<Project>,
 232        lsp_adapter_delegate: Option<Arc<dyn LspAdapterDelegate>>,
 233        window: &mut Window,
 234        cx: &mut Context<Self>,
 235    ) -> Self {
 236        let completion_provider = SlashCommandCompletionProvider::new(
 237            context.read(cx).slash_commands().clone(),
 238            Some(cx.entity().downgrade()),
 239            Some(workspace.clone()),
 240        );
 241
 242        let editor = cx.new(|cx| {
 243            let mut editor =
 244                Editor::for_buffer(context.read(cx).buffer().clone(), None, window, cx);
 245            editor.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(agent_panel_delegate) = <dyn AgentPanelDelegate>::try_global(cx) else {
1669            return;
1670        };
1671        let Some(context_editor_view) =
1672            agent_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 agent_panel_delegate = <dyn AgentPanelDelegate>::try_global(cx)?;
1699            let context_editor_view =
1700                agent_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(agent_panel_delegate) = <dyn AgentPanelDelegate>::try_global(cx) else {
1734            return;
1735        };
1736        let Some(context_editor_view) =
1737            agent_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(agent_panel_delegate) = <dyn AgentPanelDelegate>::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        agent_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    pub fn regenerate_summary(&mut self, cx: &mut Context<Self>) {
2209        self.context
2210            .update(cx, |context, cx| context.summarize(true, cx));
2211    }
2212
2213    fn render_patch_block(
2214        &mut self,
2215        range: Range<text::Anchor>,
2216        max_width: Pixels,
2217        gutter_width: Pixels,
2218        id: BlockId,
2219        selected: bool,
2220        window: &mut Window,
2221        cx: &mut Context<Self>,
2222    ) -> Option<AnyElement> {
2223        let snapshot = self
2224            .editor
2225            .update(cx, |editor, cx| editor.snapshot(window, cx));
2226        let (excerpt_id, _buffer_id, _) = snapshot.buffer_snapshot.as_singleton().unwrap();
2227        let excerpt_id = *excerpt_id;
2228        let anchor = snapshot
2229            .buffer_snapshot
2230            .anchor_in_excerpt(excerpt_id, range.start)
2231            .unwrap();
2232
2233        let theme = cx.theme().clone();
2234        let patch = self.context.read(cx).patch_for_range(&range, cx)?;
2235        let paths = patch
2236            .paths()
2237            .map(|p| SharedString::from(p.to_string()))
2238            .collect::<BTreeSet<_>>();
2239
2240        Some(
2241            v_flex()
2242                .id(id)
2243                .bg(theme.colors().editor_background)
2244                .ml(gutter_width)
2245                .pb_1()
2246                .w(max_width - gutter_width)
2247                .rounded_sm()
2248                .border_1()
2249                .border_color(theme.colors().border_variant)
2250                .overflow_hidden()
2251                .hover(|style| style.border_color(theme.colors().text_accent))
2252                .when(selected, |this| {
2253                    this.border_color(theme.colors().text_accent)
2254                })
2255                .cursor(CursorStyle::PointingHand)
2256                .on_click(cx.listener(move |this, _, window, cx| {
2257                    this.editor.update(cx, |editor, cx| {
2258                        editor.change_selections(None, window, cx, |selections| {
2259                            selections.select_ranges(vec![anchor..anchor]);
2260                        });
2261                    });
2262                    this.focus_active_patch(window, cx);
2263                }))
2264                .child(
2265                    div()
2266                        .px_2()
2267                        .py_1()
2268                        .overflow_hidden()
2269                        .text_ellipsis()
2270                        .border_b_1()
2271                        .border_color(theme.colors().border_variant)
2272                        .bg(theme.colors().element_background)
2273                        .child(
2274                            Label::new(patch.title.clone())
2275                                .size(LabelSize::Small)
2276                                .color(Color::Muted),
2277                        ),
2278                )
2279                .children(paths.into_iter().map(|path| {
2280                    h_flex()
2281                        .px_2()
2282                        .pt_1()
2283                        .gap_1p5()
2284                        .child(Icon::new(IconName::File).size(IconSize::Small))
2285                        .child(Label::new(path).size(LabelSize::Small))
2286                }))
2287                .when(patch.status == AssistantPatchStatus::Pending, |div| {
2288                    div.child(
2289                        h_flex()
2290                            .pt_1()
2291                            .px_2()
2292                            .gap_1()
2293                            .child(
2294                                Icon::new(IconName::ArrowCircle)
2295                                    .size(IconSize::XSmall)
2296                                    .color(Color::Muted)
2297                                    .with_animation(
2298                                        "arrow-circle",
2299                                        Animation::new(Duration::from_secs(2)).repeat(),
2300                                        |icon, delta| {
2301                                            icon.transform(Transformation::rotate(percentage(
2302                                                delta,
2303                                            )))
2304                                        },
2305                                    ),
2306                            )
2307                            .child(
2308                                Label::new("Generating…")
2309                                    .color(Color::Muted)
2310                                    .size(LabelSize::Small)
2311                                    .with_animation(
2312                                        "pulsating-label",
2313                                        Animation::new(Duration::from_secs(2))
2314                                            .repeat()
2315                                            .with_easing(pulsating_between(0.4, 0.8)),
2316                                        |label, delta| label.alpha(delta),
2317                                    ),
2318                            ),
2319                    )
2320                })
2321                .into_any(),
2322        )
2323    }
2324
2325    fn render_notice(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2326        // This was previously gated behind the `zed-pro` feature flag. Since we
2327        // aren't planning to ship that right now, we're just hard-coding this
2328        // value to not show the nudge.
2329        let nudge = Some(false);
2330
2331        if nudge.map_or(false, |value| value) {
2332            Some(
2333                h_flex()
2334                    .p_3()
2335                    .border_b_1()
2336                    .border_color(cx.theme().colors().border_variant)
2337                    .bg(cx.theme().colors().editor_background)
2338                    .justify_between()
2339                    .child(
2340                        h_flex()
2341                            .gap_3()
2342                            .child(Icon::new(IconName::ZedAssistant).color(Color::Accent))
2343                            .child(Label::new("Zed AI is here! Get started by signing in →")),
2344                    )
2345                    .child(
2346                        Button::new("sign-in", "Sign in")
2347                            .size(ButtonSize::Compact)
2348                            .style(ButtonStyle::Filled)
2349                            .on_click(cx.listener(|this, _event, _window, cx| {
2350                                let client = this
2351                                    .workspace
2352                                    .update(cx, |workspace, _| workspace.client().clone())
2353                                    .log_err();
2354
2355                                if let Some(client) = client {
2356                                    cx.spawn(async move |this, cx| {
2357                                        client.authenticate_and_connect(true, cx).await?;
2358                                        this.update(cx, |_, cx| cx.notify())
2359                                    })
2360                                    .detach_and_log_err(cx)
2361                                }
2362                            })),
2363                    )
2364                    .into_any_element(),
2365            )
2366        } else if let Some(configuration_error) = configuration_error(cx) {
2367            let label = match configuration_error {
2368                ConfigurationError::NoProvider => "No LLM provider selected.",
2369                ConfigurationError::ProviderNotAuthenticated => "LLM provider is not configured.",
2370                ConfigurationError::ProviderPendingTermsAcceptance(_) => {
2371                    "LLM provider requires accepting the Terms of Service."
2372                }
2373            };
2374            Some(
2375                h_flex()
2376                    .px_3()
2377                    .py_2()
2378                    .border_b_1()
2379                    .border_color(cx.theme().colors().border_variant)
2380                    .bg(cx.theme().colors().editor_background)
2381                    .justify_between()
2382                    .child(
2383                        h_flex()
2384                            .gap_3()
2385                            .child(
2386                                Icon::new(IconName::Warning)
2387                                    .size(IconSize::Small)
2388                                    .color(Color::Warning),
2389                            )
2390                            .child(Label::new(label)),
2391                    )
2392                    .child(
2393                        Button::new("open-configuration", "Configure Providers")
2394                            .size(ButtonSize::Compact)
2395                            .icon(Some(IconName::SlidersVertical))
2396                            .icon_size(IconSize::Small)
2397                            .icon_position(IconPosition::Start)
2398                            .style(ButtonStyle::Filled)
2399                            .on_click({
2400                                let focus_handle = self.focus_handle(cx).clone();
2401                                move |_event, window, cx| {
2402                                    focus_handle.dispatch_action(
2403                                        &zed_actions::agent::OpenConfiguration,
2404                                        window,
2405                                        cx,
2406                                    );
2407                                }
2408                            }),
2409                    )
2410                    .into_any_element(),
2411            )
2412        } else {
2413            None
2414        }
2415    }
2416
2417    fn render_send_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2418        let focus_handle = self.focus_handle(cx).clone();
2419
2420        let (style, tooltip) = match token_state(&self.context, cx) {
2421            Some(TokenState::NoTokensLeft { .. }) => (
2422                ButtonStyle::Tinted(TintColor::Error),
2423                Some(Tooltip::text("Token limit reached")(window, cx)),
2424            ),
2425            Some(TokenState::HasMoreTokens {
2426                over_warn_threshold,
2427                ..
2428            }) => {
2429                let (style, tooltip) = if over_warn_threshold {
2430                    (
2431                        ButtonStyle::Tinted(TintColor::Warning),
2432                        Some(Tooltip::text("Token limit is close to exhaustion")(
2433                            window, cx,
2434                        )),
2435                    )
2436                } else {
2437                    (ButtonStyle::Filled, None)
2438                };
2439                (style, tooltip)
2440            }
2441            None => (ButtonStyle::Filled, None),
2442        };
2443
2444        let model = LanguageModelRegistry::read_global(cx).default_model();
2445
2446        let has_configuration_error = configuration_error(cx).is_some();
2447        let needs_to_accept_terms = self.show_accept_terms
2448            && model
2449                .as_ref()
2450                .map_or(false, |model| model.provider.must_accept_terms(cx));
2451        let disabled = has_configuration_error || needs_to_accept_terms;
2452
2453        ButtonLike::new("send_button")
2454            .disabled(disabled)
2455            .style(style)
2456            .when_some(tooltip, |button, tooltip| {
2457                button.tooltip(move |_, _| tooltip.clone())
2458            })
2459            .layer(ElevationIndex::ModalSurface)
2460            .child(Label::new(
2461                if AssistantSettings::get_global(cx).are_live_diffs_enabled(cx) {
2462                    "Chat"
2463                } else {
2464                    "Send"
2465                },
2466            ))
2467            .children(
2468                KeyBinding::for_action_in(&Assist, &focus_handle, window, cx)
2469                    .map(|binding| binding.into_any_element()),
2470            )
2471            .on_click(move |_event, window, cx| {
2472                focus_handle.dispatch_action(&Assist, window, cx);
2473            })
2474    }
2475
2476    fn render_edit_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2477        let focus_handle = self.focus_handle(cx).clone();
2478
2479        let (style, tooltip) = match token_state(&self.context, cx) {
2480            Some(TokenState::NoTokensLeft { .. }) => (
2481                ButtonStyle::Tinted(TintColor::Error),
2482                Some(Tooltip::text("Token limit reached")(window, cx)),
2483            ),
2484            Some(TokenState::HasMoreTokens {
2485                over_warn_threshold,
2486                ..
2487            }) => {
2488                let (style, tooltip) = if over_warn_threshold {
2489                    (
2490                        ButtonStyle::Tinted(TintColor::Warning),
2491                        Some(Tooltip::text("Token limit is close to exhaustion")(
2492                            window, cx,
2493                        )),
2494                    )
2495                } else {
2496                    (ButtonStyle::Filled, None)
2497                };
2498                (style, tooltip)
2499            }
2500            None => (ButtonStyle::Filled, None),
2501        };
2502
2503        let provider = LanguageModelRegistry::read_global(cx)
2504            .default_model()
2505            .map(|default| default.provider);
2506
2507        let has_configuration_error = configuration_error(cx).is_some();
2508        let needs_to_accept_terms = self.show_accept_terms
2509            && provider
2510                .as_ref()
2511                .map_or(false, |provider| provider.must_accept_terms(cx));
2512        let disabled = has_configuration_error || needs_to_accept_terms;
2513
2514        ButtonLike::new("edit_button")
2515            .disabled(disabled)
2516            .style(style)
2517            .when_some(tooltip, |button, tooltip| {
2518                button.tooltip(move |_, _| tooltip.clone())
2519            })
2520            .layer(ElevationIndex::ModalSurface)
2521            .child(Label::new("Suggest Edits"))
2522            .children(
2523                KeyBinding::for_action_in(&Edit, &focus_handle, window, cx)
2524                    .map(|binding| binding.into_any_element()),
2525            )
2526            .on_click(move |_event, window, cx| {
2527                focus_handle.dispatch_action(&Edit, window, cx);
2528            })
2529    }
2530
2531    fn render_inject_context_menu(&self, cx: &mut Context<Self>) -> impl IntoElement {
2532        slash_command_picker::SlashCommandSelector::new(
2533            self.slash_commands.clone(),
2534            cx.entity().downgrade(),
2535            IconButton::new("trigger", IconName::Plus)
2536                .icon_size(IconSize::Small)
2537                .icon_color(Color::Muted),
2538            move |window, cx| {
2539                Tooltip::with_meta(
2540                    "Add Context",
2541                    None,
2542                    "Type / to insert via keyboard",
2543                    window,
2544                    cx,
2545                )
2546            },
2547        )
2548    }
2549
2550    fn render_language_model_selector(&self, cx: &mut Context<Self>) -> impl IntoElement {
2551        let active_model = LanguageModelRegistry::read_global(cx)
2552            .default_model()
2553            .map(|default| default.model);
2554        let focus_handle = self.editor().focus_handle(cx).clone();
2555        let model_name = match active_model {
2556            Some(model) => model.name().0,
2557            None => SharedString::from("No model selected"),
2558        };
2559
2560        LanguageModelSelectorPopoverMenu::new(
2561            self.language_model_selector.clone(),
2562            ButtonLike::new("active-model")
2563                .style(ButtonStyle::Subtle)
2564                .child(
2565                    h_flex()
2566                        .gap_0p5()
2567                        .child(
2568                            Label::new(model_name)
2569                                .size(LabelSize::Small)
2570                                .color(Color::Muted),
2571                        )
2572                        .child(
2573                            Icon::new(IconName::ChevronDown)
2574                                .color(Color::Muted)
2575                                .size(IconSize::XSmall),
2576                        ),
2577                ),
2578            move |window, cx| {
2579                Tooltip::for_action_in(
2580                    "Change Model",
2581                    &ToggleModelSelector,
2582                    &focus_handle,
2583                    window,
2584                    cx,
2585                )
2586            },
2587            gpui::Corner::BottomLeft,
2588        )
2589        .with_handle(self.language_model_selector_menu_handle.clone())
2590    }
2591
2592    fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2593        let last_error = self.last_error.as_ref()?;
2594
2595        Some(
2596            div()
2597                .absolute()
2598                .right_3()
2599                .bottom_12()
2600                .max_w_96()
2601                .py_2()
2602                .px_3()
2603                .elevation_2(cx)
2604                .occlude()
2605                .child(match last_error {
2606                    AssistError::FileRequired => self.render_file_required_error(cx),
2607                    AssistError::PaymentRequired => self.render_payment_required_error(cx),
2608                    AssistError::MaxMonthlySpendReached => {
2609                        self.render_max_monthly_spend_reached_error(cx)
2610                    }
2611                    AssistError::Message(error_message) => {
2612                        self.render_assist_error(error_message, cx)
2613                    }
2614                })
2615                .into_any(),
2616        )
2617    }
2618
2619    fn render_file_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2620        v_flex()
2621            .gap_0p5()
2622            .child(
2623                h_flex()
2624                    .gap_1p5()
2625                    .items_center()
2626                    .child(Icon::new(IconName::Warning).color(Color::Warning))
2627                    .child(
2628                        Label::new("Suggest Edits needs a file to edit").weight(FontWeight::MEDIUM),
2629                    ),
2630            )
2631            .child(
2632                div()
2633                    .id("error-message")
2634                    .max_h_24()
2635                    .overflow_y_scroll()
2636                    .child(Label::new(
2637                        "To include files, type /file or /tab in your prompt.",
2638                    )),
2639            )
2640            .child(
2641                h_flex()
2642                    .justify_end()
2643                    .mt_1()
2644                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2645                        |this, _, _window, cx| {
2646                            this.last_error = None;
2647                            cx.notify();
2648                        },
2649                    ))),
2650            )
2651            .into_any()
2652    }
2653
2654    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2655        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.";
2656
2657        v_flex()
2658            .gap_0p5()
2659            .child(
2660                h_flex()
2661                    .gap_1p5()
2662                    .items_center()
2663                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2664                    .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2665            )
2666            .child(
2667                div()
2668                    .id("error-message")
2669                    .max_h_24()
2670                    .overflow_y_scroll()
2671                    .child(Label::new(ERROR_MESSAGE)),
2672            )
2673            .child(
2674                h_flex()
2675                    .justify_end()
2676                    .mt_1()
2677                    .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
2678                        |this, _, _window, cx| {
2679                            this.last_error = None;
2680                            cx.open_url(&zed_urls::account_url(cx));
2681                            cx.notify();
2682                        },
2683                    )))
2684                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2685                        |this, _, _window, cx| {
2686                            this.last_error = None;
2687                            cx.notify();
2688                        },
2689                    ))),
2690            )
2691            .into_any()
2692    }
2693
2694    fn render_max_monthly_spend_reached_error(&self, cx: &mut Context<Self>) -> AnyElement {
2695        const ERROR_MESSAGE: &str = "You have reached your maximum monthly spend. Increase your spend limit to continue using Zed LLMs.";
2696
2697        v_flex()
2698            .gap_0p5()
2699            .child(
2700                h_flex()
2701                    .gap_1p5()
2702                    .items_center()
2703                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2704                    .child(Label::new("Max Monthly Spend Reached").weight(FontWeight::MEDIUM)),
2705            )
2706            .child(
2707                div()
2708                    .id("error-message")
2709                    .max_h_24()
2710                    .overflow_y_scroll()
2711                    .child(Label::new(ERROR_MESSAGE)),
2712            )
2713            .child(
2714                h_flex()
2715                    .justify_end()
2716                    .mt_1()
2717                    .child(
2718                        Button::new("subscribe", "Update Monthly Spend Limit").on_click(
2719                            cx.listener(|this, _, _window, cx| {
2720                                this.last_error = None;
2721                                cx.open_url(&zed_urls::account_url(cx));
2722                                cx.notify();
2723                            }),
2724                        ),
2725                    )
2726                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2727                        |this, _, _window, cx| {
2728                            this.last_error = None;
2729                            cx.notify();
2730                        },
2731                    ))),
2732            )
2733            .into_any()
2734    }
2735
2736    fn render_assist_error(
2737        &self,
2738        error_message: &SharedString,
2739        cx: &mut Context<Self>,
2740    ) -> AnyElement {
2741        v_flex()
2742            .gap_0p5()
2743            .child(
2744                h_flex()
2745                    .gap_1p5()
2746                    .items_center()
2747                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2748                    .child(
2749                        Label::new("Error interacting with language model")
2750                            .weight(FontWeight::MEDIUM),
2751                    ),
2752            )
2753            .child(
2754                div()
2755                    .id("error-message")
2756                    .max_h_32()
2757                    .overflow_y_scroll()
2758                    .child(Label::new(error_message.clone())),
2759            )
2760            .child(
2761                h_flex()
2762                    .justify_end()
2763                    .mt_1()
2764                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2765                        |this, _, _window, cx| {
2766                            this.last_error = None;
2767                            cx.notify();
2768                        },
2769                    ))),
2770            )
2771            .into_any()
2772    }
2773}
2774
2775/// Returns the contents of the *outermost* fenced code block that contains the given offset.
2776fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
2777    const CODE_BLOCK_NODE: &'static str = "fenced_code_block";
2778    const CODE_BLOCK_CONTENT: &'static str = "code_fence_content";
2779
2780    let layer = snapshot.syntax_layers().next()?;
2781
2782    let root_node = layer.node();
2783    let mut cursor = root_node.walk();
2784
2785    // Go to the first child for the given offset
2786    while cursor.goto_first_child_for_byte(offset).is_some() {
2787        // If we're at the end of the node, go to the next one.
2788        // Example: if you have a fenced-code-block, and you're on the start of the line
2789        // right after the closing ```, you want to skip the fenced-code-block and
2790        // go to the next sibling.
2791        if cursor.node().end_byte() == offset {
2792            cursor.goto_next_sibling();
2793        }
2794
2795        if cursor.node().start_byte() > offset {
2796            break;
2797        }
2798
2799        // We found the fenced code block.
2800        if cursor.node().kind() == CODE_BLOCK_NODE {
2801            // Now we need to find the child node that contains the code.
2802            cursor.goto_first_child();
2803            loop {
2804                if cursor.node().kind() == CODE_BLOCK_CONTENT {
2805                    return Some(cursor.node().byte_range());
2806                }
2807                if !cursor.goto_next_sibling() {
2808                    break;
2809                }
2810            }
2811        }
2812    }
2813
2814    None
2815}
2816
2817fn render_thought_process_fold_icon_button(
2818    editor: WeakEntity<Editor>,
2819    status: ThoughtProcessStatus,
2820) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2821    Arc::new(move |fold_id, fold_range, _cx| {
2822        let editor = editor.clone();
2823
2824        let button = ButtonLike::new(fold_id).layer(ElevationIndex::ElevatedSurface);
2825        let button = match status {
2826            ThoughtProcessStatus::Pending => button
2827                .child(
2828                    Icon::new(IconName::LightBulb)
2829                        .size(IconSize::Small)
2830                        .color(Color::Muted),
2831                )
2832                .child(
2833                    Label::new("Thinking…").color(Color::Muted).with_animation(
2834                        "pulsating-label",
2835                        Animation::new(Duration::from_secs(2))
2836                            .repeat()
2837                            .with_easing(pulsating_between(0.4, 0.8)),
2838                        |label, delta| label.alpha(delta),
2839                    ),
2840                ),
2841            ThoughtProcessStatus::Completed => button
2842                .style(ButtonStyle::Filled)
2843                .child(Icon::new(IconName::LightBulb).size(IconSize::Small))
2844                .child(Label::new("Thought Process").single_line()),
2845        };
2846
2847        button
2848            .on_click(move |_, window, cx| {
2849                editor
2850                    .update(cx, |editor, cx| {
2851                        let buffer_start = fold_range
2852                            .start
2853                            .to_point(&editor.buffer().read(cx).read(cx));
2854                        let buffer_row = MultiBufferRow(buffer_start.row);
2855                        editor.unfold_at(buffer_row, window, cx);
2856                    })
2857                    .ok();
2858            })
2859            .into_any_element()
2860    })
2861}
2862
2863fn render_fold_icon_button(
2864    editor: WeakEntity<Editor>,
2865    icon_path: SharedString,
2866    label: SharedString,
2867) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2868    Arc::new(move |fold_id, fold_range, _cx| {
2869        let editor = editor.clone();
2870        ButtonLike::new(fold_id)
2871            .style(ButtonStyle::Filled)
2872            .layer(ElevationIndex::ElevatedSurface)
2873            .child(Icon::from_path(icon_path.clone()))
2874            .child(Label::new(label.clone()).single_line())
2875            .on_click(move |_, window, cx| {
2876                editor
2877                    .update(cx, |editor, cx| {
2878                        let buffer_start = fold_range
2879                            .start
2880                            .to_point(&editor.buffer().read(cx).read(cx));
2881                        let buffer_row = MultiBufferRow(buffer_start.row);
2882                        editor.unfold_at(buffer_row, window, cx);
2883                    })
2884                    .ok();
2885            })
2886            .into_any_element()
2887    })
2888}
2889
2890type ToggleFold = Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>;
2891
2892fn render_slash_command_output_toggle(
2893    row: MultiBufferRow,
2894    is_folded: bool,
2895    fold: ToggleFold,
2896    _window: &mut Window,
2897    _cx: &mut App,
2898) -> AnyElement {
2899    Disclosure::new(
2900        ("slash-command-output-fold-indicator", row.0 as u64),
2901        !is_folded,
2902    )
2903    .toggle_state(is_folded)
2904    .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2905    .into_any_element()
2906}
2907
2908pub fn fold_toggle(
2909    name: &'static str,
2910) -> impl Fn(
2911    MultiBufferRow,
2912    bool,
2913    Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
2914    &mut Window,
2915    &mut App,
2916) -> AnyElement {
2917    move |row, is_folded, fold, _window, _cx| {
2918        Disclosure::new((name, row.0 as u64), !is_folded)
2919            .toggle_state(is_folded)
2920            .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2921            .into_any_element()
2922    }
2923}
2924
2925fn quote_selection_fold_placeholder(title: String, editor: WeakEntity<Editor>) -> FoldPlaceholder {
2926    FoldPlaceholder {
2927        render: Arc::new({
2928            move |fold_id, fold_range, _cx| {
2929                let editor = editor.clone();
2930                ButtonLike::new(fold_id)
2931                    .style(ButtonStyle::Filled)
2932                    .layer(ElevationIndex::ElevatedSurface)
2933                    .child(Icon::new(IconName::TextSnippet))
2934                    .child(Label::new(title.clone()).single_line())
2935                    .on_click(move |_, window, cx| {
2936                        editor
2937                            .update(cx, |editor, cx| {
2938                                let buffer_start = fold_range
2939                                    .start
2940                                    .to_point(&editor.buffer().read(cx).read(cx));
2941                                let buffer_row = MultiBufferRow(buffer_start.row);
2942                                editor.unfold_at(buffer_row, window, cx);
2943                            })
2944                            .ok();
2945                    })
2946                    .into_any_element()
2947            }
2948        }),
2949        merge_adjacent: false,
2950        ..Default::default()
2951    }
2952}
2953
2954fn render_quote_selection_output_toggle(
2955    row: MultiBufferRow,
2956    is_folded: bool,
2957    fold: ToggleFold,
2958    _window: &mut Window,
2959    _cx: &mut App,
2960) -> AnyElement {
2961    Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
2962        .toggle_state(is_folded)
2963        .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2964        .into_any_element()
2965}
2966
2967fn render_pending_slash_command_gutter_decoration(
2968    row: MultiBufferRow,
2969    status: &PendingSlashCommandStatus,
2970    confirm_command: Arc<dyn Fn(&mut Window, &mut App)>,
2971) -> AnyElement {
2972    let mut icon = IconButton::new(
2973        ("slash-command-gutter-decoration", row.0),
2974        ui::IconName::TriangleRight,
2975    )
2976    .on_click(move |_e, window, cx| confirm_command(window, cx))
2977    .icon_size(ui::IconSize::Small)
2978    .size(ui::ButtonSize::None);
2979
2980    match status {
2981        PendingSlashCommandStatus::Idle => {
2982            icon = icon.icon_color(Color::Muted);
2983        }
2984        PendingSlashCommandStatus::Running { .. } => {
2985            icon = icon.toggle_state(true);
2986        }
2987        PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
2988    }
2989
2990    icon.into_any_element()
2991}
2992
2993fn render_docs_slash_command_trailer(
2994    row: MultiBufferRow,
2995    command: ParsedSlashCommand,
2996    cx: &mut App,
2997) -> AnyElement {
2998    if command.arguments.is_empty() {
2999        return Empty.into_any();
3000    }
3001    let args = DocsSlashCommandArgs::parse(&command.arguments);
3002
3003    let Some(store) = args
3004        .provider()
3005        .and_then(|provider| IndexedDocsStore::try_global(provider, cx).ok())
3006    else {
3007        return Empty.into_any();
3008    };
3009
3010    let Some(package) = args.package() else {
3011        return Empty.into_any();
3012    };
3013
3014    let mut children = Vec::new();
3015
3016    if store.is_indexing(&package) {
3017        children.push(
3018            div()
3019                .id(("crates-being-indexed", row.0))
3020                .child(Icon::new(IconName::ArrowCircle).with_animation(
3021                    "arrow-circle",
3022                    Animation::new(Duration::from_secs(4)).repeat(),
3023                    |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
3024                ))
3025                .tooltip({
3026                    let package = package.clone();
3027                    Tooltip::text(format!("Indexing {package}"))
3028                })
3029                .into_any_element(),
3030        );
3031    }
3032
3033    if let Some(latest_error) = store.latest_error_for_package(&package) {
3034        children.push(
3035            div()
3036                .id(("latest-error", row.0))
3037                .child(
3038                    Icon::new(IconName::Warning)
3039                        .size(IconSize::Small)
3040                        .color(Color::Warning),
3041                )
3042                .tooltip(Tooltip::text(format!("Failed to index: {latest_error}")))
3043                .into_any_element(),
3044        )
3045    }
3046
3047    let is_indexing = store.is_indexing(&package);
3048    let latest_error = store.latest_error_for_package(&package);
3049
3050    if !is_indexing && latest_error.is_none() {
3051        return Empty.into_any();
3052    }
3053
3054    h_flex().gap_2().children(children).into_any_element()
3055}
3056
3057#[derive(Debug, Clone, Serialize, Deserialize)]
3058struct CopyMetadata {
3059    creases: Vec<SelectedCreaseMetadata>,
3060}
3061
3062#[derive(Debug, Clone, Serialize, Deserialize)]
3063struct SelectedCreaseMetadata {
3064    range_relative_to_selection: Range<usize>,
3065    crease: CreaseMetadata,
3066}
3067
3068impl EventEmitter<EditorEvent> for ContextEditor {}
3069impl EventEmitter<SearchEvent> for ContextEditor {}
3070
3071impl Render for ContextEditor {
3072    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3073        let provider = LanguageModelRegistry::read_global(cx)
3074            .default_model()
3075            .map(|default| default.provider);
3076        let accept_terms = if self.show_accept_terms {
3077            provider.as_ref().and_then(|provider| {
3078                provider.render_accept_terms(LanguageModelProviderTosView::PromptEditorPopup, cx)
3079            })
3080        } else {
3081            None
3082        };
3083
3084        let language_model_selector = self.language_model_selector_menu_handle.clone();
3085        v_flex()
3086            .key_context("ContextEditor")
3087            .capture_action(cx.listener(ContextEditor::cancel))
3088            .capture_action(cx.listener(ContextEditor::save))
3089            .capture_action(cx.listener(ContextEditor::copy))
3090            .capture_action(cx.listener(ContextEditor::cut))
3091            .capture_action(cx.listener(ContextEditor::paste))
3092            .capture_action(cx.listener(ContextEditor::cycle_message_role))
3093            .capture_action(cx.listener(ContextEditor::confirm_command))
3094            .on_action(cx.listener(ContextEditor::edit))
3095            .on_action(cx.listener(ContextEditor::assist))
3096            .on_action(cx.listener(ContextEditor::split))
3097            .on_action(move |_: &ToggleModelSelector, window, cx| {
3098                language_model_selector.toggle(window, cx);
3099            })
3100            .size_full()
3101            .children(self.render_notice(cx))
3102            .child(
3103                div()
3104                    .flex_grow()
3105                    .bg(cx.theme().colors().editor_background)
3106                    .child(self.editor.clone()),
3107            )
3108            .when_some(accept_terms, |this, element| {
3109                this.child(
3110                    div()
3111                        .absolute()
3112                        .right_3()
3113                        .bottom_12()
3114                        .max_w_96()
3115                        .py_2()
3116                        .px_3()
3117                        .elevation_2(cx)
3118                        .bg(cx.theme().colors().surface_background)
3119                        .occlude()
3120                        .child(element),
3121                )
3122            })
3123            .children(self.render_last_error(cx))
3124            .child(
3125                h_flex().w_full().relative().child(
3126                    h_flex()
3127                        .p_2()
3128                        .w_full()
3129                        .border_t_1()
3130                        .border_color(cx.theme().colors().border_variant)
3131                        .bg(cx.theme().colors().editor_background)
3132                        .child(
3133                            h_flex()
3134                                .gap_1()
3135                                .child(self.render_inject_context_menu(cx))
3136                                .child(ui::Divider::vertical())
3137                                .child(
3138                                    div()
3139                                        .pl_0p5()
3140                                        .child(self.render_language_model_selector(cx)),
3141                                ),
3142                        )
3143                        .child(
3144                            h_flex()
3145                                .w_full()
3146                                .justify_end()
3147                                .when(
3148                                    AssistantSettings::get_global(cx).are_live_diffs_enabled(cx),
3149                                    |buttons| {
3150                                        buttons
3151                                            .items_center()
3152                                            .gap_1p5()
3153                                            .child(self.render_edit_button(window, cx))
3154                                            .child(
3155                                                Label::new("or")
3156                                                    .size(LabelSize::Small)
3157                                                    .color(Color::Muted),
3158                                            )
3159                                    },
3160                                )
3161                                .child(self.render_send_button(window, cx)),
3162                        ),
3163                ),
3164            )
3165    }
3166}
3167
3168impl Focusable for ContextEditor {
3169    fn focus_handle(&self, cx: &App) -> FocusHandle {
3170        self.editor.focus_handle(cx)
3171    }
3172}
3173
3174impl Item for ContextEditor {
3175    type Event = editor::EditorEvent;
3176
3177    fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
3178        util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into()
3179    }
3180
3181    fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
3182        match event {
3183            EditorEvent::Edited { .. } => {
3184                f(item::ItemEvent::Edit);
3185            }
3186            EditorEvent::TitleChanged => {
3187                f(item::ItemEvent::UpdateTab);
3188            }
3189            _ => {}
3190        }
3191    }
3192
3193    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
3194        Some(self.title(cx).to_string().into())
3195    }
3196
3197    fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
3198        Some(Box::new(handle.clone()))
3199    }
3200
3201    fn set_nav_history(
3202        &mut self,
3203        nav_history: pane::ItemNavHistory,
3204        window: &mut Window,
3205        cx: &mut Context<Self>,
3206    ) {
3207        self.editor.update(cx, |editor, cx| {
3208            Item::set_nav_history(editor, nav_history, window, cx)
3209        })
3210    }
3211
3212    fn navigate(
3213        &mut self,
3214        data: Box<dyn std::any::Any>,
3215        window: &mut Window,
3216        cx: &mut Context<Self>,
3217    ) -> bool {
3218        self.editor
3219            .update(cx, |editor, cx| Item::navigate(editor, data, window, cx))
3220    }
3221
3222    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3223        self.editor
3224            .update(cx, |editor, cx| Item::deactivated(editor, window, cx))
3225    }
3226
3227    fn act_as_type<'a>(
3228        &'a self,
3229        type_id: TypeId,
3230        self_handle: &'a Entity<Self>,
3231        _: &'a App,
3232    ) -> Option<AnyView> {
3233        if type_id == TypeId::of::<Self>() {
3234            Some(self_handle.to_any())
3235        } else if type_id == TypeId::of::<Editor>() {
3236            Some(self.editor.to_any())
3237        } else {
3238            None
3239        }
3240    }
3241
3242    fn include_in_nav_history() -> bool {
3243        false
3244    }
3245}
3246
3247impl SearchableItem for ContextEditor {
3248    type Match = <Editor as SearchableItem>::Match;
3249
3250    fn clear_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
3251        self.editor.update(cx, |editor, cx| {
3252            editor.clear_matches(window, cx);
3253        });
3254    }
3255
3256    fn update_matches(
3257        &mut self,
3258        matches: &[Self::Match],
3259        window: &mut Window,
3260        cx: &mut Context<Self>,
3261    ) {
3262        self.editor
3263            .update(cx, |editor, cx| editor.update_matches(matches, window, cx));
3264    }
3265
3266    fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
3267        self.editor
3268            .update(cx, |editor, cx| editor.query_suggestion(window, cx))
3269    }
3270
3271    fn activate_match(
3272        &mut self,
3273        index: usize,
3274        matches: &[Self::Match],
3275        window: &mut Window,
3276        cx: &mut Context<Self>,
3277    ) {
3278        self.editor.update(cx, |editor, cx| {
3279            editor.activate_match(index, matches, window, cx);
3280        });
3281    }
3282
3283    fn select_matches(
3284        &mut self,
3285        matches: &[Self::Match],
3286        window: &mut Window,
3287        cx: &mut Context<Self>,
3288    ) {
3289        self.editor
3290            .update(cx, |editor, cx| editor.select_matches(matches, window, cx));
3291    }
3292
3293    fn replace(
3294        &mut self,
3295        identifier: &Self::Match,
3296        query: &project::search::SearchQuery,
3297        window: &mut Window,
3298        cx: &mut Context<Self>,
3299    ) {
3300        self.editor.update(cx, |editor, cx| {
3301            editor.replace(identifier, query, window, cx)
3302        });
3303    }
3304
3305    fn find_matches(
3306        &mut self,
3307        query: Arc<project::search::SearchQuery>,
3308        window: &mut Window,
3309        cx: &mut Context<Self>,
3310    ) -> Task<Vec<Self::Match>> {
3311        self.editor
3312            .update(cx, |editor, cx| editor.find_matches(query, window, cx))
3313    }
3314
3315    fn active_match_index(
3316        &mut self,
3317        direction: Direction,
3318        matches: &[Self::Match],
3319        window: &mut Window,
3320        cx: &mut Context<Self>,
3321    ) -> Option<usize> {
3322        self.editor.update(cx, |editor, cx| {
3323            editor.active_match_index(direction, matches, window, cx)
3324        })
3325    }
3326}
3327
3328impl FollowableItem for ContextEditor {
3329    fn remote_id(&self) -> Option<workspace::ViewId> {
3330        self.remote_id
3331    }
3332
3333    fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant> {
3334        let context = self.context.read(cx);
3335        Some(proto::view::Variant::ContextEditor(
3336            proto::view::ContextEditor {
3337                context_id: context.id().to_proto(),
3338                editor: if let Some(proto::view::Variant::Editor(proto)) =
3339                    self.editor.read(cx).to_state_proto(window, cx)
3340                {
3341                    Some(proto)
3342                } else {
3343                    None
3344                },
3345            },
3346        ))
3347    }
3348
3349    fn from_state_proto(
3350        workspace: Entity<Workspace>,
3351        id: workspace::ViewId,
3352        state: &mut Option<proto::view::Variant>,
3353        window: &mut Window,
3354        cx: &mut App,
3355    ) -> Option<Task<Result<Entity<Self>>>> {
3356        let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
3357            return None;
3358        };
3359        let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
3360            unreachable!()
3361        };
3362
3363        let context_id = ContextId::from_proto(state.context_id);
3364        let editor_state = state.editor?;
3365
3366        let project = workspace.read(cx).project().clone();
3367        let agent_panel_delegate = <dyn AgentPanelDelegate>::try_global(cx)?;
3368
3369        let context_editor_task = workspace.update(cx, |workspace, cx| {
3370            agent_panel_delegate.open_remote_context(workspace, context_id, window, cx)
3371        });
3372
3373        Some(window.spawn(cx, async move |cx| {
3374            let context_editor = context_editor_task.await?;
3375            context_editor
3376                .update_in(cx, |context_editor, window, cx| {
3377                    context_editor.remote_id = Some(id);
3378                    context_editor.editor.update(cx, |editor, cx| {
3379                        editor.apply_update_proto(
3380                            &project,
3381                            proto::update_view::Variant::Editor(proto::update_view::Editor {
3382                                selections: editor_state.selections,
3383                                pending_selection: editor_state.pending_selection,
3384                                scroll_top_anchor: editor_state.scroll_top_anchor,
3385                                scroll_x: editor_state.scroll_y,
3386                                scroll_y: editor_state.scroll_y,
3387                                ..Default::default()
3388                            }),
3389                            window,
3390                            cx,
3391                        )
3392                    })
3393                })?
3394                .await?;
3395            Ok(context_editor)
3396        }))
3397    }
3398
3399    fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
3400        Editor::to_follow_event(event)
3401    }
3402
3403    fn add_event_to_update_proto(
3404        &self,
3405        event: &Self::Event,
3406        update: &mut Option<proto::update_view::Variant>,
3407        window: &Window,
3408        cx: &App,
3409    ) -> bool {
3410        self.editor
3411            .read(cx)
3412            .add_event_to_update_proto(event, update, window, cx)
3413    }
3414
3415    fn apply_update_proto(
3416        &mut self,
3417        project: &Entity<Project>,
3418        message: proto::update_view::Variant,
3419        window: &mut Window,
3420        cx: &mut Context<Self>,
3421    ) -> Task<Result<()>> {
3422        self.editor.update(cx, |editor, cx| {
3423            editor.apply_update_proto(project, message, window, cx)
3424        })
3425    }
3426
3427    fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
3428        true
3429    }
3430
3431    fn set_leader_id(
3432        &mut self,
3433        leader_id: Option<CollaboratorId>,
3434        window: &mut Window,
3435        cx: &mut Context<Self>,
3436    ) {
3437        self.editor
3438            .update(cx, |editor, cx| editor.set_leader_id(leader_id, window, cx))
3439    }
3440
3441    fn dedup(&self, existing: &Self, _window: &Window, cx: &App) -> Option<item::Dedup> {
3442        if existing.context.read(cx).id() == self.context.read(cx).id() {
3443            Some(item::Dedup::KeepExisting)
3444        } else {
3445            None
3446        }
3447    }
3448}
3449
3450pub struct ContextEditorToolbarItem {
3451    active_context_editor: Option<WeakEntity<ContextEditor>>,
3452    model_summary_editor: Entity<Editor>,
3453}
3454
3455impl ContextEditorToolbarItem {
3456    pub fn new(model_summary_editor: Entity<Editor>) -> Self {
3457        Self {
3458            active_context_editor: None,
3459            model_summary_editor,
3460        }
3461    }
3462}
3463
3464pub fn render_remaining_tokens(
3465    context_editor: &Entity<ContextEditor>,
3466    cx: &App,
3467) -> Option<impl IntoElement + use<>> {
3468    let context = &context_editor.read(cx).context;
3469
3470    let (token_count_color, token_count, max_token_count, tooltip) = match token_state(context, cx)?
3471    {
3472        TokenState::NoTokensLeft {
3473            max_token_count,
3474            token_count,
3475        } => (
3476            Color::Error,
3477            token_count,
3478            max_token_count,
3479            Some("Token Limit Reached"),
3480        ),
3481        TokenState::HasMoreTokens {
3482            max_token_count,
3483            token_count,
3484            over_warn_threshold,
3485        } => {
3486            let (color, tooltip) = if over_warn_threshold {
3487                (Color::Warning, Some("Token Limit is Close to Exhaustion"))
3488            } else {
3489                (Color::Muted, None)
3490            };
3491            (color, token_count, max_token_count, tooltip)
3492        }
3493    };
3494
3495    Some(
3496        h_flex()
3497            .id("token-count")
3498            .gap_0p5()
3499            .child(
3500                Label::new(humanize_token_count(token_count))
3501                    .size(LabelSize::Small)
3502                    .color(token_count_color),
3503            )
3504            .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
3505            .child(
3506                Label::new(humanize_token_count(max_token_count))
3507                    .size(LabelSize::Small)
3508                    .color(Color::Muted),
3509            )
3510            .when_some(tooltip, |element, tooltip| {
3511                element.tooltip(Tooltip::text(tooltip))
3512            }),
3513    )
3514}
3515
3516impl Render for ContextEditorToolbarItem {
3517    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
3518        let left_side = h_flex()
3519            .group("chat-title-group")
3520            .gap_1()
3521            .items_center()
3522            .flex_grow()
3523            .child(
3524                div()
3525                    .w_full()
3526                    .when(self.active_context_editor.is_some(), |left_side| {
3527                        left_side.child(self.model_summary_editor.clone())
3528                    }),
3529            )
3530            .child(
3531                div().visible_on_hover("chat-title-group").child(
3532                    IconButton::new("regenerate-context", IconName::RefreshTitle)
3533                        .shape(ui::IconButtonShape::Square)
3534                        .tooltip(Tooltip::text("Regenerate Title"))
3535                        .on_click(cx.listener(move |_, _, _window, cx| {
3536                            cx.emit(ContextEditorToolbarItemEvent::RegenerateSummary)
3537                        })),
3538                ),
3539            );
3540
3541        let right_side = h_flex()
3542            .gap_2()
3543            // TODO display this in a nicer way, once we have a design for it.
3544            // .children({
3545            //     let project = self
3546            //         .workspace
3547            //         .upgrade()
3548            //         .map(|workspace| workspace.read(cx).project().downgrade());
3549            //
3550            //     let scan_items_remaining = cx.update_global(|db: &mut SemanticDb, cx| {
3551            //         project.and_then(|project| db.remaining_summaries(&project, cx))
3552            //     });
3553            //     scan_items_remaining
3554            //         .map(|remaining_items| format!("Files to scan: {}", remaining_items))
3555            // })
3556            .children(
3557                self.active_context_editor
3558                    .as_ref()
3559                    .and_then(|editor| editor.upgrade())
3560                    .and_then(|editor| render_remaining_tokens(&editor, cx)),
3561            );
3562
3563        h_flex()
3564            .px_0p5()
3565            .size_full()
3566            .gap_2()
3567            .justify_between()
3568            .child(left_side)
3569            .child(right_side)
3570    }
3571}
3572
3573impl ToolbarItemView for ContextEditorToolbarItem {
3574    fn set_active_pane_item(
3575        &mut self,
3576        active_pane_item: Option<&dyn ItemHandle>,
3577        _window: &mut Window,
3578        cx: &mut Context<Self>,
3579    ) -> ToolbarItemLocation {
3580        self.active_context_editor = active_pane_item
3581            .and_then(|item| item.act_as::<ContextEditor>(cx))
3582            .map(|editor| editor.downgrade());
3583        cx.notify();
3584        if self.active_context_editor.is_none() {
3585            ToolbarItemLocation::Hidden
3586        } else {
3587            ToolbarItemLocation::PrimaryRight
3588        }
3589    }
3590
3591    fn pane_focus_update(
3592        &mut self,
3593        _pane_focused: bool,
3594        _window: &mut Window,
3595        cx: &mut Context<Self>,
3596    ) {
3597        cx.notify();
3598    }
3599}
3600
3601impl EventEmitter<ToolbarItemEvent> for ContextEditorToolbarItem {}
3602
3603pub enum ContextEditorToolbarItemEvent {
3604    RegenerateSummary,
3605}
3606impl EventEmitter<ContextEditorToolbarItemEvent> for ContextEditorToolbarItem {}
3607
3608enum PendingSlashCommand {}
3609
3610fn invoked_slash_command_fold_placeholder(
3611    command_id: InvokedSlashCommandId,
3612    context: WeakEntity<AssistantContext>,
3613) -> FoldPlaceholder {
3614    FoldPlaceholder {
3615        constrain_width: false,
3616        merge_adjacent: false,
3617        render: Arc::new(move |fold_id, _, cx| {
3618            let Some(context) = context.upgrade() else {
3619                return Empty.into_any();
3620            };
3621
3622            let Some(command) = context.read(cx).invoked_slash_command(&command_id) else {
3623                return Empty.into_any();
3624            };
3625
3626            h_flex()
3627                .id(fold_id)
3628                .px_1()
3629                .ml_6()
3630                .gap_2()
3631                .bg(cx.theme().colors().surface_background)
3632                .rounded_sm()
3633                .child(Label::new(format!("/{}", command.name.clone())))
3634                .map(|parent| match &command.status {
3635                    InvokedSlashCommandStatus::Running(_) => {
3636                        parent.child(Icon::new(IconName::ArrowCircle).with_animation(
3637                            "arrow-circle",
3638                            Animation::new(Duration::from_secs(4)).repeat(),
3639                            |icon, delta| icon.transform(Transformation::rotate(percentage(delta))),
3640                        ))
3641                    }
3642                    InvokedSlashCommandStatus::Error(message) => parent.child(
3643                        Label::new(format!("error: {message}"))
3644                            .single_line()
3645                            .color(Color::Error),
3646                    ),
3647                    InvokedSlashCommandStatus::Finished => parent,
3648                })
3649                .into_any_element()
3650        }),
3651        type_tag: Some(TypeId::of::<PendingSlashCommand>()),
3652    }
3653}
3654
3655enum TokenState {
3656    NoTokensLeft {
3657        max_token_count: usize,
3658        token_count: usize,
3659    },
3660    HasMoreTokens {
3661        max_token_count: usize,
3662        token_count: usize,
3663        over_warn_threshold: bool,
3664    },
3665}
3666
3667fn token_state(context: &Entity<AssistantContext>, cx: &App) -> Option<TokenState> {
3668    const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
3669
3670    let model = LanguageModelRegistry::read_global(cx)
3671        .default_model()?
3672        .model;
3673    let token_count = context.read(cx).token_count()?;
3674    let max_token_count = model.max_token_count();
3675
3676    let remaining_tokens = max_token_count as isize - token_count as isize;
3677    let token_state = if remaining_tokens <= 0 {
3678        TokenState::NoTokensLeft {
3679            max_token_count,
3680            token_count,
3681        }
3682    } else {
3683        let over_warn_threshold =
3684            token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
3685        TokenState::HasMoreTokens {
3686            max_token_count,
3687            token_count,
3688            over_warn_threshold,
3689        }
3690    };
3691    Some(token_state)
3692}
3693
3694fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
3695    let image_size = data
3696        .size(0)
3697        .map(|dimension| Pixels::from(u32::from(dimension)));
3698    let image_ratio = image_size.width / image_size.height;
3699    let bounds_ratio = max_size.width / max_size.height;
3700
3701    if image_size.width > max_size.width || image_size.height > max_size.height {
3702        if bounds_ratio > image_ratio {
3703            size(
3704                image_size.width * (max_size.height / image_size.height),
3705                max_size.height,
3706            )
3707        } else {
3708            size(
3709                max_size.width,
3710                image_size.height * (max_size.width / image_size.width),
3711            )
3712        }
3713    } else {
3714        size(image_size.width, image_size.height)
3715    }
3716}
3717
3718pub enum ConfigurationError {
3719    NoProvider,
3720    ProviderNotAuthenticated,
3721    ProviderPendingTermsAcceptance(Arc<dyn LanguageModelProvider>),
3722}
3723
3724fn configuration_error(cx: &App) -> Option<ConfigurationError> {
3725    let model = LanguageModelRegistry::read_global(cx).default_model();
3726    let is_authenticated = model
3727        .as_ref()
3728        .map_or(false, |model| model.provider.is_authenticated(cx));
3729
3730    if model.is_some() && is_authenticated {
3731        return None;
3732    }
3733
3734    if model.is_none() {
3735        return Some(ConfigurationError::NoProvider);
3736    }
3737
3738    if !is_authenticated {
3739        return Some(ConfigurationError::ProviderNotAuthenticated);
3740    }
3741
3742    None
3743}
3744
3745pub fn humanize_token_count(count: usize) -> String {
3746    match count {
3747        0..=999 => count.to_string(),
3748        1000..=9999 => {
3749            let thousands = count / 1000;
3750            let hundreds = (count % 1000 + 50) / 100;
3751            if hundreds == 0 {
3752                format!("{}k", thousands)
3753            } else if hundreds == 10 {
3754                format!("{}k", thousands + 1)
3755            } else {
3756                format!("{}.{}k", thousands, hundreds)
3757            }
3758        }
3759        1_000_000..=9_999_999 => {
3760            let millions = count / 1_000_000;
3761            let hundred_thousands = (count % 1_000_000 + 50_000) / 100_000;
3762            if hundred_thousands == 0 {
3763                format!("{}M", millions)
3764            } else if hundred_thousands == 10 {
3765                format!("{}M", millions + 1)
3766            } else {
3767                format!("{}.{}M", millions, hundred_thousands)
3768            }
3769        }
3770        10_000_000.. => format!("{}M", (count + 500_000) / 1_000_000),
3771        _ => format!("{}k", (count + 500) / 1000),
3772    }
3773}
3774
3775pub fn make_lsp_adapter_delegate(
3776    project: &Entity<Project>,
3777    cx: &mut App,
3778) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
3779    project.update(cx, |project, cx| {
3780        // TODO: Find the right worktree.
3781        let Some(worktree) = project.worktrees(cx).next() else {
3782            return Ok(None::<Arc<dyn LspAdapterDelegate>>);
3783        };
3784        let http_client = project.client().http_client();
3785        project.lsp_store().update(cx, |_, cx| {
3786            Ok(Some(LocalLspAdapterDelegate::new(
3787                project.languages().clone(),
3788                project.environment(),
3789                cx.weak_entity(),
3790                &worktree,
3791                http_client,
3792                project.fs().clone(),
3793                cx,
3794            ) as Arc<dyn LspAdapterDelegate>))
3795        })
3796    })
3797}
3798
3799#[cfg(test)]
3800mod tests {
3801    use super::*;
3802    use gpui::App;
3803    use language::Buffer;
3804    use unindent::Unindent;
3805
3806    #[gpui::test]
3807    fn test_find_code_blocks(cx: &mut App) {
3808        let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
3809
3810        let buffer = cx.new(|cx| {
3811            let text = r#"
3812                line 0
3813                line 1
3814                ```rust
3815                fn main() {}
3816                ```
3817                line 5
3818                line 6
3819                line 7
3820                ```go
3821                func main() {}
3822                ```
3823                line 11
3824                ```
3825                this is plain text code block
3826                ```
3827
3828                ```go
3829                func another() {}
3830                ```
3831                line 19
3832            "#
3833            .unindent();
3834            let mut buffer = Buffer::local(text, cx);
3835            buffer.set_language(Some(markdown.clone()), cx);
3836            buffer
3837        });
3838        let snapshot = buffer.read(cx).snapshot();
3839
3840        let code_blocks = vec![
3841            Point::new(3, 0)..Point::new(4, 0),
3842            Point::new(9, 0)..Point::new(10, 0),
3843            Point::new(13, 0)..Point::new(14, 0),
3844            Point::new(17, 0)..Point::new(18, 0),
3845        ]
3846        .into_iter()
3847        .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
3848        .collect::<Vec<_>>();
3849
3850        let expected_results = vec![
3851            (0, None),
3852            (1, None),
3853            (2, Some(code_blocks[0].clone())),
3854            (3, Some(code_blocks[0].clone())),
3855            (4, Some(code_blocks[0].clone())),
3856            (5, None),
3857            (6, None),
3858            (7, None),
3859            (8, Some(code_blocks[1].clone())),
3860            (9, Some(code_blocks[1].clone())),
3861            (10, Some(code_blocks[1].clone())),
3862            (11, None),
3863            (12, Some(code_blocks[2].clone())),
3864            (13, Some(code_blocks[2].clone())),
3865            (14, Some(code_blocks[2].clone())),
3866            (15, None),
3867            (16, Some(code_blocks[3].clone())),
3868            (17, Some(code_blocks[3].clone())),
3869            (18, Some(code_blocks[3].clone())),
3870            (19, None),
3871        ];
3872
3873        for (row, expected) in expected_results {
3874            let offset = snapshot.point_to_offset(Point::new(row, 0));
3875            let range = find_surrounding_code_block(&snapshot, offset);
3876            assert_eq!(range, expected, "unexpected result on row {:?}", row);
3877        }
3878    }
3879}