text_thread_editor.rs

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