text_thread_editor.rs

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