context_editor.rs

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