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