text_thread_editor.rs

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