context_editor.rs

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