text_thread_editor.rs

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