text_thread_editor.rs

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