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