text_thread_editor.rs

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