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, SearchToken, 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 model_id = model.id().0.to_string();
 323                                settings.agent.get_or_insert_default().set_model(
 324                                    LanguageModelSelection {
 325                                        provider: LanguageModelProviderSetting(provider),
 326                                        model: model_id,
 327                                        enable_thinking: model.supports_thinking(),
 328                                        effort: model
 329                                            .default_effort_level()
 330                                            .map(|effort| effort.value.to_string()),
 331                                    },
 332                                )
 333                            });
 334                        }
 335                    },
 336                    {
 337                        let fs = fs.clone();
 338                        move |model, should_be_favorite, cx| {
 339                            crate::favorite_models::toggle_in_settings(
 340                                model,
 341                                should_be_favorite,
 342                                fs.clone(),
 343                                cx,
 344                            );
 345                        }
 346                    },
 347                    true, // Use popover styles for picker
 348                    focus_handle,
 349                    window,
 350                    cx,
 351                )
 352            }),
 353            language_model_selector_menu_handle: PopoverMenuHandle::default(),
 354        };
 355        this.update_message_headers(cx);
 356        this.update_image_blocks(cx);
 357        this.insert_slash_command_output_sections(slash_command_sections, false, window, cx);
 358        this.insert_thought_process_output_sections(
 359            thought_process_sections
 360                .into_iter()
 361                .map(|section| (section, ThoughtProcessStatus::Completed)),
 362            window,
 363            cx,
 364        );
 365        this
 366    }
 367
 368    fn settings_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 369        self.editor.update(cx, |editor, cx| {
 370            let show_edit_predictions = all_language_settings(None, cx)
 371                .edit_predictions
 372                .enabled_in_text_threads;
 373
 374            editor.set_show_edit_predictions(Some(show_edit_predictions), window, cx);
 375        });
 376    }
 377
 378    pub fn text_thread(&self) -> &Entity<TextThread> {
 379        &self.text_thread
 380    }
 381
 382    pub fn editor(&self) -> &Entity<Editor> {
 383        &self.editor
 384    }
 385
 386    pub fn insert_default_prompt(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 387        let command_name = DefaultSlashCommand.name();
 388        self.editor.update(cx, |editor, cx| {
 389            editor.insert(&format!("/{command_name}\n\n"), window, cx)
 390        });
 391        let command = self.text_thread.update(cx, |text_thread, cx| {
 392            text_thread.reparse(cx);
 393            text_thread.parsed_slash_commands()[0].clone()
 394        });
 395        self.run_command(
 396            command.source_range,
 397            &command.name,
 398            &command.arguments,
 399            false,
 400            self.workspace.clone(),
 401            window,
 402            cx,
 403        );
 404    }
 405
 406    fn assist(&mut self, _: &Assist, window: &mut Window, cx: &mut Context<Self>) {
 407        if self.sending_disabled(cx) {
 408            return;
 409        }
 410        telemetry::event!("Agent Message Sent", agent = "zed-text");
 411        self.send_to_model(window, cx);
 412    }
 413
 414    fn send_to_model(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 415        self.last_error = None;
 416        if let Some(user_message) = self
 417            .text_thread
 418            .update(cx, |text_thread, cx| text_thread.assist(cx))
 419        {
 420            let new_selection = {
 421                let cursor = user_message
 422                    .start
 423                    .to_offset(self.text_thread.read(cx).buffer().read(cx));
 424                MultiBufferOffset(cursor)..MultiBufferOffset(cursor)
 425            };
 426            self.editor.update(cx, |editor, cx| {
 427                editor.change_selections(Default::default(), window, cx, |selections| {
 428                    selections.select_ranges([new_selection])
 429                });
 430            });
 431            // Avoid scrolling to the new cursor position so the assistant's output is stable.
 432            cx.defer_in(window, |this, _, _| this.scroll_position = None);
 433        }
 434
 435        cx.notify();
 436    }
 437
 438    fn cancel(
 439        &mut self,
 440        _: &editor::actions::Cancel,
 441        _window: &mut Window,
 442        cx: &mut Context<Self>,
 443    ) {
 444        self.last_error = None;
 445
 446        if self
 447            .text_thread
 448            .update(cx, |text_thread, cx| text_thread.cancel_last_assist(cx))
 449        {
 450            return;
 451        }
 452
 453        cx.propagate();
 454    }
 455
 456    fn cycle_message_role(
 457        &mut self,
 458        _: &CycleMessageRole,
 459        _window: &mut Window,
 460        cx: &mut Context<Self>,
 461    ) {
 462        let cursors = self.cursors(cx);
 463        self.text_thread.update(cx, |text_thread, cx| {
 464            let messages = text_thread
 465                .messages_for_offsets(cursors.into_iter().map(|cursor| cursor.0), cx)
 466                .into_iter()
 467                .map(|message| message.id)
 468                .collect();
 469            text_thread.cycle_message_roles(messages, cx)
 470        });
 471    }
 472
 473    fn cursors(&self, cx: &mut App) -> Vec<MultiBufferOffset> {
 474        let selections = self.editor.update(cx, |editor, cx| {
 475            editor
 476                .selections
 477                .all::<MultiBufferOffset>(&editor.display_snapshot(cx))
 478        });
 479        selections
 480            .into_iter()
 481            .map(|selection| selection.head())
 482            .collect()
 483    }
 484
 485    pub fn insert_command(&mut self, name: &str, window: &mut Window, cx: &mut Context<Self>) {
 486        if let Some(command) = self.slash_commands.command(name, cx) {
 487            self.editor.update(cx, |editor, cx| {
 488                editor.transact(window, cx, |editor, window, cx| {
 489                    editor.change_selections(Default::default(), window, cx, |s| s.try_cancel());
 490                    let snapshot = editor.buffer().read(cx).snapshot(cx);
 491                    let newest_cursor = editor
 492                        .selections
 493                        .newest::<Point>(&editor.display_snapshot(cx))
 494                        .head();
 495                    if newest_cursor.column > 0
 496                        || snapshot
 497                            .chars_at(newest_cursor)
 498                            .next()
 499                            .is_some_and(|ch| ch != '\n')
 500                    {
 501                        editor.move_to_end_of_line(
 502                            &MoveToEndOfLine {
 503                                stop_at_soft_wraps: false,
 504                            },
 505                            window,
 506                            cx,
 507                        );
 508                        editor.newline(&Newline, window, cx);
 509                    }
 510
 511                    editor.insert(&format!("/{name}"), window, cx);
 512                    if command.accepts_arguments() {
 513                        editor.insert(" ", window, cx);
 514                        editor.show_completions(&ShowCompletions, window, cx);
 515                    }
 516                });
 517            });
 518            if !command.requires_argument() {
 519                self.confirm_command(&ConfirmCommand, window, cx);
 520            }
 521        }
 522    }
 523
 524    pub fn confirm_command(
 525        &mut self,
 526        _: &ConfirmCommand,
 527        window: &mut Window,
 528        cx: &mut Context<Self>,
 529    ) {
 530        if self.editor.read(cx).has_visible_completions_menu() {
 531            return;
 532        }
 533
 534        let selections = self.editor.read(cx).selections.disjoint_anchors_arc();
 535        let mut commands_by_range = HashMap::default();
 536        let workspace = self.workspace.clone();
 537        self.text_thread.update(cx, |text_thread, cx| {
 538            text_thread.reparse(cx);
 539            for selection in selections.iter() {
 540                if let Some(command) =
 541                    text_thread.pending_command_for_position(selection.head().text_anchor, cx)
 542                {
 543                    commands_by_range
 544                        .entry(command.source_range.clone())
 545                        .or_insert_with(|| command.clone());
 546                }
 547            }
 548        });
 549
 550        if commands_by_range.is_empty() {
 551            cx.propagate();
 552        } else {
 553            for command in commands_by_range.into_values() {
 554                self.run_command(
 555                    command.source_range,
 556                    &command.name,
 557                    &command.arguments,
 558                    true,
 559                    workspace.clone(),
 560                    window,
 561                    cx,
 562                );
 563            }
 564            cx.stop_propagation();
 565        }
 566    }
 567
 568    pub fn run_command(
 569        &mut self,
 570        command_range: Range<language::Anchor>,
 571        name: &str,
 572        arguments: &[String],
 573        ensure_trailing_newline: bool,
 574        workspace: WeakEntity<Workspace>,
 575        window: &mut Window,
 576        cx: &mut Context<Self>,
 577    ) {
 578        if let Some(command) = self.slash_commands.command(name, cx) {
 579            let text_thread = self.text_thread.read(cx);
 580            let sections = text_thread
 581                .slash_command_output_sections()
 582                .iter()
 583                .filter(|section| section.is_valid(text_thread.buffer().read(cx)))
 584                .cloned()
 585                .collect::<Vec<_>>();
 586            let snapshot = text_thread.buffer().read(cx).snapshot();
 587            let output = command.run(
 588                arguments,
 589                &sections,
 590                snapshot,
 591                workspace,
 592                self.lsp_adapter_delegate.clone(),
 593                window,
 594                cx,
 595            );
 596            self.text_thread.update(cx, |text_thread, cx| {
 597                text_thread.insert_command_output(
 598                    command_range,
 599                    name,
 600                    output,
 601                    ensure_trailing_newline,
 602                    cx,
 603                )
 604            });
 605        }
 606    }
 607
 608    fn handle_text_thread_event(
 609        &mut self,
 610        _: &Entity<TextThread>,
 611        event: &TextThreadEvent,
 612        window: &mut Window,
 613        cx: &mut Context<Self>,
 614    ) {
 615        let text_thread_editor = cx.entity().downgrade();
 616
 617        match event {
 618            TextThreadEvent::MessagesEdited => {
 619                self.update_message_headers(cx);
 620                self.update_image_blocks(cx);
 621                self.text_thread.update(cx, |text_thread, cx| {
 622                    text_thread.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
 623                });
 624            }
 625            TextThreadEvent::SummaryChanged => {
 626                cx.emit(EditorEvent::TitleChanged);
 627                self.text_thread.update(cx, |text_thread, cx| {
 628                    text_thread.save(Some(Duration::from_millis(500)), self.fs.clone(), cx);
 629                });
 630            }
 631            TextThreadEvent::SummaryGenerated => {}
 632            TextThreadEvent::PathChanged { .. } => {}
 633            TextThreadEvent::StartedThoughtProcess(range) => {
 634                let creases = self.insert_thought_process_output_sections(
 635                    [(
 636                        ThoughtProcessOutputSection {
 637                            range: range.clone(),
 638                        },
 639                        ThoughtProcessStatus::Pending,
 640                    )],
 641                    window,
 642                    cx,
 643                );
 644                self.pending_thought_process = Some((creases[0], range.start));
 645            }
 646            TextThreadEvent::EndedThoughtProcess(end) => {
 647                if let Some((crease_id, start)) = self.pending_thought_process.take() {
 648                    self.editor.update(cx, |editor, cx| {
 649                        let multi_buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
 650                        let start_anchor =
 651                            multi_buffer_snapshot.as_singleton_anchor(start).unwrap();
 652
 653                        editor.display_map.update(cx, |display_map, cx| {
 654                            display_map.unfold_intersecting(
 655                                vec![start_anchor..start_anchor],
 656                                true,
 657                                cx,
 658                            );
 659                        });
 660                        editor.remove_creases(vec![crease_id], cx);
 661                    });
 662                    self.insert_thought_process_output_sections(
 663                        [(
 664                            ThoughtProcessOutputSection { range: start..*end },
 665                            ThoughtProcessStatus::Completed,
 666                        )],
 667                        window,
 668                        cx,
 669                    );
 670                }
 671            }
 672            TextThreadEvent::StreamedCompletion => {
 673                self.editor.update(cx, |editor, cx| {
 674                    if let Some(scroll_position) = self.scroll_position {
 675                        let snapshot = editor.snapshot(window, cx);
 676                        let cursor_point = scroll_position.cursor.to_display_point(&snapshot);
 677                        let scroll_top =
 678                            cursor_point.row().as_f64() - scroll_position.offset_before_cursor.y;
 679                        editor.set_scroll_position(
 680                            point(scroll_position.offset_before_cursor.x, scroll_top),
 681                            window,
 682                            cx,
 683                        );
 684                    }
 685                });
 686            }
 687            TextThreadEvent::ParsedSlashCommandsUpdated { removed, updated } => {
 688                self.editor.update(cx, |editor, cx| {
 689                    let buffer = editor.buffer().read(cx).snapshot(cx);
 690                    let (excerpt_id, _, _) = buffer.as_singleton().unwrap();
 691
 692                    editor.remove_creases(
 693                        removed
 694                            .iter()
 695                            .filter_map(|range| self.pending_slash_command_creases.remove(range)),
 696                        cx,
 697                    );
 698
 699                    let crease_ids = editor.insert_creases(
 700                        updated.iter().map(|command| {
 701                            let workspace = self.workspace.clone();
 702                            let confirm_command = Arc::new({
 703                                let text_thread_editor = text_thread_editor.clone();
 704                                let command = command.clone();
 705                                move |window: &mut Window, cx: &mut App| {
 706                                    text_thread_editor
 707                                        .update(cx, |text_thread_editor, cx| {
 708                                            text_thread_editor.run_command(
 709                                                command.source_range.clone(),
 710                                                &command.name,
 711                                                &command.arguments,
 712                                                false,
 713                                                workspace.clone(),
 714                                                window,
 715                                                cx,
 716                                            );
 717                                        })
 718                                        .ok();
 719                                }
 720                            });
 721                            let placeholder = FoldPlaceholder {
 722                                render: Arc::new(move |_, _, _| Empty.into_any()),
 723                                ..Default::default()
 724                            };
 725                            let render_toggle = {
 726                                let confirm_command = confirm_command.clone();
 727                                let command = command.clone();
 728                                move |row, _, _, _window: &mut Window, _cx: &mut App| {
 729                                    render_pending_slash_command_gutter_decoration(
 730                                        row,
 731                                        &command.status,
 732                                        confirm_command.clone(),
 733                                    )
 734                                }
 735                            };
 736                            let render_trailer = {
 737                                move |_row, _unfold, _window: &mut Window, _cx: &mut App| {
 738                                    Empty.into_any()
 739                                }
 740                            };
 741
 742                            let range = buffer
 743                                .anchor_range_in_excerpt(excerpt_id, command.source_range.clone())
 744                                .unwrap();
 745                            Crease::inline(range, placeholder, render_toggle, render_trailer)
 746                        }),
 747                        cx,
 748                    );
 749
 750                    self.pending_slash_command_creases.extend(
 751                        updated
 752                            .iter()
 753                            .map(|command| command.source_range.clone())
 754                            .zip(crease_ids),
 755                    );
 756                })
 757            }
 758            TextThreadEvent::InvokedSlashCommandChanged { command_id } => {
 759                self.update_invoked_slash_command(*command_id, window, cx);
 760            }
 761            TextThreadEvent::SlashCommandOutputSectionAdded { section } => {
 762                self.insert_slash_command_output_sections([section.clone()], false, window, cx);
 763            }
 764            TextThreadEvent::Operation(_) => {}
 765            TextThreadEvent::ShowAssistError(error_message) => {
 766                self.last_error = Some(AssistError::Message(error_message.clone()));
 767            }
 768            TextThreadEvent::ShowPaymentRequiredError => {
 769                self.last_error = Some(AssistError::PaymentRequired);
 770            }
 771        }
 772    }
 773
 774    fn update_invoked_slash_command(
 775        &mut self,
 776        command_id: InvokedSlashCommandId,
 777        window: &mut Window,
 778        cx: &mut Context<Self>,
 779    ) {
 780        if let Some(invoked_slash_command) =
 781            self.text_thread.read(cx).invoked_slash_command(&command_id)
 782            && let InvokedSlashCommandStatus::Finished = invoked_slash_command.status
 783        {
 784            let run_commands_in_ranges = invoked_slash_command.run_commands_in_ranges.clone();
 785            for range in run_commands_in_ranges {
 786                let commands = self.text_thread.update(cx, |text_thread, cx| {
 787                    text_thread.reparse(cx);
 788                    text_thread
 789                        .pending_commands_for_range(range.clone(), cx)
 790                        .to_vec()
 791                });
 792
 793                for command in commands {
 794                    self.run_command(
 795                        command.source_range,
 796                        &command.name,
 797                        &command.arguments,
 798                        false,
 799                        self.workspace.clone(),
 800                        window,
 801                        cx,
 802                    );
 803                }
 804            }
 805        }
 806
 807        self.editor.update(cx, |editor, cx| {
 808            if let Some(invoked_slash_command) =
 809                self.text_thread.read(cx).invoked_slash_command(&command_id)
 810            {
 811                if let InvokedSlashCommandStatus::Finished = invoked_slash_command.status {
 812                    let buffer = editor.buffer().read(cx).snapshot(cx);
 813                    let (excerpt_id, _buffer_id, _buffer_snapshot) = buffer.as_singleton().unwrap();
 814
 815                    let range = buffer
 816                        .anchor_range_in_excerpt(excerpt_id, invoked_slash_command.range.clone())
 817                        .unwrap();
 818                    editor.remove_folds_with_type(
 819                        &[range],
 820                        TypeId::of::<PendingSlashCommand>(),
 821                        false,
 822                        cx,
 823                    );
 824
 825                    editor.remove_creases(
 826                        HashSet::from_iter(self.invoked_slash_command_creases.remove(&command_id)),
 827                        cx,
 828                    );
 829                } else if let hash_map::Entry::Vacant(entry) =
 830                    self.invoked_slash_command_creases.entry(command_id)
 831                {
 832                    let buffer = editor.buffer().read(cx).snapshot(cx);
 833                    let (excerpt_id, _buffer_id, _buffer_snapshot) = 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::ZedAgent.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                                        .start_icon(
1195                                            Icon::new(IconName::XCircle)
1196                                                .size(IconSize::XSmall)
1197                                                .color(Color::Error),
1198                                        )
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, ThreadView 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                    .map(|s| {
1513                        let (start, end) = if s.is_empty() {
1514                            let row = multi_buffer::MultiBufferRow(s.start.row);
1515                            let line_start = text::Point::new(s.start.row, 0);
1516                            let line_end = text::Point::new(s.start.row, snapshot.line_len(row));
1517                            (line_start, line_end)
1518                        } else {
1519                            (s.start, s.end)
1520                        };
1521                        snapshot.anchor_after(start)..snapshot.anchor_before(end)
1522                    })
1523                    .collect::<Vec<_>>()
1524            });
1525            Some((selections, buffer))
1526        }) {
1527            agent_panel_delegate.quote_selection(workspace, selections, buffer, window, cx);
1528        }
1529    }
1530
1531    pub fn quote_ranges(
1532        &mut self,
1533        ranges: Vec<Range<Point>>,
1534        snapshot: MultiBufferSnapshot,
1535        window: &mut Window,
1536        cx: &mut Context<Self>,
1537    ) {
1538        let creases = selections_creases(ranges, snapshot, cx);
1539
1540        self.editor.update(cx, |editor, cx| {
1541            editor.insert("\n", window, cx);
1542            for (text, crease_title) in creases {
1543                let point = editor
1544                    .selections
1545                    .newest::<Point>(&editor.display_snapshot(cx))
1546                    .head();
1547                let start_row = MultiBufferRow(point.row);
1548
1549                editor.insert(&text, window, cx);
1550
1551                let snapshot = editor.buffer().read(cx).snapshot(cx);
1552                let anchor_before = snapshot.anchor_after(point);
1553                let anchor_after = editor
1554                    .selections
1555                    .newest_anchor()
1556                    .head()
1557                    .bias_left(&snapshot);
1558
1559                editor.insert("\n", window, cx);
1560
1561                let fold_placeholder =
1562                    quote_selection_fold_placeholder(crease_title, cx.entity().downgrade());
1563                let crease = Crease::inline(
1564                    anchor_before..anchor_after,
1565                    fold_placeholder,
1566                    render_quote_selection_output_toggle,
1567                    |_, _, _, _| Empty.into_any(),
1568                );
1569                editor.insert_creases(vec![crease], cx);
1570                editor.fold_at(start_row, window, cx);
1571            }
1572        })
1573    }
1574
1575    pub fn quote_terminal_text(
1576        &mut self,
1577        text: String,
1578        window: &mut Window,
1579        cx: &mut Context<Self>,
1580    ) {
1581        let crease_title = "terminal".to_string();
1582        let formatted_text = format!("```console\n{}\n```\n", text);
1583
1584        self.editor.update(cx, |editor, cx| {
1585            // Insert newline first if not at the start of a line
1586            let point = editor
1587                .selections
1588                .newest::<Point>(&editor.display_snapshot(cx))
1589                .head();
1590            if point.column > 0 {
1591                editor.insert("\n", window, cx);
1592            }
1593
1594            let point = editor
1595                .selections
1596                .newest::<Point>(&editor.display_snapshot(cx))
1597                .head();
1598            let start_row = MultiBufferRow(point.row);
1599
1600            editor.insert(&formatted_text, window, cx);
1601
1602            let snapshot = editor.buffer().read(cx).snapshot(cx);
1603            let anchor_before = snapshot.anchor_after(point);
1604            let anchor_after = editor
1605                .selections
1606                .newest_anchor()
1607                .head()
1608                .bias_left(&snapshot);
1609
1610            let fold_placeholder =
1611                quote_selection_fold_placeholder(crease_title, cx.entity().downgrade());
1612            let crease = Crease::inline(
1613                anchor_before..anchor_after,
1614                fold_placeholder,
1615                render_quote_selection_output_toggle,
1616                |_, _, _, _| Empty.into_any(),
1617            );
1618            editor.insert_creases(vec![crease], cx);
1619            editor.fold_at(start_row, window, cx);
1620        })
1621    }
1622
1623    fn copy(&mut self, _: &editor::actions::Copy, _window: &mut Window, cx: &mut Context<Self>) {
1624        if self.editor.read(cx).selections.count() == 1 {
1625            let (copied_text, metadata, _) = self.get_clipboard_contents(cx);
1626            cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1627                copied_text,
1628                metadata,
1629            ));
1630            cx.stop_propagation();
1631            return;
1632        }
1633
1634        cx.propagate();
1635    }
1636
1637    fn cut(&mut self, _: &editor::actions::Cut, window: &mut Window, cx: &mut Context<Self>) {
1638        if self.editor.read(cx).selections.count() == 1 {
1639            let (copied_text, metadata, selections) = self.get_clipboard_contents(cx);
1640
1641            self.editor.update(cx, |editor, cx| {
1642                editor.transact(window, cx, |this, window, cx| {
1643                    this.change_selections(Default::default(), window, cx, |s| {
1644                        s.select(selections);
1645                    });
1646                    this.insert("", window, cx);
1647                    cx.write_to_clipboard(ClipboardItem::new_string_with_json_metadata(
1648                        copied_text,
1649                        metadata,
1650                    ));
1651                });
1652            });
1653
1654            cx.stop_propagation();
1655            return;
1656        }
1657
1658        cx.propagate();
1659    }
1660
1661    fn get_clipboard_contents(
1662        &mut self,
1663        cx: &mut Context<Self>,
1664    ) -> (
1665        String,
1666        CopyMetadata,
1667        Vec<text::Selection<MultiBufferOffset>>,
1668    ) {
1669        let (mut selection, creases) = self.editor.update(cx, |editor, cx| {
1670            let mut selection = editor
1671                .selections
1672                .newest_adjusted(&editor.display_snapshot(cx));
1673            let snapshot = editor.buffer().read(cx).snapshot(cx);
1674
1675            selection.goal = SelectionGoal::None;
1676
1677            let selection_start = snapshot.point_to_offset(selection.start);
1678
1679            (
1680                selection.map(|point| snapshot.point_to_offset(point)),
1681                editor.display_map.update(cx, |display_map, cx| {
1682                    display_map
1683                        .snapshot(cx)
1684                        .crease_snapshot
1685                        .creases_in_range(
1686                            MultiBufferRow(selection.start.row)
1687                                ..MultiBufferRow(selection.end.row + 1),
1688                            &snapshot,
1689                        )
1690                        .filter_map(|crease| {
1691                            if let Crease::Inline {
1692                                range, metadata, ..
1693                            } = &crease
1694                            {
1695                                let metadata = metadata.as_ref()?;
1696                                let start = range
1697                                    .start
1698                                    .to_offset(&snapshot)
1699                                    .saturating_sub(selection_start);
1700                                let end = range
1701                                    .end
1702                                    .to_offset(&snapshot)
1703                                    .saturating_sub(selection_start);
1704
1705                                let range_relative_to_selection = start..end;
1706                                if !range_relative_to_selection.is_empty() {
1707                                    return Some(SelectedCreaseMetadata {
1708                                        range_relative_to_selection,
1709                                        crease: metadata.clone(),
1710                                    });
1711                                }
1712                            }
1713                            None
1714                        })
1715                        .collect::<Vec<_>>()
1716                }),
1717            )
1718        });
1719
1720        let text_thread = self.text_thread.read(cx);
1721
1722        let mut text = String::new();
1723
1724        // If selection is empty, we want to copy the entire line
1725        if selection.range().is_empty() {
1726            let snapshot = self.editor.read(cx).buffer().read(cx).snapshot(cx);
1727            let point = snapshot.offset_to_point(selection.range().start);
1728            selection.start = snapshot.point_to_offset(Point::new(point.row, 0));
1729            selection.end = snapshot
1730                .point_to_offset(cmp::min(Point::new(point.row + 1, 0), snapshot.max_point()));
1731            for chunk in snapshot.text_for_range(selection.range()) {
1732                text.push_str(chunk);
1733            }
1734        } else {
1735            for message in text_thread.messages(cx) {
1736                if message.offset_range.start >= selection.range().end.0 {
1737                    break;
1738                } else if message.offset_range.end >= selection.range().start.0 {
1739                    let range = cmp::max(message.offset_range.start, selection.range().start.0)
1740                        ..cmp::min(message.offset_range.end, selection.range().end.0);
1741                    if !range.is_empty() {
1742                        for chunk in text_thread.buffer().read(cx).text_for_range(range) {
1743                            text.push_str(chunk);
1744                        }
1745                        if message.offset_range.end < selection.range().end.0 {
1746                            text.push('\n');
1747                        }
1748                    }
1749                }
1750            }
1751        }
1752        (text, CopyMetadata { creases }, vec![selection])
1753    }
1754
1755    fn paste(
1756        &mut self,
1757        action: &editor::actions::Paste,
1758        window: &mut Window,
1759        cx: &mut Context<Self>,
1760    ) {
1761        let Some(workspace) = self.workspace.upgrade() else {
1762            return;
1763        };
1764        let editor_clipboard_selections = cx.read_from_clipboard().and_then(|item| {
1765            item.entries().iter().find_map(|entry| match entry {
1766                ClipboardEntry::String(text) => {
1767                    text.metadata_json::<Vec<editor::ClipboardSelection>>()
1768                }
1769                _ => None,
1770            })
1771        });
1772
1773        // Insert creases for pasted clipboard selections that:
1774        // 1. Contain exactly one selection
1775        // 2. Have an associated file path
1776        // 3. Span multiple lines (not single-line selections)
1777        // 4. Belong to a file that exists in the current project
1778        let should_insert_creases = util::maybe!({
1779            let selections = editor_clipboard_selections.as_ref()?;
1780            if selections.len() > 1 {
1781                return Some(false);
1782            }
1783            let selection = selections.first()?;
1784            let file_path = selection.file_path.as_ref()?;
1785            let line_range = selection.line_range.as_ref()?;
1786
1787            if line_range.start() == line_range.end() {
1788                return Some(false);
1789            }
1790
1791            Some(
1792                workspace
1793                    .read(cx)
1794                    .project()
1795                    .read(cx)
1796                    .project_path_for_absolute_path(file_path, cx)
1797                    .is_some(),
1798            )
1799        })
1800        .unwrap_or(false);
1801
1802        if should_insert_creases && let Some(clipboard_item) = cx.read_from_clipboard() {
1803            let clipboard_text = clipboard_item
1804                .entries()
1805                .iter()
1806                .find_map(|entry| match entry {
1807                    ClipboardEntry::String(s) => Some(s),
1808                    _ => None,
1809                });
1810            if let Some(clipboard_text) = clipboard_text {
1811                if let Some(selections) = editor_clipboard_selections {
1812                    cx.stop_propagation();
1813
1814                    let text = clipboard_text.text();
1815                    self.editor.update(cx, |editor, cx| {
1816                        let mut current_offset = 0;
1817                        let weak_editor = cx.entity().downgrade();
1818
1819                        for selection in selections {
1820                            if let (Some(file_path), Some(line_range)) =
1821                                (selection.file_path, selection.line_range)
1822                            {
1823                                let selected_text =
1824                                    &text[current_offset..current_offset + selection.len];
1825                                let fence = assistant_slash_commands::codeblock_fence_for_path(
1826                                    file_path.to_str(),
1827                                    Some(line_range.clone()),
1828                                );
1829                                let formatted_text = format!("{fence}{selected_text}\n```");
1830
1831                                let insert_point = editor
1832                                    .selections
1833                                    .newest::<Point>(&editor.display_snapshot(cx))
1834                                    .head();
1835                                let start_row = MultiBufferRow(insert_point.row);
1836
1837                                editor.insert(&formatted_text, window, cx);
1838
1839                                let snapshot = editor.buffer().read(cx).snapshot(cx);
1840                                let anchor_before = snapshot.anchor_after(insert_point);
1841                                let anchor_after = editor
1842                                    .selections
1843                                    .newest_anchor()
1844                                    .head()
1845                                    .bias_left(&snapshot);
1846
1847                                editor.insert("\n", window, cx);
1848
1849                                let crease_text = acp_thread::selection_name(
1850                                    Some(file_path.as_ref()),
1851                                    &line_range,
1852                                );
1853
1854                                let fold_placeholder = quote_selection_fold_placeholder(
1855                                    crease_text,
1856                                    weak_editor.clone(),
1857                                );
1858                                let crease = Crease::inline(
1859                                    anchor_before..anchor_after,
1860                                    fold_placeholder,
1861                                    render_quote_selection_output_toggle,
1862                                    |_, _, _, _| Empty.into_any(),
1863                                );
1864                                editor.insert_creases(vec![crease], cx);
1865                                editor.fold_at(start_row, window, cx);
1866
1867                                current_offset += selection.len;
1868                                if !selection.is_entire_line && current_offset < text.len() {
1869                                    current_offset += 1;
1870                                }
1871                            }
1872                        }
1873                    });
1874                    return;
1875                }
1876            }
1877        }
1878
1879        cx.stop_propagation();
1880
1881        let clipboard_item = cx.read_from_clipboard();
1882
1883        let mut images: Vec<gpui::Image> = Vec::new();
1884        let mut paths: Vec<std::path::PathBuf> = Vec::new();
1885        let mut metadata: Option<CopyMetadata> = None;
1886
1887        if let Some(item) = &clipboard_item {
1888            for entry in item.entries() {
1889                match entry {
1890                    ClipboardEntry::Image(image) => images.push(image.clone()),
1891                    ClipboardEntry::ExternalPaths(external) => {
1892                        paths.extend(external.paths().iter().cloned());
1893                    }
1894                    ClipboardEntry::String(text) => {
1895                        if metadata.is_none() {
1896                            metadata = text.metadata_json::<CopyMetadata>();
1897                        }
1898                    }
1899                }
1900            }
1901        }
1902
1903        for path in paths {
1904            let Ok(content) = std::fs::read(path) else {
1905                continue;
1906            };
1907            let Ok(format) = image::guess_format(&content) else {
1908                continue;
1909            };
1910            images.push(gpui::Image::from_bytes(
1911                match format {
1912                    image::ImageFormat::Png => gpui::ImageFormat::Png,
1913                    image::ImageFormat::Jpeg => gpui::ImageFormat::Jpeg,
1914                    image::ImageFormat::WebP => gpui::ImageFormat::Webp,
1915                    image::ImageFormat::Gif => gpui::ImageFormat::Gif,
1916                    image::ImageFormat::Bmp => gpui::ImageFormat::Bmp,
1917                    image::ImageFormat::Tiff => gpui::ImageFormat::Tiff,
1918                    image::ImageFormat::Ico => gpui::ImageFormat::Ico,
1919                    _ => continue,
1920                },
1921                content,
1922            ));
1923        }
1924
1925        // Respect entry priority order — if the first entry is text, the source
1926        // application considers text the primary content. Discard collected images
1927        // so the text-paste branch runs instead.
1928        if clipboard_item
1929            .as_ref()
1930            .and_then(|item| item.entries().first())
1931            .is_some_and(|entry| matches!(entry, ClipboardEntry::String(_)))
1932        {
1933            images.clear();
1934        }
1935
1936        if images.is_empty() {
1937            self.editor.update(cx, |editor, cx| {
1938                let paste_position = editor
1939                    .selections
1940                    .newest::<MultiBufferOffset>(&editor.display_snapshot(cx))
1941                    .head();
1942                editor.paste(action, window, cx);
1943
1944                if let Some(metadata) = metadata {
1945                    let buffer = editor.buffer().read(cx).snapshot(cx);
1946
1947                    let mut buffer_rows_to_fold = BTreeSet::new();
1948                    let weak_editor = cx.entity().downgrade();
1949                    editor.insert_creases(
1950                        metadata.creases.into_iter().map(|metadata| {
1951                            let start = buffer.anchor_after(
1952                                paste_position + metadata.range_relative_to_selection.start,
1953                            );
1954                            let end = buffer.anchor_before(
1955                                paste_position + metadata.range_relative_to_selection.end,
1956                            );
1957
1958                            let buffer_row = MultiBufferRow(start.to_point(&buffer).row);
1959                            buffer_rows_to_fold.insert(buffer_row);
1960                            Crease::inline(
1961                                start..end,
1962                                FoldPlaceholder {
1963                                    render: render_fold_icon_button(
1964                                        weak_editor.clone(),
1965                                        metadata.crease.icon_path.clone(),
1966                                        metadata.crease.label.clone(),
1967                                    ),
1968                                    ..Default::default()
1969                                },
1970                                render_slash_command_output_toggle,
1971                                |_, _, _, _| Empty.into_any(),
1972                            )
1973                            .with_metadata(metadata.crease)
1974                        }),
1975                        cx,
1976                    );
1977                    for buffer_row in buffer_rows_to_fold.into_iter().rev() {
1978                        editor.fold_at(buffer_row, window, cx);
1979                    }
1980                }
1981            });
1982        } else {
1983            let mut image_positions = Vec::new();
1984            self.editor.update(cx, |editor, cx| {
1985                editor.transact(window, cx, |editor, _window, cx| {
1986                    let edits = editor
1987                        .selections
1988                        .all::<MultiBufferOffset>(&editor.display_snapshot(cx))
1989                        .into_iter()
1990                        .map(|selection| (selection.start..selection.end, "\n"));
1991                    editor.edit(edits, cx);
1992
1993                    let snapshot = editor.buffer().read(cx).snapshot(cx);
1994                    for selection in editor
1995                        .selections
1996                        .all::<MultiBufferOffset>(&editor.display_snapshot(cx))
1997                    {
1998                        image_positions.push(snapshot.anchor_before(selection.end));
1999                    }
2000                });
2001            });
2002
2003            self.text_thread.update(cx, |text_thread, cx| {
2004                for image in images {
2005                    let Some(render_image) = image.to_image_data(cx.svg_renderer()).log_err()
2006                    else {
2007                        continue;
2008                    };
2009                    let image_id = image.id();
2010                    let image_task = LanguageModelImage::from_image(Arc::new(image), cx).shared();
2011
2012                    for image_position in image_positions.iter() {
2013                        text_thread.insert_content(
2014                            Content::Image {
2015                                anchor: image_position.text_anchor,
2016                                image_id,
2017                                image: image_task.clone(),
2018                                render_image: render_image.clone(),
2019                            },
2020                            cx,
2021                        );
2022                    }
2023                }
2024            });
2025        }
2026    }
2027
2028    fn paste_raw(&mut self, _: &PasteRaw, window: &mut Window, cx: &mut Context<Self>) {
2029        self.editor.update(cx, |editor, cx| {
2030            editor.paste(&editor::actions::Paste, window, cx);
2031        });
2032    }
2033
2034    fn update_image_blocks(&mut self, cx: &mut Context<Self>) {
2035        self.editor.update(cx, |editor, cx| {
2036            let buffer = editor.buffer().read(cx).snapshot(cx);
2037            let excerpt_id = buffer.as_singleton().unwrap().0;
2038            let old_blocks = std::mem::take(&mut self.image_blocks);
2039            let new_blocks = self
2040                .text_thread
2041                .read(cx)
2042                .contents(cx)
2043                .map(
2044                    |Content::Image {
2045                         anchor,
2046                         render_image,
2047                         ..
2048                     }| (anchor, render_image),
2049                )
2050                .filter_map(|(anchor, render_image)| {
2051                    const MAX_HEIGHT_IN_LINES: u32 = 8;
2052                    let anchor = buffer.anchor_in_excerpt(excerpt_id, anchor).unwrap();
2053                    let image = render_image;
2054                    anchor.is_valid(&buffer).then(|| BlockProperties {
2055                        placement: BlockPlacement::Above(anchor),
2056                        height: Some(MAX_HEIGHT_IN_LINES),
2057                        style: BlockStyle::Sticky,
2058                        render: Arc::new(move |cx| {
2059                            let image_size = size_for_image(
2060                                &image,
2061                                size(
2062                                    cx.max_width - cx.margins.gutter.full_width(),
2063                                    MAX_HEIGHT_IN_LINES as f32 * cx.line_height,
2064                                ),
2065                            );
2066                            h_flex()
2067                                .pl(cx.margins.gutter.full_width())
2068                                .child(
2069                                    img(image.clone())
2070                                        .object_fit(gpui::ObjectFit::ScaleDown)
2071                                        .w(image_size.width)
2072                                        .h(image_size.height),
2073                                )
2074                                .into_any_element()
2075                        }),
2076                        priority: 0,
2077                    })
2078                })
2079                .collect::<Vec<_>>();
2080
2081            editor.remove_blocks(old_blocks, None, cx);
2082            let ids = editor.insert_blocks(new_blocks, None, cx);
2083            self.image_blocks = HashSet::from_iter(ids);
2084        });
2085    }
2086
2087    fn split(&mut self, _: &Split, _window: &mut Window, cx: &mut Context<Self>) {
2088        self.text_thread.update(cx, |text_thread, cx| {
2089            let selections = self.editor.read(cx).selections.disjoint_anchors_arc();
2090            for selection in selections.as_ref() {
2091                let buffer = self.editor.read(cx).buffer().read(cx).snapshot(cx);
2092                let range = selection
2093                    .map(|endpoint| endpoint.to_offset(&buffer))
2094                    .range();
2095                text_thread.split_message(range.start.0..range.end.0, cx);
2096            }
2097        });
2098    }
2099
2100    fn save(&mut self, _: &Save, _window: &mut Window, cx: &mut Context<Self>) {
2101        self.text_thread.update(cx, |text_thread, cx| {
2102            text_thread.save(Some(Duration::from_millis(500)), self.fs.clone(), cx)
2103        });
2104    }
2105
2106    pub fn title(&self, cx: &App) -> SharedString {
2107        self.text_thread.read(cx).summary().or_default()
2108    }
2109
2110    pub fn regenerate_summary(&mut self, cx: &mut Context<Self>) {
2111        self.text_thread
2112            .update(cx, |text_thread, cx| text_thread.summarize(true, cx));
2113    }
2114
2115    fn render_remaining_tokens(&self, cx: &App) -> Option<impl IntoElement + use<>> {
2116        let (token_count_color, token_count, max_token_count, tooltip) =
2117            match token_state(&self.text_thread, cx)? {
2118                TokenState::NoTokensLeft {
2119                    max_token_count,
2120                    token_count,
2121                } => (
2122                    Color::Error,
2123                    token_count,
2124                    max_token_count,
2125                    Some("Token Limit Reached"),
2126                ),
2127                TokenState::HasMoreTokens {
2128                    max_token_count,
2129                    token_count,
2130                    over_warn_threshold,
2131                } => {
2132                    let (color, tooltip) = if over_warn_threshold {
2133                        (Color::Warning, Some("Token Limit is Close to Exhaustion"))
2134                    } else {
2135                        (Color::Muted, None)
2136                    };
2137                    (color, token_count, max_token_count, tooltip)
2138                }
2139            };
2140
2141        Some(
2142            h_flex()
2143                .id("token-count")
2144                .gap_0p5()
2145                .child(
2146                    Label::new(humanize_token_count(token_count))
2147                        .size(LabelSize::Small)
2148                        .color(token_count_color),
2149                )
2150                .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
2151                .child(
2152                    Label::new(humanize_token_count(max_token_count))
2153                        .size(LabelSize::Small)
2154                        .color(Color::Muted),
2155                )
2156                .when_some(tooltip, |element, tooltip| {
2157                    element.tooltip(Tooltip::text(tooltip))
2158                }),
2159        )
2160    }
2161
2162    fn render_send_button(&self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2163        let focus_handle = self.focus_handle(cx);
2164
2165        let (style, tooltip) = match token_state(&self.text_thread, cx) {
2166            Some(TokenState::NoTokensLeft { .. }) => (
2167                ButtonStyle::Tinted(TintColor::Error),
2168                Some(Tooltip::text("Token limit reached")(window, cx)),
2169            ),
2170            Some(TokenState::HasMoreTokens {
2171                over_warn_threshold,
2172                ..
2173            }) => {
2174                let (style, tooltip) = if over_warn_threshold {
2175                    (
2176                        ButtonStyle::Tinted(TintColor::Warning),
2177                        Some(Tooltip::text("Token limit is close to exhaustion")(
2178                            window, cx,
2179                        )),
2180                    )
2181                } else {
2182                    (ButtonStyle::Filled, None)
2183                };
2184                (style, tooltip)
2185            }
2186            None => (ButtonStyle::Filled, None),
2187        };
2188
2189        Button::new("send_button", "Send")
2190            .label_size(LabelSize::Small)
2191            .disabled(self.sending_disabled(cx))
2192            .style(style)
2193            .when_some(tooltip, |button, tooltip| {
2194                button.tooltip(move |_, _| tooltip.clone())
2195            })
2196            .layer(ElevationIndex::ModalSurface)
2197            .key_binding(
2198                KeyBinding::for_action_in(&Assist, &focus_handle, cx)
2199                    .map(|kb| kb.size(rems_from_px(12.))),
2200            )
2201            .on_click(move |_event, window, cx| {
2202                focus_handle.dispatch_action(&Assist, window, cx);
2203            })
2204    }
2205
2206    /// Whether or not we should allow messages to be sent.
2207    /// Will return false if the selected provided has a configuration error or
2208    /// if the user has not accepted the terms of service for this provider.
2209    fn sending_disabled(&self, cx: &mut Context<'_, TextThreadEditor>) -> bool {
2210        let model_registry = LanguageModelRegistry::read_global(cx);
2211        let Some(configuration_error) =
2212            model_registry.configuration_error(model_registry.default_model(), cx)
2213        else {
2214            return false;
2215        };
2216
2217        match configuration_error {
2218            ConfigurationError::NoProvider
2219            | ConfigurationError::ModelNotFound
2220            | ConfigurationError::ProviderNotAuthenticated(_) => true,
2221        }
2222    }
2223
2224    fn render_inject_context_menu(&self, cx: &mut Context<Self>) -> impl IntoElement {
2225        slash_command_picker::SlashCommandSelector::new(
2226            self.slash_commands.clone(),
2227            cx.entity().downgrade(),
2228            IconButton::new("trigger", IconName::Plus)
2229                .icon_size(IconSize::Small)
2230                .icon_color(Color::Muted)
2231                .selected_icon_color(Color::Accent)
2232                .selected_style(ButtonStyle::Filled),
2233            move |_window, cx| {
2234                Tooltip::with_meta("Add Context", None, "Type / to insert via keyboard", cx)
2235            },
2236        )
2237    }
2238
2239    fn render_language_model_selector(
2240        &self,
2241        window: &mut Window,
2242        cx: &mut Context<Self>,
2243    ) -> impl IntoElement {
2244        let active_model = LanguageModelRegistry::read_global(cx)
2245            .default_model()
2246            .map(|default| default.model);
2247        let model_name = match active_model {
2248            Some(model) => model.name().0,
2249            None => SharedString::from("Select Model"),
2250        };
2251
2252        let active_provider = LanguageModelRegistry::read_global(cx)
2253            .default_model()
2254            .map(|default| default.provider);
2255
2256        let provider_icon = active_provider
2257            .as_ref()
2258            .map(|p| p.icon())
2259            .unwrap_or(IconOrSvg::Icon(IconName::ZedAgent));
2260
2261        let (color, icon) = if self.language_model_selector_menu_handle.is_deployed() {
2262            (Color::Accent, IconName::ChevronUp)
2263        } else {
2264            (Color::Muted, IconName::ChevronDown)
2265        };
2266
2267        let provider_icon_element = match provider_icon {
2268            IconOrSvg::Svg(path) => Icon::from_external_svg(path),
2269            IconOrSvg::Icon(name) => Icon::new(name),
2270        }
2271        .color(color)
2272        .size(IconSize::XSmall);
2273
2274        let show_cycle_row = self
2275            .language_model_selector
2276            .read(cx)
2277            .delegate
2278            .favorites_count()
2279            > 1;
2280
2281        let tooltip = Tooltip::element({
2282            move |_, _cx| {
2283                ModelSelectorTooltip::new()
2284                    .show_cycle_row(show_cycle_row)
2285                    .into_any_element()
2286            }
2287        });
2288
2289        PickerPopoverMenu::new(
2290            self.language_model_selector.clone(),
2291            Button::new("active-model", model_name)
2292                .color(color)
2293                .label_size(LabelSize::Small)
2294                .start_icon(provider_icon_element)
2295                .end_icon(Icon::new(icon).color(color).size(IconSize::XSmall)),
2296            tooltip,
2297            gpui::Corner::BottomRight,
2298            cx,
2299        )
2300        .with_handle(self.language_model_selector_menu_handle.clone())
2301        .render(window, cx)
2302    }
2303
2304    fn render_last_error(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
2305        let last_error = self.last_error.as_ref()?;
2306
2307        Some(
2308            div()
2309                .absolute()
2310                .right_3()
2311                .bottom_12()
2312                .max_w_96()
2313                .py_2()
2314                .px_3()
2315                .elevation_2(cx)
2316                .occlude()
2317                .child(match last_error {
2318                    AssistError::PaymentRequired => self.render_payment_required_error(cx),
2319                    AssistError::Message(error_message) => {
2320                        self.render_assist_error(error_message, cx)
2321                    }
2322                })
2323                .into_any(),
2324        )
2325    }
2326
2327    fn render_payment_required_error(&self, cx: &mut Context<Self>) -> AnyElement {
2328        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.";
2329
2330        v_flex()
2331            .gap_0p5()
2332            .child(
2333                h_flex()
2334                    .gap_1p5()
2335                    .items_center()
2336                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2337                    .child(Label::new("Free Usage Exceeded").weight(FontWeight::MEDIUM)),
2338            )
2339            .child(
2340                div()
2341                    .id("error-message")
2342                    .max_h_24()
2343                    .overflow_y_scroll()
2344                    .child(Label::new(ERROR_MESSAGE)),
2345            )
2346            .child(
2347                h_flex()
2348                    .justify_end()
2349                    .mt_1()
2350                    .child(Button::new("subscribe", "Subscribe").on_click(cx.listener(
2351                        |this, _, _window, cx| {
2352                            this.last_error = None;
2353                            cx.open_url(&zed_urls::account_url(cx));
2354                            cx.notify();
2355                        },
2356                    )))
2357                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2358                        |this, _, _window, cx| {
2359                            this.last_error = None;
2360                            cx.notify();
2361                        },
2362                    ))),
2363            )
2364            .into_any()
2365    }
2366
2367    fn render_assist_error(
2368        &self,
2369        error_message: &SharedString,
2370        cx: &mut Context<Self>,
2371    ) -> AnyElement {
2372        v_flex()
2373            .gap_0p5()
2374            .child(
2375                h_flex()
2376                    .gap_1p5()
2377                    .items_center()
2378                    .child(Icon::new(IconName::XCircle).color(Color::Error))
2379                    .child(
2380                        Label::new("Error interacting with language model")
2381                            .weight(FontWeight::MEDIUM),
2382                    ),
2383            )
2384            .child(
2385                div()
2386                    .id("error-message")
2387                    .max_h_32()
2388                    .overflow_y_scroll()
2389                    .child(Label::new(error_message.clone())),
2390            )
2391            .child(
2392                h_flex()
2393                    .justify_end()
2394                    .mt_1()
2395                    .child(Button::new("dismiss", "Dismiss").on_click(cx.listener(
2396                        |this, _, _window, cx| {
2397                            this.last_error = None;
2398                            cx.notify();
2399                        },
2400                    ))),
2401            )
2402            .into_any()
2403    }
2404}
2405
2406/// Returns the contents of the *outermost* fenced code block that contains the given offset.
2407fn find_surrounding_code_block(snapshot: &BufferSnapshot, offset: usize) -> Option<Range<usize>> {
2408    const CODE_BLOCK_NODE: &str = "fenced_code_block";
2409    const CODE_BLOCK_CONTENT: &str = "code_fence_content";
2410
2411    let layer = snapshot.syntax_layers().next()?;
2412
2413    let root_node = layer.node();
2414    let mut cursor = root_node.walk();
2415
2416    // Go to the first child for the given offset
2417    while cursor.goto_first_child_for_byte(offset).is_some() {
2418        // If we're at the end of the node, go to the next one.
2419        // Example: if you have a fenced-code-block, and you're on the start of the line
2420        // right after the closing ```, you want to skip the fenced-code-block and
2421        // go to the next sibling.
2422        if cursor.node().end_byte() == offset {
2423            cursor.goto_next_sibling();
2424        }
2425
2426        if cursor.node().start_byte() > offset {
2427            break;
2428        }
2429
2430        // We found the fenced code block.
2431        if cursor.node().kind() == CODE_BLOCK_NODE {
2432            // Now we need to find the child node that contains the code.
2433            cursor.goto_first_child();
2434            loop {
2435                if cursor.node().kind() == CODE_BLOCK_CONTENT {
2436                    return Some(cursor.node().byte_range());
2437                }
2438                if !cursor.goto_next_sibling() {
2439                    break;
2440                }
2441            }
2442        }
2443    }
2444
2445    None
2446}
2447
2448fn render_thought_process_fold_icon_button(
2449    editor: WeakEntity<Editor>,
2450    status: ThoughtProcessStatus,
2451) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2452    Arc::new(move |fold_id, fold_range, _cx| {
2453        let editor = editor.clone();
2454
2455        let button = ButtonLike::new(fold_id).layer(ElevationIndex::ElevatedSurface);
2456        let button = match status {
2457            ThoughtProcessStatus::Pending => button
2458                .child(
2459                    Icon::new(IconName::ToolThink)
2460                        .size(IconSize::Small)
2461                        .color(Color::Muted),
2462                )
2463                .child(
2464                    Label::new("Thinking…").color(Color::Muted).with_animation(
2465                        "pulsating-label",
2466                        Animation::new(Duration::from_secs(2))
2467                            .repeat()
2468                            .with_easing(pulsating_between(0.4, 0.8)),
2469                        |label, delta| label.alpha(delta),
2470                    ),
2471                ),
2472            ThoughtProcessStatus::Completed => button
2473                .style(ButtonStyle::Filled)
2474                .child(Icon::new(IconName::ToolThink).size(IconSize::Small))
2475                .child(Label::new("Thought Process").single_line()),
2476        };
2477
2478        button
2479            .on_click(move |_, window, cx| {
2480                editor
2481                    .update(cx, |editor, cx| {
2482                        let buffer_start = fold_range
2483                            .start
2484                            .to_point(&editor.buffer().read(cx).read(cx));
2485                        let buffer_row = MultiBufferRow(buffer_start.row);
2486                        editor.unfold_at(buffer_row, window, cx);
2487                    })
2488                    .ok();
2489            })
2490            .into_any_element()
2491    })
2492}
2493
2494fn render_fold_icon_button(
2495    editor: WeakEntity<Editor>,
2496    icon_path: SharedString,
2497    label: SharedString,
2498) -> Arc<dyn Send + Sync + Fn(FoldId, Range<Anchor>, &mut App) -> AnyElement> {
2499    Arc::new(move |fold_id, fold_range, _cx| {
2500        let editor = editor.clone();
2501        ButtonLike::new(fold_id)
2502            .style(ButtonStyle::Filled)
2503            .layer(ElevationIndex::ElevatedSurface)
2504            .child(Icon::from_path(icon_path.clone()))
2505            .child(Label::new(label.clone()).single_line())
2506            .on_click(move |_, window, cx| {
2507                editor
2508                    .update(cx, |editor, cx| {
2509                        let buffer_start = fold_range
2510                            .start
2511                            .to_point(&editor.buffer().read(cx).read(cx));
2512                        let buffer_row = MultiBufferRow(buffer_start.row);
2513                        editor.unfold_at(buffer_row, window, cx);
2514                    })
2515                    .ok();
2516            })
2517            .into_any_element()
2518    })
2519}
2520
2521type ToggleFold = Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>;
2522
2523fn render_slash_command_output_toggle(
2524    row: MultiBufferRow,
2525    is_folded: bool,
2526    fold: ToggleFold,
2527    _window: &mut Window,
2528    _cx: &mut App,
2529) -> AnyElement {
2530    Disclosure::new(
2531        ("slash-command-output-fold-indicator", row.0 as u64),
2532        !is_folded,
2533    )
2534    .toggle_state(is_folded)
2535    .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2536    .into_any_element()
2537}
2538
2539pub fn fold_toggle(
2540    name: &'static str,
2541) -> impl Fn(
2542    MultiBufferRow,
2543    bool,
2544    Arc<dyn Fn(bool, &mut Window, &mut App) + Send + Sync>,
2545    &mut Window,
2546    &mut App,
2547) -> AnyElement {
2548    move |row, is_folded, fold, _window, _cx| {
2549        Disclosure::new((name, row.0 as u64), !is_folded)
2550            .toggle_state(is_folded)
2551            .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2552            .into_any_element()
2553    }
2554}
2555
2556fn quote_selection_fold_placeholder(title: String, editor: WeakEntity<Editor>) -> FoldPlaceholder {
2557    FoldPlaceholder {
2558        render: Arc::new({
2559            move |fold_id, fold_range, _cx| {
2560                let editor = editor.clone();
2561                ButtonLike::new(fold_id)
2562                    .style(ButtonStyle::Filled)
2563                    .layer(ElevationIndex::ElevatedSurface)
2564                    .child(Icon::new(IconName::TextSnippet))
2565                    .child(Label::new(title.clone()).single_line())
2566                    .on_click(move |_, window, cx| {
2567                        editor
2568                            .update(cx, |editor, cx| {
2569                                let buffer_start = fold_range
2570                                    .start
2571                                    .to_point(&editor.buffer().read(cx).read(cx));
2572                                let buffer_row = MultiBufferRow(buffer_start.row);
2573                                editor.unfold_at(buffer_row, window, cx);
2574                            })
2575                            .ok();
2576                    })
2577                    .into_any_element()
2578            }
2579        }),
2580        merge_adjacent: false,
2581        ..Default::default()
2582    }
2583}
2584
2585fn render_quote_selection_output_toggle(
2586    row: MultiBufferRow,
2587    is_folded: bool,
2588    fold: ToggleFold,
2589    _window: &mut Window,
2590    _cx: &mut App,
2591) -> AnyElement {
2592    Disclosure::new(("quote-selection-indicator", row.0 as u64), !is_folded)
2593        .toggle_state(is_folded)
2594        .on_click(move |_e, window, cx| fold(!is_folded, window, cx))
2595        .into_any_element()
2596}
2597
2598fn render_pending_slash_command_gutter_decoration(
2599    row: MultiBufferRow,
2600    status: &PendingSlashCommandStatus,
2601    confirm_command: Arc<dyn Fn(&mut Window, &mut App)>,
2602) -> AnyElement {
2603    let mut icon = IconButton::new(
2604        ("slash-command-gutter-decoration", row.0),
2605        ui::IconName::TriangleRight,
2606    )
2607    .on_click(move |_e, window, cx| confirm_command(window, cx))
2608    .icon_size(ui::IconSize::Small)
2609    .size(ui::ButtonSize::None);
2610
2611    match status {
2612        PendingSlashCommandStatus::Idle => {
2613            icon = icon.icon_color(Color::Muted);
2614        }
2615        PendingSlashCommandStatus::Running { .. } => {
2616            icon = icon.toggle_state(true);
2617        }
2618        PendingSlashCommandStatus::Error(_) => icon = icon.icon_color(Color::Error),
2619    }
2620
2621    icon.into_any_element()
2622}
2623
2624#[derive(Debug, Clone, Serialize, Deserialize)]
2625struct CopyMetadata {
2626    creases: Vec<SelectedCreaseMetadata>,
2627}
2628
2629#[derive(Debug, Clone, Serialize, Deserialize)]
2630struct SelectedCreaseMetadata {
2631    range_relative_to_selection: Range<usize>,
2632    crease: CreaseMetadata,
2633}
2634
2635impl EventEmitter<EditorEvent> for TextThreadEditor {}
2636impl EventEmitter<SearchEvent> for TextThreadEditor {}
2637
2638impl Render for TextThreadEditor {
2639    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
2640        let language_model_selector = self.language_model_selector_menu_handle.clone();
2641
2642        v_flex()
2643            .key_context("ContextEditor")
2644            .capture_action(cx.listener(TextThreadEditor::cancel))
2645            .capture_action(cx.listener(TextThreadEditor::save))
2646            .capture_action(cx.listener(TextThreadEditor::copy))
2647            .capture_action(cx.listener(TextThreadEditor::cut))
2648            .capture_action(cx.listener(TextThreadEditor::paste))
2649            .on_action(cx.listener(TextThreadEditor::paste_raw))
2650            .capture_action(cx.listener(TextThreadEditor::cycle_message_role))
2651            .capture_action(cx.listener(TextThreadEditor::confirm_command))
2652            .on_action(cx.listener(TextThreadEditor::assist))
2653            .on_action(cx.listener(TextThreadEditor::split))
2654            .on_action(move |_: &ToggleModelSelector, window, cx| {
2655                language_model_selector.toggle(window, cx);
2656            })
2657            .on_action(cx.listener(|this, _: &CycleFavoriteModels, window, cx| {
2658                this.language_model_selector.update(cx, |selector, cx| {
2659                    selector.delegate.cycle_favorite_models(window, cx);
2660                });
2661            }))
2662            .size_full()
2663            .child(
2664                div()
2665                    .flex_grow()
2666                    .bg(cx.theme().colors().editor_background)
2667                    .child(self.editor.clone()),
2668            )
2669            .children(self.render_last_error(cx))
2670            .child(
2671                h_flex()
2672                    .relative()
2673                    .py_2()
2674                    .pl_1p5()
2675                    .pr_2()
2676                    .w_full()
2677                    .justify_between()
2678                    .border_t_1()
2679                    .border_color(cx.theme().colors().border_variant)
2680                    .bg(cx.theme().colors().editor_background)
2681                    .child(
2682                        h_flex()
2683                            .gap_0p5()
2684                            .child(self.render_inject_context_menu(cx)),
2685                    )
2686                    .child(
2687                        h_flex()
2688                            .gap_2p5()
2689                            .children(self.render_remaining_tokens(cx))
2690                            .child(
2691                                h_flex()
2692                                    .gap_1()
2693                                    .child(self.render_language_model_selector(window, cx))
2694                                    .child(self.render_send_button(window, cx)),
2695                            ),
2696                    ),
2697            )
2698    }
2699}
2700
2701impl Focusable for TextThreadEditor {
2702    fn focus_handle(&self, cx: &App) -> FocusHandle {
2703        self.editor.focus_handle(cx)
2704    }
2705}
2706
2707impl Item for TextThreadEditor {
2708    type Event = editor::EditorEvent;
2709
2710    fn tab_content_text(&self, _detail: usize, cx: &App) -> SharedString {
2711        util::truncate_and_trailoff(&self.title(cx), MAX_TAB_TITLE_LEN).into()
2712    }
2713
2714    fn to_item_events(event: &Self::Event, f: &mut dyn FnMut(item::ItemEvent)) {
2715        match event {
2716            EditorEvent::Edited { .. } => {
2717                f(item::ItemEvent::Edit);
2718            }
2719            EditorEvent::TitleChanged => {
2720                f(item::ItemEvent::UpdateTab);
2721            }
2722            _ => {}
2723        }
2724    }
2725
2726    fn tab_tooltip_text(&self, cx: &App) -> Option<SharedString> {
2727        Some(self.title(cx).to_string().into())
2728    }
2729
2730    fn as_searchable(
2731        &self,
2732        handle: &Entity<Self>,
2733        _: &App,
2734    ) -> Option<Box<dyn SearchableItemHandle>> {
2735        Some(Box::new(handle.clone()))
2736    }
2737
2738    fn set_nav_history(
2739        &mut self,
2740        nav_history: pane::ItemNavHistory,
2741        window: &mut Window,
2742        cx: &mut Context<Self>,
2743    ) {
2744        self.editor.update(cx, |editor, cx| {
2745            Item::set_nav_history(editor, nav_history, window, cx)
2746        })
2747    }
2748
2749    fn navigate(
2750        &mut self,
2751        data: Arc<dyn Any + Send>,
2752        window: &mut Window,
2753        cx: &mut Context<Self>,
2754    ) -> bool {
2755        self.editor
2756            .update(cx, |editor, cx| Item::navigate(editor, data, window, cx))
2757    }
2758
2759    fn deactivated(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2760        self.editor
2761            .update(cx, |editor, cx| Item::deactivated(editor, window, cx))
2762    }
2763
2764    fn act_as_type<'a>(
2765        &'a self,
2766        type_id: TypeId,
2767        self_handle: &'a Entity<Self>,
2768        _: &'a App,
2769    ) -> Option<gpui::AnyEntity> {
2770        if type_id == TypeId::of::<Self>() {
2771            Some(self_handle.clone().into())
2772        } else if type_id == TypeId::of::<Editor>() {
2773            Some(self.editor.clone().into())
2774        } else {
2775            None
2776        }
2777    }
2778
2779    fn include_in_nav_history() -> bool {
2780        false
2781    }
2782}
2783
2784impl SearchableItem for TextThreadEditor {
2785    type Match = <Editor as SearchableItem>::Match;
2786
2787    fn clear_matches(&mut self, window: &mut Window, cx: &mut Context<Self>) {
2788        self.editor.update(cx, |editor, cx| {
2789            editor.clear_matches(window, cx);
2790        });
2791    }
2792
2793    fn update_matches(
2794        &mut self,
2795        matches: &[Self::Match],
2796        active_match_index: Option<usize>,
2797        token: SearchToken,
2798        window: &mut Window,
2799        cx: &mut Context<Self>,
2800    ) {
2801        self.editor.update(cx, |editor, cx| {
2802            editor.update_matches(matches, active_match_index, token, window, cx)
2803        });
2804    }
2805
2806    fn query_suggestion(&mut self, window: &mut Window, cx: &mut Context<Self>) -> String {
2807        self.editor
2808            .update(cx, |editor, cx| editor.query_suggestion(window, cx))
2809    }
2810
2811    fn activate_match(
2812        &mut self,
2813        index: usize,
2814        matches: &[Self::Match],
2815        token: SearchToken,
2816        window: &mut Window,
2817        cx: &mut Context<Self>,
2818    ) {
2819        self.editor.update(cx, |editor, cx| {
2820            editor.activate_match(index, matches, token, window, cx);
2821        });
2822    }
2823
2824    fn select_matches(
2825        &mut self,
2826        matches: &[Self::Match],
2827        token: SearchToken,
2828        window: &mut Window,
2829        cx: &mut Context<Self>,
2830    ) {
2831        self.editor.update(cx, |editor, cx| {
2832            editor.select_matches(matches, token, window, cx)
2833        });
2834    }
2835
2836    fn replace(
2837        &mut self,
2838        identifier: &Self::Match,
2839        query: &project::search::SearchQuery,
2840        token: SearchToken,
2841        window: &mut Window,
2842        cx: &mut Context<Self>,
2843    ) {
2844        self.editor.update(cx, |editor, cx| {
2845            editor.replace(identifier, query, token, window, cx)
2846        });
2847    }
2848
2849    fn find_matches(
2850        &mut self,
2851        query: Arc<project::search::SearchQuery>,
2852        window: &mut Window,
2853        cx: &mut Context<Self>,
2854    ) -> Task<Vec<Self::Match>> {
2855        self.editor
2856            .update(cx, |editor, cx| editor.find_matches(query, window, cx))
2857    }
2858
2859    fn active_match_index(
2860        &mut self,
2861        direction: Direction,
2862        matches: &[Self::Match],
2863        token: SearchToken,
2864        window: &mut Window,
2865        cx: &mut Context<Self>,
2866    ) -> Option<usize> {
2867        self.editor.update(cx, |editor, cx| {
2868            editor.active_match_index(direction, matches, token, window, cx)
2869        })
2870    }
2871}
2872
2873impl FollowableItem for TextThreadEditor {
2874    fn remote_id(&self) -> Option<workspace::ViewId> {
2875        self.remote_id
2876    }
2877
2878    fn to_state_proto(&self, window: &mut Window, cx: &mut App) -> Option<proto::view::Variant> {
2879        let context_id = self.text_thread.read(cx).id().to_proto();
2880        let editor_proto = self
2881            .editor
2882            .update(cx, |editor, cx| editor.to_state_proto(window, cx));
2883        Some(proto::view::Variant::ContextEditor(
2884            proto::view::ContextEditor {
2885                context_id,
2886                editor: if let Some(proto::view::Variant::Editor(proto)) = editor_proto {
2887                    Some(proto)
2888                } else {
2889                    None
2890                },
2891            },
2892        ))
2893    }
2894
2895    fn from_state_proto(
2896        workspace: Entity<Workspace>,
2897        id: workspace::ViewId,
2898        state: &mut Option<proto::view::Variant>,
2899        window: &mut Window,
2900        cx: &mut App,
2901    ) -> Option<Task<Result<Entity<Self>>>> {
2902        let proto::view::Variant::ContextEditor(_) = state.as_ref()? else {
2903            return None;
2904        };
2905        let Some(proto::view::Variant::ContextEditor(state)) = state.take() else {
2906            unreachable!()
2907        };
2908
2909        let text_thread_id = TextThreadId::from_proto(state.context_id);
2910        let editor_state = state.editor?;
2911
2912        let project = workspace.read(cx).project().clone();
2913        let agent_panel_delegate = <dyn AgentPanelDelegate>::try_global(cx)?;
2914
2915        let text_thread_editor_task = workspace.update(cx, |workspace, cx| {
2916            agent_panel_delegate.open_remote_text_thread(workspace, text_thread_id, window, cx)
2917        });
2918
2919        Some(window.spawn(cx, async move |cx| {
2920            let text_thread_editor = text_thread_editor_task.await?;
2921            text_thread_editor
2922                .update_in(cx, |text_thread_editor, window, cx| {
2923                    text_thread_editor.remote_id = Some(id);
2924                    text_thread_editor.editor.update(cx, |editor, cx| {
2925                        editor.apply_update_proto(
2926                            &project,
2927                            proto::update_view::Variant::Editor(proto::update_view::Editor {
2928                                selections: editor_state.selections,
2929                                pending_selection: editor_state.pending_selection,
2930                                scroll_top_anchor: editor_state.scroll_top_anchor,
2931                                scroll_x: editor_state.scroll_y,
2932                                scroll_y: editor_state.scroll_y,
2933                                ..Default::default()
2934                            }),
2935                            window,
2936                            cx,
2937                        )
2938                    })
2939                })?
2940                .await?;
2941            Ok(text_thread_editor)
2942        }))
2943    }
2944
2945    fn to_follow_event(event: &Self::Event) -> Option<item::FollowEvent> {
2946        Editor::to_follow_event(event)
2947    }
2948
2949    fn add_event_to_update_proto(
2950        &self,
2951        event: &Self::Event,
2952        update: &mut Option<proto::update_view::Variant>,
2953        window: &mut Window,
2954        cx: &mut App,
2955    ) -> bool {
2956        self.editor.update(cx, |editor, cx| {
2957            editor.add_event_to_update_proto(event, update, window, cx)
2958        })
2959    }
2960
2961    fn apply_update_proto(
2962        &mut self,
2963        project: &Entity<Project>,
2964        message: proto::update_view::Variant,
2965        window: &mut Window,
2966        cx: &mut Context<Self>,
2967    ) -> Task<Result<()>> {
2968        self.editor.update(cx, |editor, cx| {
2969            editor.apply_update_proto(project, message, window, cx)
2970        })
2971    }
2972
2973    fn is_project_item(&self, _window: &Window, _cx: &App) -> bool {
2974        true
2975    }
2976
2977    fn set_leader_id(
2978        &mut self,
2979        leader_id: Option<CollaboratorId>,
2980        window: &mut Window,
2981        cx: &mut Context<Self>,
2982    ) {
2983        self.editor
2984            .update(cx, |editor, cx| editor.set_leader_id(leader_id, window, cx))
2985    }
2986
2987    fn dedup(&self, existing: &Self, _window: &Window, cx: &App) -> Option<item::Dedup> {
2988        if existing.text_thread.read(cx).id() == self.text_thread.read(cx).id() {
2989            Some(item::Dedup::KeepExisting)
2990        } else {
2991            None
2992        }
2993    }
2994}
2995
2996enum PendingSlashCommand {}
2997
2998fn invoked_slash_command_fold_placeholder(
2999    command_id: InvokedSlashCommandId,
3000    text_thread: WeakEntity<TextThread>,
3001) -> FoldPlaceholder {
3002    FoldPlaceholder {
3003        collapsed_text: None,
3004        constrain_width: false,
3005        merge_adjacent: false,
3006        render: Arc::new(move |fold_id, _, cx| {
3007            let Some(text_thread) = text_thread.upgrade() else {
3008                return Empty.into_any();
3009            };
3010
3011            let Some(command) = text_thread.read(cx).invoked_slash_command(&command_id) else {
3012                return Empty.into_any();
3013            };
3014
3015            h_flex()
3016                .id(fold_id)
3017                .px_1()
3018                .ml_6()
3019                .gap_2()
3020                .bg(cx.theme().colors().surface_background)
3021                .rounded_sm()
3022                .child(Label::new(format!("/{}", command.name)))
3023                .map(|parent| match &command.status {
3024                    InvokedSlashCommandStatus::Running(_) => {
3025                        parent.child(Icon::new(IconName::ArrowCircle).with_rotate_animation(4))
3026                    }
3027                    InvokedSlashCommandStatus::Error(message) => parent.child(
3028                        Label::new(format!("error: {message}"))
3029                            .single_line()
3030                            .color(Color::Error),
3031                    ),
3032                    InvokedSlashCommandStatus::Finished => parent,
3033                })
3034                .into_any_element()
3035        }),
3036        type_tag: Some(TypeId::of::<PendingSlashCommand>()),
3037    }
3038}
3039
3040enum TokenState {
3041    NoTokensLeft {
3042        max_token_count: u64,
3043        token_count: u64,
3044    },
3045    HasMoreTokens {
3046        max_token_count: u64,
3047        token_count: u64,
3048        over_warn_threshold: bool,
3049    },
3050}
3051
3052fn token_state(text_thread: &Entity<TextThread>, cx: &App) -> Option<TokenState> {
3053    const WARNING_TOKEN_THRESHOLD: f32 = 0.8;
3054
3055    let model = LanguageModelRegistry::read_global(cx)
3056        .default_model()?
3057        .model;
3058    let token_count = text_thread.read(cx).token_count()?;
3059    let max_token_count = model.max_token_count();
3060    let token_state = if max_token_count.saturating_sub(token_count) == 0 {
3061        TokenState::NoTokensLeft {
3062            max_token_count,
3063            token_count,
3064        }
3065    } else {
3066        let over_warn_threshold =
3067            token_count as f32 / max_token_count as f32 >= WARNING_TOKEN_THRESHOLD;
3068        TokenState::HasMoreTokens {
3069            max_token_count,
3070            token_count,
3071            over_warn_threshold,
3072        }
3073    };
3074    Some(token_state)
3075}
3076
3077fn size_for_image(data: &RenderImage, max_size: Size<Pixels>) -> Size<Pixels> {
3078    let image_size = data
3079        .size(0)
3080        .map(|dimension| Pixels::from(u32::from(dimension)));
3081    let image_ratio = image_size.width / image_size.height;
3082    let bounds_ratio = max_size.width / max_size.height;
3083
3084    if image_size.width > max_size.width || image_size.height > max_size.height {
3085        if bounds_ratio > image_ratio {
3086            size(
3087                image_size.width * (max_size.height / image_size.height),
3088                max_size.height,
3089            )
3090        } else {
3091            size(
3092                max_size.width,
3093                image_size.height * (max_size.width / image_size.width),
3094            )
3095        }
3096    } else {
3097        size(image_size.width, image_size.height)
3098    }
3099}
3100
3101pub fn humanize_token_count(count: u64) -> String {
3102    match count {
3103        0..=999 => count.to_string(),
3104        1000..=9999 => {
3105            let thousands = count / 1000;
3106            let hundreds = (count % 1000 + 50) / 100;
3107            if hundreds == 0 {
3108                format!("{}k", thousands)
3109            } else if hundreds == 10 {
3110                format!("{}k", thousands + 1)
3111            } else {
3112                format!("{}.{}k", thousands, hundreds)
3113            }
3114        }
3115        1_000_000..=9_999_999 => {
3116            let millions = count / 1_000_000;
3117            let hundred_thousands = (count % 1_000_000 + 50_000) / 100_000;
3118            if hundred_thousands == 0 {
3119                format!("{}M", millions)
3120            } else if hundred_thousands == 10 {
3121                format!("{}M", millions + 1)
3122            } else {
3123                format!("{}.{}M", millions, hundred_thousands)
3124            }
3125        }
3126        10_000_000.. => format!("{}M", (count + 500_000) / 1_000_000),
3127        _ => format!("{}k", (count + 500) / 1000),
3128    }
3129}
3130
3131pub fn make_lsp_adapter_delegate(
3132    project: &Entity<Project>,
3133    cx: &mut App,
3134) -> Result<Option<Arc<dyn LspAdapterDelegate>>> {
3135    project.update(cx, |project, cx| {
3136        // TODO: Find the right worktree.
3137        let Some(worktree) = project.worktrees(cx).next() else {
3138            return Ok(None::<Arc<dyn LspAdapterDelegate>>);
3139        };
3140        let http_client = project.client().http_client();
3141        project.lsp_store().update(cx, |_, cx| {
3142            Ok(Some(LocalLspAdapterDelegate::new(
3143                project.languages().clone(),
3144                project.environment(),
3145                cx.weak_entity(),
3146                &worktree,
3147                http_client,
3148                project.fs().clone(),
3149                cx,
3150            ) as Arc<dyn LspAdapterDelegate>))
3151        })
3152    })
3153}
3154
3155#[cfg(test)]
3156mod tests {
3157    use super::*;
3158    use editor::{MultiBufferOffset, SelectionEffects};
3159    use fs::FakeFs;
3160    use gpui::{App, TestAppContext, VisualTestContext};
3161    use indoc::indoc;
3162    use language::{Buffer, LanguageRegistry};
3163    use pretty_assertions::assert_eq;
3164    use prompt_store::PromptBuilder;
3165    use text::OffsetRangeExt;
3166    use unindent::Unindent;
3167    use util::path;
3168    use workspace::MultiWorkspace;
3169
3170    #[gpui::test]
3171    async fn test_copy_paste_whole_message(cx: &mut TestAppContext) {
3172        let (context, text_thread_editor, mut cx) = setup_text_thread_editor_text(vec![
3173            (Role::User, "What is the Zed editor?"),
3174            (
3175                Role::Assistant,
3176                "Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.",
3177            ),
3178            (Role::User, ""),
3179        ],cx).await;
3180
3181        // Select & Copy whole user message
3182        assert_copy_paste_text_thread_editor(
3183            &text_thread_editor,
3184            message_range(&context, 0, &mut cx),
3185            indoc! {"
3186                What is the Zed editor?
3187                Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
3188                What is the Zed editor?
3189            "},
3190            &mut cx,
3191        );
3192
3193        // Select & Copy whole assistant message
3194        assert_copy_paste_text_thread_editor(
3195            &text_thread_editor,
3196            message_range(&context, 1, &mut cx),
3197            indoc! {"
3198                What is the Zed editor?
3199                Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
3200                What is the Zed editor?
3201                Zed is a modern, high-performance code editor designed from the ground up for speed and collaboration.
3202            "},
3203            &mut cx,
3204        );
3205    }
3206
3207    #[gpui::test]
3208    async fn test_copy_paste_no_selection(cx: &mut TestAppContext) {
3209        let (context, text_thread_editor, mut cx) = setup_text_thread_editor_text(
3210            vec![
3211                (Role::User, "user1"),
3212                (Role::Assistant, "assistant1"),
3213                (Role::Assistant, "assistant2"),
3214                (Role::User, ""),
3215            ],
3216            cx,
3217        )
3218        .await;
3219
3220        // Copy and paste first assistant message
3221        let message_2_range = message_range(&context, 1, &mut cx);
3222        assert_copy_paste_text_thread_editor(
3223            &text_thread_editor,
3224            message_2_range.start..message_2_range.start,
3225            indoc! {"
3226                user1
3227                assistant1
3228                assistant2
3229                assistant1
3230            "},
3231            &mut cx,
3232        );
3233
3234        // Copy and cut second assistant message
3235        let message_3_range = message_range(&context, 2, &mut cx);
3236        assert_copy_paste_text_thread_editor(
3237            &text_thread_editor,
3238            message_3_range.start..message_3_range.start,
3239            indoc! {"
3240                user1
3241                assistant1
3242                assistant2
3243                assistant1
3244                assistant2
3245            "},
3246            &mut cx,
3247        );
3248    }
3249
3250    #[gpui::test]
3251    fn test_find_code_blocks(cx: &mut App) {
3252        let markdown = languages::language("markdown", tree_sitter_md::LANGUAGE.into());
3253
3254        let buffer = cx.new(|cx| {
3255            let text = r#"
3256                line 0
3257                line 1
3258                ```rust
3259                fn main() {}
3260                ```
3261                line 5
3262                line 6
3263                line 7
3264                ```go
3265                func main() {}
3266                ```
3267                line 11
3268                ```
3269                this is plain text code block
3270                ```
3271
3272                ```go
3273                func another() {}
3274                ```
3275                line 19
3276            "#
3277            .unindent();
3278            let mut buffer = Buffer::local(text, cx);
3279            buffer.set_language(Some(markdown.clone()), cx);
3280            buffer
3281        });
3282        let snapshot = buffer.read(cx).snapshot();
3283
3284        let code_blocks = vec![
3285            Point::new(3, 0)..Point::new(4, 0),
3286            Point::new(9, 0)..Point::new(10, 0),
3287            Point::new(13, 0)..Point::new(14, 0),
3288            Point::new(17, 0)..Point::new(18, 0),
3289        ]
3290        .into_iter()
3291        .map(|range| snapshot.point_to_offset(range.start)..snapshot.point_to_offset(range.end))
3292        .collect::<Vec<_>>();
3293
3294        let expected_results = vec![
3295            (0, None),
3296            (1, None),
3297            (2, Some(code_blocks[0].clone())),
3298            (3, Some(code_blocks[0].clone())),
3299            (4, Some(code_blocks[0].clone())),
3300            (5, None),
3301            (6, None),
3302            (7, None),
3303            (8, Some(code_blocks[1].clone())),
3304            (9, Some(code_blocks[1].clone())),
3305            (10, Some(code_blocks[1].clone())),
3306            (11, None),
3307            (12, Some(code_blocks[2].clone())),
3308            (13, Some(code_blocks[2].clone())),
3309            (14, Some(code_blocks[2].clone())),
3310            (15, None),
3311            (16, Some(code_blocks[3].clone())),
3312            (17, Some(code_blocks[3].clone())),
3313            (18, Some(code_blocks[3].clone())),
3314            (19, None),
3315        ];
3316
3317        for (row, expected) in expected_results {
3318            let offset = snapshot.point_to_offset(Point::new(row, 0));
3319            let range = find_surrounding_code_block(&snapshot, offset);
3320            assert_eq!(range, expected, "unexpected result on row {:?}", row);
3321        }
3322    }
3323
3324    async fn setup_text_thread_editor_text(
3325        messages: Vec<(Role, &str)>,
3326        cx: &mut TestAppContext,
3327    ) -> (
3328        Entity<TextThread>,
3329        Entity<TextThreadEditor>,
3330        VisualTestContext,
3331    ) {
3332        cx.update(init_test);
3333
3334        let fs = FakeFs::new(cx.executor());
3335        let text_thread = create_text_thread_with_messages(messages, cx);
3336
3337        let project = Project::test(fs.clone(), [path!("/test").as_ref()], cx).await;
3338        let window_handle =
3339            cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
3340        let workspace = window_handle
3341            .read_with(cx, |mw, _| mw.workspace().clone())
3342            .unwrap();
3343        let mut cx = VisualTestContext::from_window(window_handle.into(), cx);
3344
3345        let weak_workspace = workspace.downgrade();
3346        let text_thread_editor = workspace.update_in(&mut cx, |_, window, cx| {
3347            cx.new(|cx| {
3348                TextThreadEditor::for_text_thread(
3349                    text_thread.clone(),
3350                    fs,
3351                    weak_workspace,
3352                    project,
3353                    None,
3354                    window,
3355                    cx,
3356                )
3357            })
3358        });
3359
3360        (text_thread, text_thread_editor, cx)
3361    }
3362
3363    fn message_range(
3364        text_thread: &Entity<TextThread>,
3365        message_ix: usize,
3366        cx: &mut TestAppContext,
3367    ) -> Range<MultiBufferOffset> {
3368        let range = text_thread.update(cx, |text_thread, cx| {
3369            text_thread
3370                .messages(cx)
3371                .nth(message_ix)
3372                .unwrap()
3373                .anchor_range
3374                .to_offset(&text_thread.buffer().read(cx).snapshot())
3375        });
3376        MultiBufferOffset(range.start)..MultiBufferOffset(range.end)
3377    }
3378
3379    fn assert_copy_paste_text_thread_editor<T: editor::ToOffset>(
3380        text_thread_editor: &Entity<TextThreadEditor>,
3381        range: Range<T>,
3382        expected_text: &str,
3383        cx: &mut VisualTestContext,
3384    ) {
3385        text_thread_editor.update_in(cx, |text_thread_editor, window, cx| {
3386            text_thread_editor.editor.update(cx, |editor, cx| {
3387                editor.change_selections(SelectionEffects::no_scroll(), window, cx, |s| {
3388                    s.select_ranges([range])
3389                });
3390            });
3391
3392            text_thread_editor.copy(&Default::default(), window, cx);
3393
3394            text_thread_editor.editor.update(cx, |editor, cx| {
3395                editor.move_to_end(&Default::default(), window, cx);
3396            });
3397
3398            text_thread_editor.paste(&Default::default(), window, cx);
3399
3400            text_thread_editor.editor.update(cx, |editor, cx| {
3401                assert_eq!(editor.text(cx), expected_text);
3402            });
3403        });
3404    }
3405
3406    fn create_text_thread_with_messages(
3407        mut messages: Vec<(Role, &str)>,
3408        cx: &mut TestAppContext,
3409    ) -> Entity<TextThread> {
3410        let registry = Arc::new(LanguageRegistry::test(cx.executor()));
3411        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3412        cx.new(|cx| {
3413            let mut text_thread = TextThread::local(
3414                registry,
3415                prompt_builder.clone(),
3416                Arc::new(SlashCommandWorkingSet::default()),
3417                cx,
3418            );
3419            let mut message_1 = text_thread.messages(cx).next().unwrap();
3420            let (role, text) = messages.remove(0);
3421
3422            loop {
3423                if role == message_1.role {
3424                    text_thread.buffer().update(cx, |buffer, cx| {
3425                        buffer.edit([(message_1.offset_range, text)], None, cx);
3426                    });
3427                    break;
3428                }
3429                let mut ids = HashSet::default();
3430                ids.insert(message_1.id);
3431                text_thread.cycle_message_roles(ids, cx);
3432                message_1 = text_thread.messages(cx).next().unwrap();
3433            }
3434
3435            let mut last_message_id = message_1.id;
3436            for (role, text) in messages {
3437                text_thread.insert_message_after(last_message_id, role, MessageStatus::Done, cx);
3438                let message = text_thread.messages(cx).last().unwrap();
3439                last_message_id = message.id;
3440                text_thread.buffer().update(cx, |buffer, cx| {
3441                    buffer.edit([(message.offset_range, text)], None, cx);
3442                })
3443            }
3444
3445            text_thread
3446        })
3447    }
3448
3449    fn init_test(cx: &mut App) {
3450        let settings_store = SettingsStore::test(cx);
3451        prompt_store::init(cx);
3452        editor::init(cx);
3453        LanguageModelRegistry::test(cx);
3454        cx.set_global(settings_store);
3455
3456        theme::init(theme::LoadThemes::JustBase, cx);
3457    }
3458
3459    #[gpui::test]
3460    async fn test_quote_terminal_text(cx: &mut TestAppContext) {
3461        let (_context, text_thread_editor, mut cx) =
3462            setup_text_thread_editor_text(vec![(Role::User, "")], cx).await;
3463
3464        let terminal_output = "$ ls -la\ntotal 0\ndrwxr-xr-x  2 user user  40 Jan  1 00:00 .";
3465
3466        text_thread_editor.update_in(&mut cx, |text_thread_editor, window, cx| {
3467            text_thread_editor.quote_terminal_text(terminal_output.to_string(), window, cx);
3468
3469            text_thread_editor.editor.update(cx, |editor, cx| {
3470                let text = editor.text(cx);
3471                // The text should contain the terminal output wrapped in a code block
3472                assert!(
3473                    text.contains(&format!("```console\n{}\n```", terminal_output)),
3474                    "Terminal text should be wrapped in code block. Got: {}",
3475                    text
3476                );
3477            });
3478        });
3479    }
3480}