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 worktree_root_name = worktree.read(cx).root_name().to_string();
1435            let mut full_path = PathBuf::from(worktree_root_name.clone());
1436            full_path.push(&project_path.path);
1437            file_slash_command_args.push(full_path.to_string_lossy().to_string());
1438        }
1439
1440        let cmd_name = FileSlashCommand.name();
1441
1442        let file_argument = file_slash_command_args.join(" ");
1443
1444        self.editor.update(cx, |editor, cx| {
1445            editor.insert("\n", window, cx);
1446            editor.insert(&format!("/{} {}", cmd_name, file_argument), window, cx);
1447        });
1448        self.confirm_command(&ConfirmCommand, window, cx);
1449        self.dragged_file_worktrees.extend(added_worktrees);
1450    }
1451
1452    pub fn quote_selection(
1453        workspace: &mut Workspace,
1454        _: &QuoteSelection,
1455        window: &mut Window,
1456        cx: &mut Context<Workspace>,
1457    ) {
1458        let Some(agent_panel_delegate) = <dyn AgentPanelDelegate>::try_global(cx) else {
1459            return;
1460        };
1461
1462        let Some((selections, buffer)) = maybe!({
1463            let editor = workspace
1464                .active_item(cx)
1465                .and_then(|item| item.act_as::<Editor>(cx))?;
1466
1467            let buffer = editor.read(cx).buffer().clone();
1468            let snapshot = buffer.read(cx).snapshot(cx);
1469            let selections = editor.update(cx, |editor, cx| {
1470                editor
1471                    .selections
1472                    .all_adjusted(cx)
1473                    .into_iter()
1474                    .filter_map(|s| {
1475                        (!s.is_empty())
1476                            .then(|| snapshot.anchor_after(s.start)..snapshot.anchor_before(s.end))
1477                    })
1478                    .collect::<Vec<_>>()
1479            });
1480            Some((selections, buffer))
1481        }) else {
1482            return;
1483        };
1484
1485        if selections.is_empty() {
1486            return;
1487        }
1488
1489        agent_panel_delegate.quote_selection(workspace, selections, buffer, window, cx);
1490    }
1491
1492    pub fn quote_ranges(
1493        &mut self,
1494        ranges: Vec<Range<Point>>,
1495        snapshot: MultiBufferSnapshot,
1496        window: &mut Window,
1497        cx: &mut Context<Self>,
1498    ) {
1499        let creases = selections_creases(ranges, snapshot, cx);
1500
1501        self.editor.update(cx, |editor, cx| {
1502            editor.insert("\n", window, cx);
1503            for (text, crease_title) in creases {
1504                let point = editor.selections.newest::<Point>(cx).head();
1505                let start_row = MultiBufferRow(point.row);
1506
1507                editor.insert(&text, window, cx);
1508
1509                let snapshot = editor.buffer().read(cx).snapshot(cx);
1510                let anchor_before = snapshot.anchor_after(point);
1511                let anchor_after = editor
1512                    .selections
1513                    .newest_anchor()
1514                    .head()
1515                    .bias_left(&snapshot);
1516
1517                editor.insert("\n", window, cx);
1518
1519                let fold_placeholder =
1520                    quote_selection_fold_placeholder(crease_title, cx.entity().downgrade());
1521                let crease = Crease::inline(
1522                    anchor_before..anchor_after,
1523                    fold_placeholder,
1524                    render_quote_selection_output_toggle,
1525                    |_, _, _, _| Empty.into_any(),
1526                );
1527                editor.insert_creases(vec![crease], cx);
1528                editor.fold_at(start_row, window, cx);
1529            }
1530        })
1531    }
1532
1533    fn copy(&mut self, _: &editor::actions::Copy, _window: &mut Window, cx: &mut Context<Self>) {
1534        if self.editor.read(cx).selections.count() == 1 {
1535            let (copied_text, metadata, _) = self.get_clipboard_contents(cx);
1536            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1537                copied_text,
1538                metadata,
1539            ));
1540            cx.stop_propagation();
1541            return;
1542        }
1543
1544        cx.propagate();
1545    }
1546
1547    fn cut(&mut self, _: &editor::actions::Cut, window: &mut Window, cx: &mut Context<Self>) {
1548        if self.editor.read(cx).selections.count() == 1 {
1549            let (copied_text, metadata, selections) = self.get_clipboard_contents(cx);
1550
1551            self.editor.update(cx, |editor, cx| {
1552                editor.transact(window, cx, |this, window, cx| {
1553                    this.change_selections(Default::default(), window, cx, |s| {
1554                        s.select(selections);
1555                    });
1556                    this.insert("", window, cx);
1557                    cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1558                        copied_text,
1559                        metadata,
1560                    ));
1561                });
1562            });
1563
1564            cx.stop_propagation();
1565            return;
1566        }
1567
1568        cx.propagate();
1569    }
1570
1571    fn get_clipboard_contents(
1572        &mut self,
1573        cx: &mut Context<Self>,
1574    ) -> (String, CopyMetadata, Vec<text::Selection<usize>>) {
1575        let (mut selection, creases) = self.editor.update(cx, |editor, cx| {
1576            let mut selection = editor.selections.newest_adjusted(cx);
1577            let snapshot = editor.buffer().read(cx).snapshot(cx);
1578
1579            selection.goal = SelectionGoal::None;
1580
1581            let selection_start = snapshot.point_to_offset(selection.start);
1582
1583            (
1584                selection.map(|point| snapshot.point_to_offset(point)),
1585                editor.display_map.update(cx, |display_map, cx| {
1586                    display_map
1587                        .snapshot(cx)
1588                        .crease_snapshot
1589                        .creases_in_range(
1590                            MultiBufferRow(selection.start.row)
1591                                ..MultiBufferRow(selection.end.row + 1),
1592                            &snapshot,
1593                        )
1594                        .filter_map(|crease| {
1595                            if let Crease::Inline {
1596                                range, metadata, ..
1597                            } = &crease
1598                            {
1599                                let metadata = metadata.as_ref()?;
1600                                let start = range
1601                                    .start
1602                                    .to_offset(&snapshot)
1603                                    .saturating_sub(selection_start);
1604                                let end = range
1605                                    .end
1606                                    .to_offset(&snapshot)
1607                                    .saturating_sub(selection_start);
1608
1609                                let range_relative_to_selection = start..end;
1610                                if !range_relative_to_selection.is_empty() {
1611                                    return Some(SelectedCreaseMetadata {
1612                                        range_relative_to_selection,
1613                                        crease: metadata.clone(),
1614                                    });
1615                                }
1616                            }
1617                            None
1618                        })
1619                        .collect::<Vec<_>>()
1620                }),
1621            )
1622        });
1623
1624        let context = self.context.read(cx);
1625
1626        let mut text = String::new();
1627
1628        // If selection is empty, we want to copy the entire line
1629        if selection.range().is_empty() {
1630            let snapshot = context.buffer().read(cx).snapshot();
1631            let point = snapshot.offset_to_point(selection.range().start);
1632            selection.start = snapshot.point_to_offset(Point::new(point.row, 0));
1633            selection.end = snapshot
1634                .point_to_offset(cmp::min(Point::new(point.row + 1, 0), snapshot.max_point()));
1635            for chunk in context.buffer().read(cx).text_for_range(selection.range()) {
1636                text.push_str(chunk);
1637            }
1638        } else {
1639            for message in context.messages(cx) {
1640                if message.offset_range.start >= selection.range().end {
1641                    break;
1642                } else if message.offset_range.end >= selection.range().start {
1643                    let range = cmp::max(message.offset_range.start, selection.range().start)
1644                        ..cmp::min(message.offset_range.end, selection.range().end);
1645                    if !range.is_empty() {
1646                        for chunk in context.buffer().read(cx).text_for_range(range) {
1647                            text.push_str(chunk);
1648                        }
1649                        if message.offset_range.end < selection.range().end {
1650                            text.push('\n');
1651                        }
1652                    }
1653                }
1654            }
1655        }
1656        (text, CopyMetadata { creases }, vec![selection])
1657    }
1658
1659    fn paste(
1660        &mut self,
1661        action: &editor::actions::Paste,
1662        window: &mut Window,
1663        cx: &mut Context<Self>,
1664    ) {
1665        cx.stop_propagation();
1666
1667        let images = if let Some(item) = cx.read_from_clipboard() {
1668            item.into_entries()
1669                .filter_map(|entry| {
1670                    if let ClipboardEntry::Image(image) = entry {
1671                        Some(image)
1672                    } else {
1673                        None
1674                    }
1675                })
1676                .collect()
1677        } else {
1678            Vec::new()
1679        };
1680
1681        let metadata = if let Some(item) = cx.read_from_clipboard() {
1682            item.entries().first().and_then(|entry| {
1683                if let ClipboardEntry::String(text) = entry {
1684                    text.metadata_json::<CopyMetadata>()
1685                } else {
1686                    None
1687                }
1688            })
1689        } else {
1690            None
1691        };
1692
1693        if images.is_empty() {
1694            self.editor.update(cx, |editor, cx| {
1695                let paste_position = editor.selections.newest::<usize>(cx).head();
1696                editor.paste(action, window, cx);
1697
1698                if let Some(metadata) = metadata {
1699                    let buffer = editor.buffer().read(cx).snapshot(cx);
1700
1701                    let mut buffer_rows_to_fold = BTreeSet::new();
1702                    let weak_editor = cx.entity().downgrade();
1703                    editor.insert_creases(
1704                        metadata.creases.into_iter().map(|metadata| {
1705                            let start = buffer.anchor_after(
1706                                paste_position + metadata.range_relative_to_selection.start,
1707                            );
1708                            let end = buffer.anchor_before(
1709                                paste_position + metadata.range_relative_to_selection.end,
1710                            );
1711
1712                            let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1713                            buffer_rows_to_fold.insert(buffer_row);
1714                            Crease::inline(
1715                                start..end,
1716                                FoldPlaceholder {
1717                                    render: render_fold_icon_button(
1718                                        weak_editor.clone(),
1719                                        metadata.crease.icon_path.clone(),
1720                                        metadata.crease.label.clone(),
1721                                    ),
1722                                    ..Default::default()
1723                                },
1724                                render_slash_command_output_toggle,
1725                                |_, _, _, _| Empty.into_any(),
1726                            )
1727                            .with_metadata(metadata.crease)
1728                        }),
1729                        cx,
1730                    );
1731                    for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1732                        editor.fold_at(buffer_row, window, cx);
1733                    }
1734                }
1735            });
1736        } else {
1737            let mut image_positions = Vec::new();
1738            self.editor.update(cx, |editor, cx| {
1739                editor.transact(window, cx, |editor, _window, cx| {
1740                    let edits = editor
1741                        .selections
1742                        .all::<usize>(cx)
1743                        .into_iter()
1744                        .map(|selection| (selection.start..selection.end, "\n"));
1745                    editor.edit(edits, cx);
1746
1747                    let snapshot = editor.buffer().read(cx).snapshot(cx);
1748                    for selection in editor.selections.all::<usize>(cx) {
1749                        image_positions.push(snapshot.anchor_before(selection.end));
1750                    }
1751                });
1752            });
1753
1754            self.context.update(cx, |context, cx| {
1755                for image in images {
1756                    let Some(render_image) = image.to_image_data(cx.svg_renderer()).log_err()
1757                    else {
1758                        continue;
1759                    };
1760                    let image_id = image.id();
1761                    let image_task = LanguageModelImage::from_image(Arc::new(image), cx).shared();
1762
1763                    for image_position in image_positions.iter() {
1764                        context.insert_content(
1765                            Content::Image {
1766                                anchor: image_position.text_anchor,
1767                                image_id,
1768                                image: image_task.clone(),
1769                                render_image: render_image.clone(),
1770                            },
1771                            cx,
1772                        );
1773                    }
1774                }
1775            });
1776        }
1777    }
1778
1779    fn update_image_blocks(&mut self, cx: &mut Context<Self>) {
1780        self.editor.update(cx, |editor, cx| {
1781            let buffer = editor.buffer().read(cx).snapshot(cx);
1782            let excerpt_id = *buffer.as_singleton().unwrap().0;
1783            let old_blocks = std::mem::take(&mut self.image_blocks);
1784            let new_blocks = self
1785                .context
1786                .read(cx)
1787                .contents(cx)
1788                .map(
1789                    |Content::Image {
1790                         anchor,
1791                         render_image,
1792                         ..
1793                     }| (anchor, render_image),
1794                )
1795                .filter_map(|(anchor, render_image)| {
1796                    const MAX_HEIGHT_IN_LINES: u32 = 8;
1797                    let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
1798                    let image = render_image;
1799                    anchor.is_valid(&buffer).then(|| BlockProperties {
1800                        placement: BlockPlacement::Above(anchor),
1801                        height: Some(MAX_HEIGHT_IN_LINES),
1802                        style: BlockStyle::Sticky,
1803                        render: Arc::new(move |cx| {
1804                            let image_size = size_for_image(
1805                                &image,
1806                                size(
1807                                    cx.max_width - cx.margins.gutter.full_width(),
1808                                    MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
1809                                ),
1810                            );
1811                            h_flex()
1812                                .pl(cx.margins.gutter.full_width())
1813                                .child(
1814                                    img(image.clone())
1815                                        .object_fit(gpui::ObjectFit::ScaleDown)
1816                                        .w(image_size.width)
1817                                        .h(image_size.height),
1818                                )
1819                                .into_any_element()
1820                        }),
1821                        priority: 0,
1822                    })
1823                })
1824                .collect::<Vec<_>>();
1825
1826            editor.remove_blocks(old_blocks, None, cx);
1827            let ids = editor.insert_blocks(new_blocks, None, cx);
1828            self.image_blocks = HashSet::from_iter(ids);
1829        });
1830    }
1831
1832    fn split(&mut self, _: &Split, _window: &mut Window, cx: &mut Context<Self>) {
1833        self.context.update(cx, |context, cx| {
1834            let selections = self.editor.read(cx).selections.disjoint_anchors_arc();
1835            for selection in selections.as_ref() {
1836                let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
1837                let range = selection
1838                    .map(|endpoint| endpoint.to_offset(&buffer))
1839                    .range();
1840                context.split_message(range, cx);
1841            }
1842        });
1843    }
1844
1845    fn save(&mut self, _: &Save, _window: &mut Window, cx: &mut Context<Self>) {
1846        self.context.update(cx, |context, cx| {
1847            context.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
1848        });
1849    }
1850
1851    pub fn title(&self, cx: &App) -> SharedString {
1852        self.context.read(cx).summary().or_default()
1853    }
1854
1855    pub fn regenerate_summary(&mut self, cx: &mut Context<Self>) {
1856        self.context
1857            .update(cx, |context, cx| context.summarize(true, cx));
1858    }
1859
1860    fn render_remaining_tokens(&self, cx: &App) -> Option<impl IntoElement + use<>> {
1861        let (token_count_color, token_count, max_token_count, tooltip) =
1862            match token_state(&self.context, cx)? {
1863                TokenState::NoTokensLeft {
1864                    max_token_count,
1865                    token_count,
1866                } => (
1867                    Color::Error,
1868                    token_count,
1869                    max_token_count,
1870                    Some("Token Limit Reached"),
1871                ),
1872                TokenState::HasMoreTokens {
1873                    max_token_count,
1874                    token_count,
1875                    over_warn_threshold,
1876                } => {
1877                    let (color, tooltip) = if over_warn_threshold {
1878                        (Color::Warning, Some("Token Limit is Close to Exhaustion"))
1879                    } else {
1880                        (Color::Muted, None)
1881                    };
1882                    (color, token_count, max_token_count, tooltip)
1883                }
1884            };
1885
1886        Some(
1887            h_flex()
1888                .id("token-count")
1889                .gap_0p5()
1890                .child(
1891                    Label::new(humanize_token_count(token_count))
1892                        .size(LabelSize::Small)
1893                        .color(token_count_color),
1894                )
1895                .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
1896                .child(
1897                    Label::new(humanize_token_count(max_token_count))
1898                        .size(LabelSize::Small)
1899                        .color(Color::Muted),
1900                )
1901                .when_some(tooltip, |element, tooltip| {
1902                    element.tooltip(Tooltip::text(tooltip))
1903                }),
1904        )
1905    }
1906
1907    fn render_send_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1908        let focus_handle = self.focus_handle(cx);
1909
1910        let (style, tooltip) = match token_state(&self.context, cx) {
1911            Some(TokenState::NoTokensLeft { .. }) => (
1912                ButtonStyle::Tinted(TintColor::Error),
1913                Some(Tooltip::text("Token limit reached")(window, cx)),
1914            ),
1915            Some(TokenState::HasMoreTokens {
1916                over_warn_threshold,
1917                ..
1918            }) => {
1919                let (style, tooltip) = if over_warn_threshold {
1920                    (
1921                        ButtonStyle::Tinted(TintColor::Warning),
1922                        Some(Tooltip::text("Token limit is close to exhaustion")(
1923                            window, cx,
1924                        )),
1925                    )
1926                } else {
1927                    (ButtonStyle::Filled, None)
1928                };
1929                (style, tooltip)
1930            }
1931            None => (ButtonStyle::Filled, None),
1932        };
1933
1934        Button::new("send_button", "Send")
1935            .label_size(LabelSize::Small)
1936            .disabled(self.sending_disabled(cx))
1937            .style(style)
1938            .when_some(tooltip, |button, tooltip| {
1939                button.tooltip(move |_, _| tooltip.clone())
1940            })
1941            .layer(ElevationIndex::ModalSurface)
1942            .key_binding(
1943                KeyBinding::for_action_in(&Assist, &focus_handle, window, cx)
1944                    .map(|kb| kb.size(rems_from_px(12.))),
1945            )
1946            .on_click(move |_event, window, cx| {
1947                focus_handle.dispatch_action(&Assist, window, cx);
1948            })
1949    }
1950
1951    /// Whether or not we should allow messages to be sent.
1952    /// Will return false if the selected provided has a configuration error or
1953    /// if the user has not accepted the terms of service for this provider.
1954    fn sending_disabled(&self, cx: &mut Context<'_, TextThreadEditor>) -> bool {
1955        let model_registry = LanguageModelRegistry::read_global(cx);
1956        let Some(configuration_error) =
1957            model_registry.configuration_error(model_registry.default_model(), cx)
1958        else {
1959            return false;
1960        };
1961
1962        match configuration_error {
1963            ConfigurationError::NoProvider
1964            | ConfigurationError::ModelNotFound
1965            | ConfigurationError::ProviderNotAuthenticated(_) => true,
1966        }
1967    }
1968
1969    fn render_inject_context_menu(&self, cx: &mut Context<Self>) -> impl IntoElement {
1970        slash_command_picker::SlashCommandSelector::new(
1971            self.slash_commands.clone(),
1972            cx.entity().downgrade(),
1973            IconButton::new("trigger", IconName::Plus)
1974                .icon_size(IconSize::Small)
1975                .icon_color(Color::Muted),
1976            move |window, cx| {
1977                Tooltip::with_meta(
1978                    "Add Context",
1979                    None,
1980                    "Type / to insert via keyboard",
1981                    window,
1982                    cx,
1983                )
1984            },
1985        )
1986    }
1987
1988    fn render_burn_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
1989        let context = self.context().read(cx);
1990        let active_model = LanguageModelRegistry::read_global(cx)
1991            .default_model()
1992            .map(|default| default.model)?;
1993        if !active_model.supports_burn_mode() {
1994            return None;
1995        }
1996
1997        let active_completion_mode = context.completion_mode();
1998        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
1999        let icon = if burn_mode_enabled {
2000            IconName::ZedBurnModeOn
2001        } else {
2002            IconName::ZedBurnMode
2003        };
2004
2005        Some(
2006            IconButton::new("burn-mode", icon)
2007                .icon_size(IconSize::Small)
2008                .icon_color(Color::Muted)
2009                .toggle_state(burn_mode_enabled)
2010                .selected_icon_color(Color::Error)
2011                .on_click(cx.listener(move |this, _event, _window, cx| {
2012                    this.context().update(cx, |context, _cx| {
2013                        context.set_completion_mode(match active_completion_mode {
2014                            CompletionMode::Burn => CompletionMode::Normal,
2015                            CompletionMode::Normal => CompletionMode::Burn,
2016                        });
2017                    });
2018                }))
2019                .tooltip(move |_window, cx| {
2020                    cx.new(|_| BurnModeTooltip::new().selected(burn_mode_enabled))
2021                        .into()
2022                })
2023                .into_any_element(),
2024        )
2025    }
2026
2027    fn render_language_model_selector(
2028        &self,
2029        window: &mut Window,
2030        cx: &mut Context<Self>,
2031    ) -> impl IntoElement {
2032        let active_model = LanguageModelRegistry::read_global(cx)
2033            .default_model()
2034            .map(|default| default.model);
2035        let model_name = match active_model {
2036            Some(model) => model.name().0,
2037            None => SharedString::from("Select Model"),
2038        };
2039
2040        let active_provider = LanguageModelRegistry::read_global(cx)
2041            .default_model()
2042            .map(|default| default.provider);
2043
2044        let provider_icon = match active_provider {
2045            Some(provider) => provider.icon(),
2046            None => IconName::Ai,
2047        };
2048
2049        let focus_handle = self.editor().focus_handle(cx);
2050
2051        PickerPopoverMenu::new(
2052            self.language_model_selector.clone(),
2053            ButtonLike::new("active-model")
2054                .style(ButtonStyle::Subtle)
2055                .child(
2056                    h_flex()
2057                        .gap_0p5()
2058                        .child(
2059                            Icon::new(provider_icon)
2060                                .color(Color::Muted)
2061                                .size(IconSize::XSmall),
2062                        )
2063                        .child(
2064                            Label::new(model_name)
2065                                .color(Color::Muted)
2066                                .size(LabelSize::Small)
2067                                .ml_0p5(),
2068                        )
2069                        .child(
2070                            Icon::new(IconName::ChevronDown)
2071                                .color(Color::Muted)
2072                                .size(IconSize::XSmall),
2073                        ),
2074                ),
2075            move |window, cx| {
2076                Tooltip::for_action_in(
2077                    "Change Model",
2078                    &ToggleModelSelector,
2079                    &focus_handle,
2080                    window,
2081                    cx,
2082                )
2083            },
2084            gpui::Corner::BottomLeft,
2085            cx,
2086        )
2087        .with_handle(self.language_model_selector_menu_handle.clone())
2088        .render(window, cx)
2089    }
2090
2091    fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2092        let last_error = self.last_error.as_ref()?;
2093
2094        Some(
2095            div()
2096                .absolute()
2097                .right_3()
2098                .bottom_12()
2099                .max_w_96()
2100                .py_2()
2101                .px_3()
2102                .elevation_2(cx)
2103                .occlude()
2104                .child(match last_error {
2105                    AssistError::PaymentRequired => self.render_payment_required_error(cx),
2106                    AssistError::Message(error_message) => {
2107                        self.render_assist_error(error_message, cx)
2108                    }
2109                })
2110                .into_any(),
2111        )
2112    }
2113
2114    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2115        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.";
2116
2117        v_flex()
2118            .gap_0p5()
2119            .child(
2120                h_flex()
2121                    .gap_1p5()
2122                    .items_center()
2123                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2124                    .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2125            )
2126            .child(
2127                div()
2128                    .id("error-message")
2129                    .max_h_24()
2130                    .overflow_y_scroll()
2131                    .child(Label::new(ERROR_MESSAGE)),
2132            )
2133            .child(
2134                h_flex()
2135                    .justify_end()
2136                    .mt_1()
2137                    .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
2138                        |this, _, _window, cx| {
2139                            this.last_error = None;
2140                            cx.open_url(&zed_urls::account_url(cx));
2141                            cx.notify();
2142                        },
2143                    )))
2144                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2145                        |this, _, _window, cx| {
2146                            this.last_error = None;
2147                            cx.notify();
2148                        },
2149                    ))),
2150            )
2151            .into_any()
2152    }
2153
2154    fn render_assist_error(
2155        &self,
2156        error_message: &SharedString,
2157        cx: &mut Context<Self>,
2158    ) -> AnyElement {
2159        v_flex()
2160            .gap_0p5()
2161            .child(
2162                h_flex()
2163                    .gap_1p5()
2164                    .items_center()
2165                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2166                    .child(
2167                        Label::new("Error interacting with language model")
2168                            .weight(FontWeight::MEDIUM),
2169                    ),
2170            )
2171            .child(
2172                div()
2173                    .id("error-message")
2174                    .max_h_32()
2175                    .overflow_y_scroll()
2176                    .child(Label::new(error_message.clone())),
2177            )
2178            .child(
2179                h_flex()
2180                    .justify_end()
2181                    .mt_1()
2182                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2183                        |this, _, _window, cx| {
2184                            this.last_error = None;
2185                            cx.notify();
2186                        },
2187                    ))),
2188            )
2189            .into_any()
2190    }
2191}
2192
2193/// Returns the contents of the *outermost* fenced code block that contains the given offset.
2194fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
2195    const CODE_BLOCK_NODE: &str = "fenced_code_block";
2196    const CODE_BLOCK_CONTENT: &str = "code_fence_content";
2197
2198    let layer = snapshot.syntax_layers().next()?;
2199
2200    let root_node = layer.node();
2201    let mut cursor = root_node.walk();
2202
2203    // Go to the first child for the given offset
2204    while cursor.goto_first_child_for_byte(offset).is_some() {
2205        // If we're at the end of the node, go to the next one.
2206        // Example: if you have a fenced-code-block, and you're on the start of the line
2207        // right after the closing ```, you want to skip the fenced-code-block and
2208        // go to the next sibling.
2209        if cursor.node().end_byte() == offset {
2210            cursor.goto_next_sibling();
2211        }
2212
2213        if cursor.node().start_byte() > offset {
2214            break;
2215        }
2216
2217        // We found the fenced code block.
2218        if cursor.node().kind() == CODE_BLOCK_NODE {
2219            // Now we need to find the child node that contains the code.
2220            cursor.goto_first_child();
2221            loop {
2222                if cursor.node().kind() == CODE_BLOCK_CONTENT {
2223                    return Some(cursor.node().byte_range());
2224                }
2225                if !cursor.goto_next_sibling() {
2226                    break;
2227                }
2228            }
2229        }
2230    }
2231
2232    None
2233}
2234
2235fn render_thought_process_fold_icon_button(
2236    editor: WeakEntity<Editor>,
2237    status: ThoughtProcessStatus,
2238) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2239    Arc::new(move |fold_id, fold_range, _cx| {
2240        let editor = editor.clone();
2241
2242        let button = ButtonLike::new(fold_id).layer(ElevationIndex::ElevatedSurface);
2243        let button = match status {
2244            ThoughtProcessStatus::Pending => button
2245                .child(
2246                    Icon::new(IconName::ToolThink)
2247                        .size(IconSize::Small)
2248                        .color(Color::Muted),
2249                )
2250                .child(
2251                    Label::new("Thinking…").color(Color::Muted).with_animation(
2252                        "pulsating-label",
2253                        Animation::new(Duration::from_secs(2))
2254                            .repeat()
2255                            .with_easing(pulsating_between(0.4, 0.8)),
2256                        |label, delta| label.alpha(delta),
2257                    ),
2258                ),
2259            ThoughtProcessStatus::Completed => button
2260                .style(ButtonStyle::Filled)
2261                .child(Icon::new(IconName::ToolThink).size(IconSize::Small))
2262                .child(Label::new("Thought Process").single_line()),
2263        };
2264
2265        button
2266            .on_click(move |_, window, cx| {
2267                editor
2268                    .update(cx, |editor, cx| {
2269                        let buffer_start = fold_range
2270                            .start
2271                            .to_point(&editor.buffer().read(cx).read(cx));
2272                        let buffer_row = MultiBufferRow(buffer_start.row);
2273                        editor.unfold_at(buffer_row, window, cx);
2274                    })
2275                    .ok();
2276            })
2277            .into_any_element()
2278    })
2279}
2280
2281fn render_fold_icon_button(
2282    editor: WeakEntity<Editor>,
2283    icon_path: SharedString,
2284    label: SharedString,
2285) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2286    Arc::new(move |fold_id, fold_range, _cx| {
2287        let editor = editor.clone();
2288        ButtonLike::new(fold_id)
2289            .style(ButtonStyle::Filled)
2290            .layer(ElevationIndex::ElevatedSurface)
2291            .child(Icon::from_path(icon_path.clone()))
2292            .child(Label::new(label.clone()).single_line())
2293            .on_click(move |_, window, cx| {
2294                editor
2295                    .update(cx, |editor, cx| {
2296                        let buffer_start = fold_range
2297                            .start
2298                            .to_point(&editor.buffer().read(cx).read(cx));
2299                        let buffer_row = MultiBufferRow(buffer_start.row);
2300                        editor.unfold_at(buffer_row, window, cx);
2301                    })
2302                    .ok();
2303            })
2304            .into_any_element()
2305    })
2306}
2307
2308type ToggleFold = Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>;
2309
2310fn render_slash_command_output_toggle(
2311    row: MultiBufferRow,
2312    is_folded: bool,
2313    fold: ToggleFold,
2314    _window: &mut Window,
2315    _cx: &mut App,
2316) -> AnyElement {
2317    Disclosure::new(
2318        ("slash-command-output-fold-indicator", row.0 as u64),
2319        !is_folded,
2320    )
2321    .toggle_state(is_folded)
2322    .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2323    .into_any_element()
2324}
2325
2326pub fn fold_toggle(
2327    name: &'static str,
2328) -> impl Fn(
2329    MultiBufferRow,
2330    bool,
2331    Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
2332    &mut Window,
2333    &mut App,
2334) -> AnyElement {
2335    move |row, is_folded, fold, _window, _cx| {
2336        Disclosure::new((name, row.0 as u64), !is_folded)
2337            .toggle_state(is_folded)
2338            .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2339            .into_any_element()
2340    }
2341}
2342
2343fn quote_selection_fold_placeholder(title: String, editor: WeakEntity<Editor>) -> FoldPlaceholder {
2344    FoldPlaceholder {
2345        render: Arc::new({
2346            move |fold_id, fold_range, _cx| {
2347                let editor = editor.clone();
2348                ButtonLike::new(fold_id)
2349                    .style(ButtonStyle::Filled)
2350                    .layer(ElevationIndex::ElevatedSurface)
2351                    .child(Icon::new(IconName::TextSnippet))
2352                    .child(Label::new(title.clone()).single_line())
2353                    .on_click(move |_, window, cx| {
2354                        editor
2355                            .update(cx, |editor, cx| {
2356                                let buffer_start = fold_range
2357                                    .start
2358                                    .to_point(&editor.buffer().read(cx).read(cx));
2359                                let buffer_row = MultiBufferRow(buffer_start.row);
2360                                editor.unfold_at(buffer_row, window, cx);
2361                            })
2362                            .ok();
2363                    })
2364                    .into_any_element()
2365            }
2366        }),
2367        merge_adjacent: false,
2368        ..Default::default()
2369    }
2370}
2371
2372fn render_quote_selection_output_toggle(
2373    row: MultiBufferRow,
2374    is_folded: bool,
2375    fold: ToggleFold,
2376    _window: &mut Window,
2377    _cx: &mut App,
2378) -> AnyElement {
2379    Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
2380        .toggle_state(is_folded)
2381        .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2382        .into_any_element()
2383}
2384
2385fn render_pending_slash_command_gutter_decoration(
2386    row: MultiBufferRow,
2387    status: &PendingSlashCommandStatus,
2388    confirm_command: Arc<dyn Fn(&mut Window, &mut App)>,
2389) -> AnyElement {
2390    let mut icon = IconButton::new(
2391        ("slash-command-gutter-decoration", row.0),
2392        ui::IconName::TriangleRight,
2393    )
2394    .on_click(move |_e, window, cx| confirm_command(window, cx))
2395    .icon_size(ui::IconSize::Small)
2396    .size(ui::ButtonSize::None);
2397
2398    match status {
2399        PendingSlashCommandStatus::Idle => {
2400            icon = icon.icon_color(Color::Muted);
2401        }
2402        PendingSlashCommandStatus::Running { .. } => {
2403            icon = icon.toggle_state(true);
2404        }
2405        PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
2406    }
2407
2408    icon.into_any_element()
2409}
2410
2411#[derive(Debug, Clone, Serialize, Deserialize)]
2412struct CopyMetadata {
2413    creases: Vec<SelectedCreaseMetadata>,
2414}
2415
2416#[derive(Debug, Clone, Serialize, Deserialize)]
2417struct SelectedCreaseMetadata {
2418    range_relative_to_selection: Range<usize>,
2419    crease: CreaseMetadata,
2420}
2421
2422impl EventEmitter<EditorEvent> for TextThreadEditor {}
2423impl EventEmitter<SearchEvent> for TextThreadEditor {}
2424
2425impl Render for TextThreadEditor {
2426    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2427        let language_model_selector = self.language_model_selector_menu_handle.clone();
2428
2429        v_flex()
2430            .key_context("ContextEditor")
2431            .capture_action(cx.listener(TextThreadEditor::cancel))
2432            .capture_action(cx.listener(TextThreadEditor::save))
2433            .capture_action(cx.listener(TextThreadEditor::copy))
2434            .capture_action(cx.listener(TextThreadEditor::cut))
2435            .capture_action(cx.listener(TextThreadEditor::paste))
2436            .capture_action(cx.listener(TextThreadEditor::cycle_message_role))
2437            .capture_action(cx.listener(TextThreadEditor::confirm_command))
2438            .on_action(cx.listener(TextThreadEditor::assist))
2439            .on_action(cx.listener(TextThreadEditor::split))
2440            .on_action(move |_: &ToggleModelSelector, window, cx| {
2441                language_model_selector.toggle(window, cx);
2442            })
2443            .size_full()
2444            .child(
2445                div()
2446                    .flex_grow()
2447                    .bg(cx.theme().colors().editor_background)
2448                    .child(self.editor.clone()),
2449            )
2450            .children(self.render_last_error(cx))
2451            .child(
2452                h_flex()
2453                    .relative()
2454                    .py_2()
2455                    .pl_1p5()
2456                    .pr_2()
2457                    .w_full()
2458                    .justify_between()
2459                    .border_t_1()
2460                    .border_color(cx.theme().colors().border_variant)
2461                    .bg(cx.theme().colors().editor_background)
2462                    .child(
2463                        h_flex()
2464                            .gap_0p5()
2465                            .child(self.render_inject_context_menu(cx))
2466                            .children(self.render_burn_mode_toggle(cx)),
2467                    )
2468                    .child(
2469                        h_flex()
2470                            .gap_2p5()
2471                            .children(self.render_remaining_tokens(cx))
2472                            .child(
2473                                h_flex()
2474                                    .gap_1()
2475                                    .child(self.render_language_model_selector(window, cx))
2476                                    .child(self.render_send_button(window, cx)),
2477                            ),
2478                    ),
2479            )
2480    }
2481}
2482
2483impl Focusable for TextThreadEditor {
2484    fn focus_handle(&self, cx: &App) -> FocusHandle {
2485        self.editor.focus_handle(cx)
2486    }
2487}
2488
2489impl Item for TextThreadEditor {
2490    type Event = editor::EditorEvent;
2491
2492    fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
2493        util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into()
2494    }
2495
2496    fn to_item_events(event: &Self::Event, mut f: impl FnMut(item::ItemEvent)) {
2497        match event {
2498            EditorEvent::Edited { .. } => {
2499                f(item::ItemEvent::Edit);
2500            }
2501            EditorEvent::TitleChanged => {
2502                f(item::ItemEvent::UpdateTab);
2503            }
2504            _ => {}
2505        }
2506    }
2507
2508    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
2509        Some(self.title(cx).to_string().into())
2510    }
2511
2512    fn as_searchable(&self, handle: &Entity<Self>) -> Option<Box<dyn SearchableItemHandle>> {
2513        Some(Box::new(handle.clone()))
2514    }
2515
2516    fn set_nav_history(
2517        &mut self,
2518        nav_history: pane::ItemNavHistory,
2519        window: &mut Window,
2520        cx: &mut Context<Self>,
2521    ) {
2522        self.editor.update(cx, |editor, cx| {
2523            Item::set_nav_history(editor, nav_history, window, cx)
2524        })
2525    }
2526
2527    fn navigate(
2528        &mut self,
2529        data: Box<dyn std::any::Any>,
2530        window: &mut Window,
2531        cx: &mut Context<Self>,
2532    ) -> bool {
2533        self.editor
2534            .update(cx, |editor, cx| Item::navigate(editor, data, window, cx))
2535    }
2536
2537    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2538        self.editor
2539            .update(cx, |editor, cx| Item::deactivated(editor, window, cx))
2540    }
2541
2542    fn act_as_type<'a>(
2543        &'a self,
2544        type_id: TypeId,
2545        self_handle: &'a Entity<Self>,
2546        _: &'a App,
2547    ) -> Option<AnyView> {
2548        if type_id == TypeId::of::<Self>() {
2549            Some(self_handle.to_any())
2550        } else if type_id == TypeId::of::<Editor>() {
2551            Some(self.editor.to_any())
2552        } else {
2553            None
2554        }
2555    }
2556
2557    fn include_in_nav_history() -> bool {
2558        false
2559    }
2560}
2561
2562impl SearchableItem for TextThreadEditor {
2563    type Match = <Editor as SearchableItem>::Match;
2564
2565    fn clear_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2566        self.editor.update(cx, |editor, cx| {
2567            editor.clear_matches(window, cx);
2568        });
2569    }
2570
2571    fn update_matches(
2572        &mut self,
2573        matches: &[Self::Match],
2574        window: &mut Window,
2575        cx: &mut Context<Self>,
2576    ) {
2577        self.editor
2578            .update(cx, |editor, cx| editor.update_matches(matches, window, cx));
2579    }
2580
2581    fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
2582        self.editor
2583            .update(cx, |editor, cx| editor.query_suggestion(window, cx))
2584    }
2585
2586    fn activate_match(
2587        &mut self,
2588        index: usize,
2589        matches: &[Self::Match],
2590        window: &mut Window,
2591        cx: &mut Context<Self>,
2592    ) {
2593        self.editor.update(cx, |editor, cx| {
2594            editor.activate_match(index, matches, window, cx);
2595        });
2596    }
2597
2598    fn select_matches(
2599        &mut self,
2600        matches: &[Self::Match],
2601        window: &mut Window,
2602        cx: &mut Context<Self>,
2603    ) {
2604        self.editor
2605            .update(cx, |editor, cx| editor.select_matches(matches, window, cx));
2606    }
2607
2608    fn replace(
2609        &mut self,
2610        identifier: &Self::Match,
2611        query: &project::search::SearchQuery,
2612        window: &mut Window,
2613        cx: &mut Context<Self>,
2614    ) {
2615        self.editor.update(cx, |editor, cx| {
2616            editor.replace(identifier, query, window, cx)
2617        });
2618    }
2619
2620    fn find_matches(
2621        &mut self,
2622        query: Arc<project::search::SearchQuery>,
2623        window: &mut Window,
2624        cx: &mut Context<Self>,
2625    ) -> Task<Vec<Self::Match>> {
2626        self.editor
2627            .update(cx, |editor, cx| editor.find_matches(query, window, cx))
2628    }
2629
2630    fn active_match_index(
2631        &mut self,
2632        direction: Direction,
2633        matches: &[Self::Match],
2634        window: &mut Window,
2635        cx: &mut Context<Self>,
2636    ) -> Option<usize> {
2637        self.editor.update(cx, |editor, cx| {
2638            editor.active_match_index(direction, matches, window, cx)
2639        })
2640    }
2641}
2642
2643impl FollowableItem for TextThreadEditor {
2644    fn remote_id(&self) -> Option<workspace::ViewId> {
2645        self.remote_id
2646    }
2647
2648    fn to_state_proto(&self, window: &Window, cx: &App) -> Option<proto::view::Variant> {
2649        let context = self.context.read(cx);
2650        Some(proto::view::Variant::ContextEditor(
2651            proto::view::ContextEditor {
2652                context_id: context.id().to_proto(),
2653                editor: if let Some(proto::view::Variant::Editor(proto)) =
2654                    self.editor.read(cx).to_state_proto(window, cx)
2655                {
2656                    Some(proto)
2657                } else {
2658                    None
2659                },
2660            },
2661        ))
2662    }
2663
2664    fn from_state_proto(
2665        workspace: Entity<Workspace>,
2666        id: workspace::ViewId,
2667        state: &mut Option<proto::view::Variant>,
2668        window: &mut Window,
2669        cx: &mut App,
2670    ) -> Option<Task<Result<Entity<Self>>>> {
2671        let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
2672            return None;
2673        };
2674        let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
2675            unreachable!()
2676        };
2677
2678        let context_id = ContextId::from_proto(state.context_id);
2679        let editor_state = state.editor?;
2680
2681        let project = workspace.read(cx).project().clone();
2682        let agent_panel_delegate = <dyn AgentPanelDelegate>::try_global(cx)?;
2683
2684        let context_editor_task = workspace.update(cx, |workspace, cx| {
2685            agent_panel_delegate.open_remote_context(workspace, context_id, window, cx)
2686        });
2687
2688        Some(window.spawn(cx, async move |cx| {
2689            let context_editor = context_editor_task.await?;
2690            context_editor
2691                .update_in(cx, |context_editor, window, cx| {
2692                    context_editor.remote_id = Some(id);
2693                    context_editor.editor.update(cx, |editor, cx| {
2694                        editor.apply_update_proto(
2695                            &project,
2696                            proto::update_view::Variant::Editor(proto::update_view::Editor {
2697                                selections: editor_state.selections,
2698                                pending_selection: editor_state.pending_selection,
2699                                scroll_top_anchor: editor_state.scroll_top_anchor,
2700                                scroll_x: editor_state.scroll_y,
2701                                scroll_y: editor_state.scroll_y,
2702                                ..Default::default()
2703                            }),
2704                            window,
2705                            cx,
2706                        )
2707                    })
2708                })?
2709                .await?;
2710            Ok(context_editor)
2711        }))
2712    }
2713
2714    fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
2715        Editor::to_follow_event(event)
2716    }
2717
2718    fn add_event_to_update_proto(
2719        &self,
2720        event: &Self::Event,
2721        update: &mut Option<proto::update_view::Variant>,
2722        window: &Window,
2723        cx: &App,
2724    ) -> bool {
2725        self.editor
2726            .read(cx)
2727            .add_event_to_update_proto(event, update, window, cx)
2728    }
2729
2730    fn apply_update_proto(
2731        &mut self,
2732        project: &Entity<Project>,
2733        message: proto::update_view::Variant,
2734        window: &mut Window,
2735        cx: &mut Context<Self>,
2736    ) -> Task<Result<()>> {
2737        self.editor.update(cx, |editor, cx| {
2738            editor.apply_update_proto(project, message, window, cx)
2739        })
2740    }
2741
2742    fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
2743        true
2744    }
2745
2746    fn set_leader_id(
2747        &mut self,
2748        leader_id: Option<CollaboratorId>,
2749        window: &mut Window,
2750        cx: &mut Context<Self>,
2751    ) {
2752        self.editor
2753            .update(cx, |editor, cx| editor.set_leader_id(leader_id, window, cx))
2754    }
2755
2756    fn dedup(&self, existing: &Self, _window: &Window, cx: &App) -> Option<item::Dedup> {
2757        if existing.context.read(cx).id() == self.context.read(cx).id() {
2758            Some(item::Dedup::KeepExisting)
2759        } else {
2760            None
2761        }
2762    }
2763}
2764
2765enum PendingSlashCommand {}
2766
2767fn invoked_slash_command_fold_placeholder(
2768    command_id: InvokedSlashCommandId,
2769    context: WeakEntity<AssistantContext>,
2770) -> FoldPlaceholder {
2771    FoldPlaceholder {
2772        constrain_width: false,
2773        merge_adjacent: false,
2774        render: Arc::new(move |fold_id, _, cx| {
2775            let Some(context) = context.upgrade() else {
2776                return Empty.into_any();
2777            };
2778
2779            let Some(command) = context.read(cx).invoked_slash_command(&command_id) else {
2780                return Empty.into_any();
2781            };
2782
2783            h_flex()
2784                .id(fold_id)
2785                .px_1()
2786                .ml_6()
2787                .gap_2()
2788                .bg(cx.theme().colors().surface_background)
2789                .rounded_sm()
2790                .child(Label::new(format!("/{}", command.name)))
2791                .map(|parent| match &command.status {
2792                    InvokedSlashCommandStatus::Running(_) => {
2793                        parent.child(Icon::new(IconName::ArrowCircle).with_rotate_animation(4))
2794                    }
2795                    InvokedSlashCommandStatus::Error(message) => parent.child(
2796                        Label::new(format!("error: {message}"))
2797                            .single_line()
2798                            .color(Color::Error),
2799                    ),
2800                    InvokedSlashCommandStatus::Finished => parent,
2801                })
2802                .into_any_element()
2803        }),
2804        type_tag: Some(TypeId::of::<PendingSlashCommand>()),
2805    }
2806}
2807
2808enum TokenState {
2809    NoTokensLeft {
2810        max_token_count: u64,
2811        token_count: u64,
2812    },
2813    HasMoreTokens {
2814        max_token_count: u64,
2815        token_count: u64,
2816        over_warn_threshold: bool,
2817    },
2818}
2819
2820fn token_state(context: &Entity<AssistantContext>, cx: &App) -> Option<TokenState> {
2821    const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
2822
2823    let model = LanguageModelRegistry::read_global(cx)
2824        .default_model()?
2825        .model;
2826    let token_count = context.read(cx).token_count()?;
2827    let max_token_count = model.max_token_count_for_mode(context.read(cx).completion_mode().into());
2828    let token_state = if max_token_count.saturating_sub(token_count) == 0 {
2829        TokenState::NoTokensLeft {
2830            max_token_count,
2831            token_count,
2832        }
2833    } else {
2834        let over_warn_threshold =
2835            token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
2836        TokenState::HasMoreTokens {
2837            max_token_count,
2838            token_count,
2839            over_warn_threshold,
2840        }
2841    };
2842    Some(token_state)
2843}
2844
2845fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
2846    let image_size = data
2847        .size(0)
2848        .map(|dimension| Pixels::from(u32::from(dimension)));
2849    let image_ratio = image_size.width / image_size.height;
2850    let bounds_ratio = max_size.width / max_size.height;
2851
2852    if image_size.width > max_size.width || image_size.height > max_size.height {
2853        if bounds_ratio > image_ratio {
2854            size(
2855                image_size.width * (max_size.height / image_size.height),
2856                max_size.height,
2857            )
2858        } else {
2859            size(
2860                max_size.width,
2861                image_size.height * (max_size.width / image_size.width),
2862            )
2863        }
2864    } else {
2865        size(image_size.width, image_size.height)
2866    }
2867}
2868
2869pub fn humanize_token_count(count: u64) -> String {
2870    match count {
2871        0..=999 => count.to_string(),
2872        1000..=9999 => {
2873            let thousands = count / 1000;
2874            let hundreds = (count % 1000 + 50) / 100;
2875            if hundreds == 0 {
2876                format!("{}k", thousands)
2877            } else if hundreds == 10 {
2878                format!("{}k", thousands + 1)
2879            } else {
2880                format!("{}.{}k", thousands, hundreds)
2881            }
2882        }
2883        1_000_000..=9_999_999 => {
2884            let millions = count / 1_000_000;
2885            let hundred_thousands = (count % 1_000_000 + 50_000) / 100_000;
2886            if hundred_thousands == 0 {
2887                format!("{}M", millions)
2888            } else if hundred_thousands == 10 {
2889                format!("{}M", millions + 1)
2890            } else {
2891                format!("{}.{}M", millions, hundred_thousands)
2892            }
2893        }
2894        10_000_000.. => format!("{}M", (count + 500_000) / 1_000_000),
2895        _ => format!("{}k", (count + 500) / 1000),
2896    }
2897}
2898
2899pub fn make_lsp_adapter_delegate(
2900    project: &Entity<Project>,
2901    cx: &mut App,
2902) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
2903    project.update(cx, |project, cx| {
2904        // TODO: Find the right worktree.
2905        let Some(worktree) = project.worktrees(cx).next() else {
2906            return Ok(None::<Arc<dyn LspAdapterDelegate>>);
2907        };
2908        let http_client = project.client().http_client();
2909        project.lsp_store().update(cx, |_, cx| {
2910            Ok(Some(LocalLspAdapterDelegate::new(
2911                project.languages().clone(),
2912                project.environment(),
2913                cx.weak_entity(),
2914                &worktree,
2915                http_client,
2916                project.fs().clone(),
2917                cx,
2918            ) as Arc<dyn LspAdapterDelegate>))
2919        })
2920    })
2921}
2922
2923#[cfg(test)]
2924mod tests {
2925    use super::*;
2926    use editor::SelectionEffects;
2927    use fs::FakeFs;
2928    use gpui::{App, TestAppContext, VisualTestContext};
2929    use indoc::indoc;
2930    use language::{Buffer, LanguageRegistry};
2931    use pretty_assertions::assert_eq;
2932    use prompt_store::PromptBuilder;
2933    use text::OffsetRangeExt;
2934    use unindent::Unindent;
2935    use util::path;
2936
2937    #[gpui::test]
2938    async fn test_copy_paste_whole_message(cx: &mut TestAppContext) {
2939        let (context, context_editor, mut cx) = setup_context_editor_text(vec![
2940            (Role::User, "What is the Zed editor?"),
2941            (
2942                Role::Assistant,
2943                "Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.",
2944            ),
2945            (Role::User, ""),
2946        ],cx).await;
2947
2948        // Select & Copy whole user message
2949        assert_copy_paste_context_editor(
2950            &context_editor,
2951            message_range(&context, 0, &mut cx),
2952            indoc! {"
2953                What is the Zed editor?
2954                Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
2955                What is the Zed editor?
2956            "},
2957            &mut cx,
2958        );
2959
2960        // Select & Copy whole assistant message
2961        assert_copy_paste_context_editor(
2962            &context_editor,
2963            message_range(&context, 1, &mut cx),
2964            indoc! {"
2965                What is the Zed editor?
2966                Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
2967                What is the Zed editor?
2968                Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
2969            "},
2970            &mut cx,
2971        );
2972    }
2973
2974    #[gpui::test]
2975    async fn test_copy_paste_no_selection(cx: &mut TestAppContext) {
2976        let (context, context_editor, mut cx) = setup_context_editor_text(
2977            vec![
2978                (Role::User, "user1"),
2979                (Role::Assistant, "assistant1"),
2980                (Role::Assistant, "assistant2"),
2981                (Role::User, ""),
2982            ],
2983            cx,
2984        )
2985        .await;
2986
2987        // Copy and paste first assistant message
2988        let message_2_range = message_range(&context, 1, &mut cx);
2989        assert_copy_paste_context_editor(
2990            &context_editor,
2991            message_2_range.start..message_2_range.start,
2992            indoc! {"
2993                user1
2994                assistant1
2995                assistant2
2996                assistant1
2997            "},
2998            &mut cx,
2999        );
3000
3001        // Copy and cut second assistant message
3002        let message_3_range = message_range(&context, 2, &mut cx);
3003        assert_copy_paste_context_editor(
3004            &context_editor,
3005            message_3_range.start..message_3_range.start,
3006            indoc! {"
3007                user1
3008                assistant1
3009                assistant2
3010                assistant1
3011                assistant2
3012            "},
3013            &mut cx,
3014        );
3015    }
3016
3017    #[gpui::test]
3018    fn test_find_code_blocks(cx: &mut App) {
3019        let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
3020
3021        let buffer = cx.new(|cx| {
3022            let text = r#"
3023                line 0
3024                line 1
3025                ```rust
3026                fn main() {}
3027                ```
3028                line 5
3029                line 6
3030                line 7
3031                ```go
3032                func main() {}
3033                ```
3034                line 11
3035                ```
3036                this is plain text code block
3037                ```
3038
3039                ```go
3040                func another() {}
3041                ```
3042                line 19
3043            "#
3044            .unindent();
3045            let mut buffer = Buffer::local(text, cx);
3046            buffer.set_language(Some(markdown.clone()), cx);
3047            buffer
3048        });
3049        let snapshot = buffer.read(cx).snapshot();
3050
3051        let code_blocks = vec![
3052            Point::new(3, 0)..Point::new(4, 0),
3053            Point::new(9, 0)..Point::new(10, 0),
3054            Point::new(13, 0)..Point::new(14, 0),
3055            Point::new(17, 0)..Point::new(18, 0),
3056        ]
3057        .into_iter()
3058        .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
3059        .collect::<Vec<_>>();
3060
3061        let expected_results = vec![
3062            (0, None),
3063            (1, None),
3064            (2, Some(code_blocks[0].clone())),
3065            (3, Some(code_blocks[0].clone())),
3066            (4, Some(code_blocks[0].clone())),
3067            (5, None),
3068            (6, None),
3069            (7, None),
3070            (8, Some(code_blocks[1].clone())),
3071            (9, Some(code_blocks[1].clone())),
3072            (10, Some(code_blocks[1].clone())),
3073            (11, None),
3074            (12, Some(code_blocks[2].clone())),
3075            (13, Some(code_blocks[2].clone())),
3076            (14, Some(code_blocks[2].clone())),
3077            (15, None),
3078            (16, Some(code_blocks[3].clone())),
3079            (17, Some(code_blocks[3].clone())),
3080            (18, Some(code_blocks[3].clone())),
3081            (19, None),
3082        ];
3083
3084        for (row, expected) in expected_results {
3085            let offset = snapshot.point_to_offset(Point::new(row, 0));
3086            let range = find_surrounding_code_block(&snapshot, offset);
3087            assert_eq!(range, expected, "unexpected result on row {:?}", row);
3088        }
3089    }
3090
3091    async fn setup_context_editor_text(
3092        messages: Vec<(Role, &str)>,
3093        cx: &mut TestAppContext,
3094    ) -> (
3095        Entity<AssistantContext>,
3096        Entity<TextThreadEditor>,
3097        VisualTestContext,
3098    ) {
3099        cx.update(init_test);
3100
3101        let fs = FakeFs::new(cx.executor());
3102        let context = create_context_with_messages(messages, cx);
3103
3104        let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
3105        let window = cx.add_window(|window, cx| Workspace::test_new(project.clone(), window, cx));
3106        let workspace = window.root(cx).unwrap();
3107        let mut cx = VisualTestContext::from_window(*window, cx);
3108
3109        let context_editor = window
3110            .update(&mut cx, |_, window, cx| {
3111                cx.new(|cx| {
3112                    TextThreadEditor::for_context(
3113                        context.clone(),
3114                        fs,
3115                        workspace.downgrade(),
3116                        project,
3117                        None,
3118                        window,
3119                        cx,
3120                    )
3121                })
3122            })
3123            .unwrap();
3124
3125        (context, context_editor, cx)
3126    }
3127
3128    fn message_range(
3129        context: &Entity<AssistantContext>,
3130        message_ix: usize,
3131        cx: &mut TestAppContext,
3132    ) -> Range<usize> {
3133        context.update(cx, |context, cx| {
3134            context
3135                .messages(cx)
3136                .nth(message_ix)
3137                .unwrap()
3138                .anchor_range
3139                .to_offset(&context.buffer().read(cx).snapshot())
3140        })
3141    }
3142
3143    fn assert_copy_paste_context_editor<T: editor::ToOffset>(
3144        context_editor: &Entity<TextThreadEditor>,
3145        range: Range<T>,
3146        expected_text: &str,
3147        cx: &mut VisualTestContext,
3148    ) {
3149        context_editor.update_in(cx, |context_editor, window, cx| {
3150            context_editor.editor.update(cx, |editor, cx| {
3151                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
3152                    s.select_ranges([range])
3153                });
3154            });
3155
3156            context_editor.copy(&Default::default(), window, cx);
3157
3158            context_editor.editor.update(cx, |editor, cx| {
3159                editor.move_to_end(&Default::default(), window, cx);
3160            });
3161
3162            context_editor.paste(&Default::default(), window, cx);
3163
3164            context_editor.editor.update(cx, |editor, cx| {
3165                assert_eq!(editor.text(cx), expected_text);
3166            });
3167        });
3168    }
3169
3170    fn create_context_with_messages(
3171        mut messages: Vec<(Role, &str)>,
3172        cx: &mut TestAppContext,
3173    ) -> Entity<AssistantContext> {
3174        let registry = Arc::new(LanguageRegistry::test(cx.executor()));
3175        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3176        cx.new(|cx| {
3177            let mut context = AssistantContext::local(
3178                registry,
3179                None,
3180                None,
3181                prompt_builder.clone(),
3182                Arc::new(SlashCommandWorkingSet::default()),
3183                cx,
3184            );
3185            let mut message_1 = context.messages(cx).next().unwrap();
3186            let (role, text) = messages.remove(0);
3187
3188            loop {
3189                if role == message_1.role {
3190                    context.buffer().update(cx, |buffer, cx| {
3191                        buffer.edit([(message_1.offset_range, text)], None, cx);
3192                    });
3193                    break;
3194                }
3195                let mut ids = HashSet::default();
3196                ids.insert(message_1.id);
3197                context.cycle_message_roles(ids, cx);
3198                message_1 = context.messages(cx).next().unwrap();
3199            }
3200
3201            let mut last_message_id = message_1.id;
3202            for (role, text) in messages {
3203                context.insert_message_after(last_message_id, role, MessageStatus::Done, cx);
3204                let message = context.messages(cx).last().unwrap();
3205                last_message_id = message.id;
3206                context.buffer().update(cx, |buffer, cx| {
3207                    buffer.edit([(message.offset_range, text)], None, cx);
3208                })
3209            }
3210
3211            context
3212        })
3213    }
3214
3215    fn init_test(cx: &mut App) {
3216        let settings_store = SettingsStore::test(cx);
3217        prompt_store::init(cx);
3218        LanguageModelRegistry::test(cx);
3219        cx.set_global(settings_store);
3220        language::init(cx);
3221        agent_settings::init(cx);
3222        Project::init_settings(cx);
3223        theme::init(theme::LoadThemes::JustBase, cx);
3224        workspace::init_settings(cx);
3225        editor::init_settings(cx);
3226    }
3227}